多租户 SaaS 应用(CAP) · 2 · 基础实现(4/4)

项目

内容

官方仓库

SAP-samples/btp-cap-multitenant-saas

业务场景

把 CAP 应用改造成多租户 SaaS:租户订阅、隔离、按租户配置

技术栈

CAP(Node.js/Java)、mtxs、SaaS Registry、XSUAA、Cloud Foundry / Kyma

对应课程

CLD200、KYM400、BTP200

对应路径

第 2 条、第 7 条

为什么值得做:多租户是 SaaS 产品的分水岭。本案例实现了租户开通、隔离与升级机制, 用一个应用即可服务众多客户。

动手要点:

  • 理解 SaaS Registry 与租户感知应用之间的关系。

  • 研读 mta.yaml 与租户部署描述文件——大部分复杂度都集中在这里。

本页内容抓取自官方仓库 SAP-samples/btp-cap-multitenant-saas,共收录 3 篇官方文档(README 与 docs)。原仓库内容版权归 SAP SE,遵循其许可证。

资源概览

  • Kyma ✅

  • Cloud Foundry ❌

这个 SaaS 示例应用使用了多种 Kubernetes 资源以及自定义的 Kyma 资源定义。本章会简要介绍这些资源,并在需要时给出可进一步查阅的链接。

这些资源的完整细节都可以在网上找到。在本部分教程中,我们尝试结合具体场景说明各组件的用途——用的是我们自己的表述。因此请理解,我们的说明未必与所有资源的官方文档内容完全一致。如果发现任何出入,欢迎通过 pull request 提出修正或建议。

在下面的图示中,可以找到大部分本文档涉及的资源。有些资源被大多数 Pod 以类似方式使用,为了保证高层架构图的可读性,已将其从图中移除;它们的用法会在第二张图中说明。

资源细节架构图,展示示例应用各组件与请求的流动路径

我们的假设是:如果能结合示例场景理解所有这些资源的基本思想与概念,再去读那些全面但非常通用的官方文档就会轻松得多。如果你是 Kyma 和 Kubernetes 生态的新手(本项目起步时我们也是如此),那么聚焦一个具体示例的讲解,往往比通读大量通用资源文档更有帮助。如果你此前从未接触过 Kubernetes,建议先补充一些基础概念再继续。了解集群(Cluster)、节点(Node)、Pod,以及基本 Kubernetes 资源之间的关系,会让你接下来阅读本教程的内容顺畅许多。

Kyma 对象关系总览图,说明各类资源如何协同工作

在具备一些 Kubernetes 基础知识之后,我们强烈建议先从 Deployment 资源类型入手,接着了解 Istio Service Mesh,然后再深入 Service Account、Network Policy 或 Horizontal Pod Autoscaler 这类主题。你可以借助提供的高层架构图,跟随一个外部请求访问示例应用各组件的路径来学习。

引言到此为止。下面按字母顺序列出示例应用中使用的最重要的资源类型。动手试试,祝你玩得开心!

  • 资源概览

    • API Rule(API 规则)

    • Cluster Role(集群角色)

    • ConfigMap(配置映射)

    • Deployment(部署)

    • Istio Service Mesh(服务网格)

      • Istio 数据/流量流

      • Authorization Policy(授权策略)

      • Destination Rule(目标规则)

      • Request Authentication(请求认证)

      • Service Entry(服务条目)

      • Sidecar(边车)

      • Virtual Service(虚拟服务)

    • Job(任务)

    • Network Policy(网络策略)

    • Ory

    • Pod Autoscaler(Pod 自动扩缩容)

    • Pod Disruption Budget(Pod 中断预算)

    • Role Binding(角色绑定)

    • Secret(机密)

    • Service(服务)

    • Service Account(服务账户)

    • Service Binding(服务绑定)

    • Service Instance(服务实例)

API Rule(API 规则)

这一 Kyma 自定义资源可以简化工作负载的对外暴露。API Rule 会自动创建 Istio Virtual Service 和所谓的 Ory 规则。Virtual Service 负责转发经由所谓 Istio Ingress Gateway 到达的流量,Ory 则负责改写头部值,或施加 OAuth2、JWT 校验策略等访问策略。更多细节请查阅各组件的说明。

提示 - 本场景目前没有使用访问策略(access strategy),因为身份认证与授权都在 CAP 工作负载内部完成。订阅方 API Rule 中使用了 Ory Mutator 来设置自定义头部。

在示例中,Application Router、Backend Service、API Service 与 API Service Broker 都定义了 API Rule。只有 SAP API Management 的集成使用专用的 Virtual Service 定义,而不是 API Rule。原因是:API Rule 确实简化了工作负载的暴露过程,但它并不提供原生 Virtual Service 的全部能力(例如为同一请求主机配置不同的目标路由)。

示例

部署时,下面这个 Kyma API Rule 定义会创建一个 Istio Virtual Service 实例,为 cdomain-gateway(定义在 default 命名空间)这个 Istio Ingress Gateway 定义流量规则。该 Virtual Service 会把发往主机 susaas-router-default.sap-demo.com 的所有流量,路由到端口 5000 上的 Cluster IP Service susaas-router。

提示 - 基础版本并不包含自定义域名的使用,因此你环境里的 gateway 与 host 可能略有不同,会使用默认的 Kyma 域名。此外,你也可能看到在 host 字段中使用主机名而非 FQDN(完全限定域名)的 Virtual Service 示例。我们建议尽可能使用 FQDN,以避免由自动推断正确域名而引发的意外行为。

apiVersion: gateway.kyma-project.io/v1beta1
kind: APIRule
metadata:
  name: susaas-router
spec:
  # The API Rule will handle requests arriving for this Istio Gateway
  gateway: default/cdomain-gateway
  # The API Rule will handle all requests arriving for this host
  host: susaas-router-default.sap-demo.com
  rules:
	# Traffic on all paths will be routed to the Cluster IP service
    - methods:
        - GET
        - POST
        - PUT
        - DELETE
        - HEAD
      path: /.*
      # "allow" strategy will disable Ory Oathkeeper for target routing
      accessStrategies:
        - handler: allow
  # Cluster IP Service to which the traffic is routed
  service:
    name: susaas-router
    port: 5000

生成的 Virtual Service 如下所示;只要对相应的 API Rule 做了修改,它就会随之更新。

重要 - 由于 Virtual Service 会自动更新,请不要手动修改与 API Rule 关联的实例。如果 API Rule 的功能范围不够用,请改为创建专用的 Virtual Service!

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-router
spec:
  gateways:
    - default/cdomain-gateway
  hosts:
    - susaas-router-default.sap-demo.com
  http:
    - corsPolicy:
        allowMethods:
          - GET
          - POST
          - PUT
          - DELETE
          - PATCH
      headers:
        # Original target host is retained in header
        request:
          set:
            x-forwarded-host: susaas-router-default.sap-demo.com
      match:
        - uri:
            regex: /.*
      route:
        # Route traffic to the Cluster IP Service of the Application Router workload
        - destination:
            host: susaas-router.default.svc.cluster.local
            port:
              number: 5000
          weight: 100

租户开通期间为订阅方租户生成的 API Rule,会得到略有不同的 Virtual Service,因为它们需要满足一项额外要求:注入 x-custom-host 头部。借助该头部,可以使用自定义域名,而不必依赖那些通常冗长又随机的子账户子域名。

...
  try{
    const access_strategy = {
      path: '/.*',
      methods: ['GET','POST','PUT','PATCH','DELETE','HEAD'],
      accessStrategies: [{ handler: 'noop' }],
      // Mutator definitions result in Ory Mutators handled by Ory Oathkeeper
      mutators: [{
        handler: 'header',
        config: {
          // Custom Header injected into request by Ory Oathkeeper
          headers: {
            // Sample value - subscriber-a1b2c3-susaas-router-default.sap-demo.com
            "x-custom-host": `${subdomain}-${svcName}-${namespace}.${clusterDomain}`,
          }
        }
      }]
    };
...

基于上面的 Ory Mutator 定义,最终得到的 API Rule 与相应的 Virtual Service 大致如下。

API Rule

面向子域名为 subscriber-a1b2c3 的 SaaS 租户

apiVersion: gateway.kyma-project.io/v1beta1
kind: APIRule
metadata:
  name: susaas-tenant-e1771
spec:
  # Handle requests arriving for this Istio Gateway
  gateway: default/cdomain-gateway
  # Handle requests for this custom Subscriber subdomain
  host: subscriber.sap-demo.com
  rules:
    - methods:
        - GET
        - POST
        - PUT
        - DELETE
        - HEAD
      path: /.*
      accessStrategies:
        - handler: noop
      mutators:
        - config:
            headers:
              x-custom-host: subscriber-a1b2c3-susaas-router-default.sap-demo.com
          handler: header
      path: /.*
  # Cluster IP Service the traffic is routed after passing Ory Oathkeeper
  service:
    name: susaas-router
    port: 5000

Virtual Service

面向子域名为 subscriber-a1b2c3 的 SaaS 租户

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-tenant-e1771-25rzp
spec:
  gateways: ["default/cdomain-gateway"]
  hosts: ["subscriber.sap-demo.com"]
  http:
    - headers:
        # Original target host is retained in header
        request:
          set:
            x-forwarded-host: subscriber.sap-demo.com
      match:
        - uri:
            regex: /.*
      route:
        # Route traffic to the Cluster IP Service of Ory Oathkeeper
        # x-custom-host header added by Ory Oathkeeper
        - destination:
            host: ory-oathkeeper-proxy.kyma-system.svc.cluster.local
            port:
              number: 4455
          weight: 100

Ory Oathkeeper 会应用所定义的 mutator,设置 x-custom-host 头部,然后把流量转发到 Application Router 的 Cluster IP Service。结合 Application Router 的环境变量 EXTERNAL_REVERSE_PROXY,我们就可以为订阅方租户提供动态自定义域名,同时在 x-custom-host 头部中保留原始租户子域名,以满足从 TENANT_HOST_PATTERN 推导租户标识的要求。

提示
Tenant-Host-Pattern: (.*)-susaas-router-default.sap-demo.com
自定义域名:subscriber.sap-demo.com
X-Custom-Host: subscriber-a1b2c3-susaas-router-default.sap-demo.com
识别出的租户:subscriber-a1b2c3

请注意,Ory 已被列为将废弃的组件,头部 mutator 功能会在后续版本中被替换。可能的替代方案是使用 Istio 的相应特性。

Cluster Role(集群角色)

Cluster Role 用于为集群定义一组自定义权限。在示例场景中,它是运行时创建 API Rule 的关键。每当有新订阅方开通 Sustainable SaaS 应用时,运行时都会创建一条新的 API Rule。这条新规则会暴露一个可从公网访问的租户专属 URI(例如 customer-xyz.sap-demo.com)。如果在订阅时进行了配置,该 API Rule 及相应的(自动生成的)Virtual Service 将充当外部反向代理(External Reverse Proxy),允许你定义不一定与订阅方子账户子域名一致的自定义域名。

提示 - 更多细节可查看 /srv/utils/apiRule.js 中的实现。此外,Application Router 文档对 EXTERNAL_REVERSE_PROXY 标志有进一步说明,该标志用于启用反向代理功能。

自定义域名场景下的 Kyma 对象关系示意图

示例场景中所需的 Cluster Role 包含创建、删除和修改 API Rule 的权限。该 Cluster Role 通过所谓的 Role Binding 分配给一个专用 Service Account。在本例中,Cluster Role 绑定到一个 Service Account,而这个 Service Account 又被分配给 SaaS 后端应用的工作负载(Pod)。运行时,后端应用可以代表该 Service Account 与 Kyma 集群交互,因为相应的 Service Account token 会以“自动挂载”的方式挂载到工作负载中。

将 Service Account token 自动挂载到工作负载后,就可以按下面的方式获取连接集群 API 的凭据(Node.js):

  const kc = new k8s.KubeConfig();
  kc.loadFromCluster();
  ...

提示 - 想进一步了解 Service Account 如何绑定到工作负载、如何在运行时自动挂载 Service Account token,请参阅本教程的 Deployment 章节。

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: susaas-srv
rules:
  - apiGroups: ["gateway.kyma-project.io"]
    resources: ["apirules"]
    verbs:
      - create
      - delete
      - get
      - list
      - patch
      - update
      - watch
  - apiGroups:  ["gateway.kyma-project.io"]
    resources: ["apirules/status"]
    verbs: ["get"]

ConfigMap(配置映射)

ConfigMap 用于向工作负载提供额外的(配置)信息,例如本场景中 Service Broker 的配置细节。

apiVersion: v1
kind: ConfigMap
metadata:
  name: susaas-broker-config
data:
  serviceConfigs: | 
    {   
      "susaas-api-susaas-default-a1b2c3": {
        "extend_credentials": {
          "shared": {
              "apiUrl": "https://susaas-api-default.sap-demo.com"
            }
        },
        "extend_catalog": {
          "metadata": {
              "displayName": "Sustainable SaaS API"
          }
        }
      }
    }

ConfigMap 可以在工作负载或 Deployment 这类副本控制器定义中被引用。在示例场景中,ConfigMap 充当 Service Broker 某个环境变量(启动时必需)的动态内容提供者。借助 ConfigMap,我们可以通过 Helm 模板引用或 Deployment 专属变量(如命名空间,或 apiUrl 中的域名)让配置保持动态与灵活。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-broker
spec:
  ...
    spec:
      ...
      containers:
      - image: sap-demo/susaas-broker:latest
        ...
        env:
        - name: SBF_SERVICE_CONFIG
          valueFrom:
            configMapKeyRef:
              name: susaas-broker-config
              key: serviceConfigs

另一个有意思的场景是把 ConfigMap 挂载到容器的文件系统中。在示例场景里,API Service Broker 启动时需要访问一个 catalog.json 文件,其中包含可用服务计划的信息,这些内容无法通过环境变量提供。与之对应,环境变量 SBF_CATALOG_FILE 需要的是一个指向 catalog.json 文件的路径。

apiVersion: v1
kind: ConfigMap
metadata:
  name: susaas-broker-catalog
data:
  # File name which will be created when mounted to container file system
  catalog.json: | 
    {
        "services": [{
            ...

把该 ConfigMap 挂载到容器的文件系统后,会在 /etc/config 路径下生成相应的 catalog.json 文件,随后由环境变量引用该路径。

提示 - 文件名取自 ConfigMap 实例中的属性键 catalog.json。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-broker
spec:
  ...
    spec:
      ...
      containers:
      - image: sap-demo/susaas-broker:latest
        ...
        env:
        # Provide path of generated file to env variable
        - name: SBF_CATALOG_FILE
          value: "/etc/config/catalog.json"
        ...
        # Mount available volume to dedicated path
        volumeMounts:
        - name: susaas-broker-catalog
          mountPath: "/etc/config"
          readOnly: true
        ...
      ...
      # Define ConfigMap as volume in your workload
      volumes:
        - name: susaas-broker-catalog
          configMap: 
            name: susaas-broker-catalog

另外,你可能会问:为什么不直接把 catalog.json 打进 API Service Broker 的 Docker 镜像?上面的做法可以让 API Service Broker 的 Docker 镜像保持高度动态,并在部署时根据相应环境信息传入所需的实例属性。

Deployment(部署)

Deployment 包含工作负载(Pod)的核心定义。与其直接在集群中创建 Pod 或 Replica Set,不如尽可能使用 Deployment。Deployment 会根据其配置中的工作负载定义,自动实例化 Replica Set 与 Pod。

Deployment 的一大优势是:相关 Replica Set 在被删除后会自动重新实例化。此外,每当有实例被删除或终止,Replica Set 都会按 Deployment 规格中的定义重新拉起新 Pod。因此,一般建议使用 Deployment,而不是单独创建 Replica Set 或 Pod:Deployment 管理相应的 Replica Set,Replica Set 再替你管理关联的 Pod。

在深入了解 Deployment 之前,我们先绕个小弯,看看 Volume 的用法,以及如何在 Pod 中引用它们并挂载到 Container。

Volume

要理解 Volume 的用法,先回到 Pod 这一层。你可以把 Pod 想象成运行某个应用的一台小计算机。这个应用可以由多个容器组成,分别处理不同的应用进程。

所有容器共享其所在 Pod 的资源,包括网络组件、CPU、RAM 或其他计算资源。但与普通计算机不同(在普通计算机上,各个进程也共享同一文件系统),Pod 中的容器行为有所区别:每个 Container 拥有自己的文件系统。所需的 Volume 在 Pod 层级定义,但会分别挂载到各个 Container 的文件系统中。

在本示例中,Volume 主要用于向工作负载提供 SAP BTP Service Binding 凭据。把这些 Volume 挂载到名为 /bindings/ 的预定义路径后,CAP 之类的框架就能在运行时使用 Service Binding(点击此处了解更多)。若想了解 Volume 的其他用法(例如用于 ConfigMap),请参阅本教程的相关章节。

Deployment 与 Volume 的介绍就到这里。下面看一个具体示例——Application Router 的 Deployment。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-router
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: router
  template:
    metadata:
      labels:
        app.kubernetes.io/name: router
    # Specification of Pod / Workload
    spec:
      # Define if Service Account token shall be auto-mounted to Pod
      # Necessary if interaction with Cluster required at runtime
      automountServiceAccountToken: false
      # Service Account name (also "default" Service Account possible)
      serviceAccountName: susaas-router
      # Container(s) to run within Pods of this deployment
      # Istio Sidecar will be injected automatically 
      containers:
        # Definition of Container running in the Pod
        - image: sap-demo/susaas-router:latest
          name: router
          # Port and protocol this container exposes 
          ports:
            - name: http
              containerPort: 5000
              protocol: TCP
          # Environment Variables available during runtime
          env:
            # SAP BTP Service Bindings Volume mount path
            - name: SERVICE_BINDING_ROOT
              value: /bindings
            - name: PORT
              value: "5000"
            - name: APPLICATION_NAME
              value: susaas-router
            # Tenant Host Pattern for multitenancy
            - name: TENANT_HOST_PATTERN
              value: "^(.*)-susaas-router-default"
            # Enable External Reverse Proxy feature
            - name: EXTERNAL_REVERSE_PROXY 
              value: "true"
            # Additional environment variables required at runtime
            - name: APPLICATION_URI
              value: susaas-router
            - name: KYMA_NAMESPACE
              value: default
          # Endpoints for Liveness, Readiness and Startup probes
          livenessProbe:
            # These endpoints should exist and return a 200 response code
            # Otherwise, your Pods might not start successfully
            httpGet:
              path: /healthz
              port: http
          readinessProbe:
            httpGet:
              path: /healthz
              port: http
          startupProbe:
            httpGet:
              path: /healthz
              port: http
            failureThreshold: 15
            periodSeconds: 2
          # Volumes mounted to container incl. SAP BTP Service Bindings
          # All SAP BTP Service Bindings are mounted on /bindings/ path
          volumeMounts:
            - mountPath: /bindings/destination/
              name: "destination"
              readOnly: true
            - mountPath: /bindings/html5-apps-repo/
              name: "html5-apps-repo"
              readOnly: true
            - mountPath: /bindings/xsuaa/
              name: "xsuaa"
              readOnly: true
          # Resource configurations for Container
          resources:
            limits:
              cpu: 300m
              ephemeral-storage: 1G
              memory: 500M
            requests:
              cpu: 300m
              ephemeral-storage: 1G
              memory: 500M
          # Container security config additional to Pod level restrictions
          securityContext:
            allowPrivilegeEscalation: false
            capabilities:
              drop:
                - ALL
            privileged: false
            readOnlyRootFilesystem: false
      # Pod restart policy
      restartPolicy: Always
      # Security config applying to all containers in the Pod
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
      # Topology Spread Constraints control how Pods are allocated within your Cluster 
      # Allows you to define failure domains like "Nodes" to enable high-availability
      topologySpreadConstraints:
        - labelSelector:
            matchLabels:
              app.kubernetes.io/name: router
          maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
      # Volumes required by workload resources incl. SAP BTP Service Bindings
      volumes:
        - name: destination
          secret:
            secretName: susaas-router-destination
        - name: html5-apps-repo
          secret:
            secretName: susaas-router-html5-apps-repo
        - name: xsuaa
          secret:
            secretName: susaas-router-xsuaa

想进一步了解高可用以及自动生成的 Deployment 配置中使用的 topologySpreadCosntraints,可以阅读 Kubernetes 官方文档(点击此处)。

Istio Service Mesh(服务网格)

Istio 是 Kubernetes 上应用最广泛的服务网格方案之一。它为集群带来一组能力:以统一、高效的方式保护、连接并监控服务及其工作负载之间的通信。Istio 是一个开源项目,并已预配置在 Kyma 集群中。在本示例中,我们主要用 Istio 保证集群内部通信的安全,同时把示例 SaaS 应用暴露到公网。这涉及多种组件,后续小节会逐一细说。

如果在某个 Kyma 命名空间中启用了 Istio-Injection(即设置所需的命名空间注解),那么在该命名空间中每创建一个新 Pod,都会自动向工作负载注入所谓的 Istio Sidecar 代理(基于 Envoy —— 详见此处)。该代理确保服务(及其工作负载)之间的进出通信始终经过这些 Istio 代理。为此,Istio 支持所有类型的 Kubernetes Service,但在本场景中,我们提到的 Service 一律指 Cluster IP Service。想更好地理解代理如何丰富并控制工作负载之间的通信流,请查看下面这张取自 Istio 官方文档的图示。

Istio 架构图,展示控制平面与 Envoy 数据平面
来源:https://istio.io/latest/docs/ops/deployment/architecture/

你也许会问:多这一层代理来处理服务间通信有什么好处?除了出色的流量监控能力,这种架构还能让集群内甚至跨节点的通信得到加密、安全且透明的保障——否则这些通信可能是明文的(除非工作负载自身强制加密)。此外,Istio 还自带一系列顺手的工具,可用于为 Service 定义流量路由策略或授权检查。想进一步了解 Sidecar 代理的思路,以及如何在服务网格中强制启用所谓的双向 TLS(mTLS)通信,请查看以下文档(点击此处)。

Istio 安全架构细节图,展示证书体系与 mTLS 通信
来源:https://istio.io/latest/docs/concepts/security/

除了处理集群内 Service 之间的通信,Istio 还简化了向外部相关方暴露工作负载的过程。通过在集群边缘部署专用的 Envoy 代理(称为 Gateway —— 详见此处),Istio 可以帮助你以安全的方式让 Service 可从公网访问。一个不错的副作用是:不再需要用 Load Balancer Service 暴露工作负载,从而省下大量公网 IP 地址的开销。下面的截图展示了使用 Kiali(了解更多)监控 Istio 所管理流量的示例。

Kiali 界面截图,展示 Istio Ingress 网关的流量拓扑
来源:https://istio.io/latest/docs/examples/microservices-istio/istio-ingress-gateway/

该图展示了一个此类(Ingress)Gateway 的示例,它允许从外部访问服务网格中的 Service。Istio 提供的工具集非常强大,而在本示例场景中我们只用到了很小一部分。若要用于生产工作负载,务必详细研读完整的 Istio 文档(点击此处)。

Istio 数据/流量流

为了更好理解 Istio 如何管理 Service 之间的通信以及外部流入的流量,我们再简要看一下数据流图示,以及下面给出的一些高层细节。跟随这些内容,你可以了解用于保障外部相关方与工作负载交互安全的各种 Istio 组件。

资源细节架构图,展示示例应用各组件与请求的流动路径

入口流量

我们来看看:当来自公网的请求到达 Kyma 集群时,底层发生了什么。这是默认情形——无论用户在浏览器中打开 SaaS 应用,还是尝试访问 SaaS API 端点(使用 SAP API Management 时另有一个例外)。

  1. 首先,请求到达位于服务网格边缘的所谓 Istio(Ingress)Gateway 详见此处。

    • 如前所述,Istio(Ingress)Gateway 也是一种基于 Envoy 的代理,提供与内部 Sidecar 代理类似的能力。

    • Gateway 提供 TLS 终止处理等能力,并确保后续发往网格内 Service 的流量都使用 mTLS(双向 TLS)。

    • 你可以在同一服务网格中使用多个 Istio(Ingress)Gateway 实例,例如处理不同自定义域名的入站流量。

    • 除非服务网格中需要自定义域名,否则可以使用默认的 Kyma Istio(Ingress)Gateway。

      Istio 文档 - 你使用网关来管理网格的入站和出站流量,从而指定哪些流量可以进入或离开网格。网关配置应用于运行在网格边缘的独立 Envoy 代理,而不是与服务工作负载并排运行的 Sidecar Envoy 代理(详见此处)。

  2. 为了把流量路由到服务网格中正确的 Service(及其关联工作负载),Istio 使用所谓的 Virtual Service。

    • Virtual Service 定义灵活的规则,说明流量如何路由到服务网格内的 Service。

    • 除了网格内的 Service,你还可以通过 Service Entry 把流量路由到网格外的服务,例如 SAP API Management。

    • 虽然本示例场景没有用到,Virtual Service 也可用于复杂的网格内路由需求。

      提示 - 这种情况下需要把 mesh 添加为 Virtual Service 的 Gateway,并按目标 Service 添加相应的 host 值,如 susaas-router(最好写成 susaas-router.default.svc.cluster.local)。

    • 在示例场景中,Virtual Service 大多由所谓的 Kyma API Rule 自动生成,对开发者隐藏了 Istio 的细节。对于默认场景,这样很好,简化了整套路由与服务暴露的配置。

    • 只有 SAP API Management 的集成在示例场景中使用了专用的 Virtual Service。API Rule 提供的能力范围不足以满足该需求。

      Istio 文档 - Virtual Service 与 Destination Rule 一起,构成 Istio 流量路由功能的关键构件。Virtual Service 让你可以配置请求如何路由到 Istio 服务网格内的某个服务,其基础是 Istio 与平台提供的连通性与服务发现能力。每个 Virtual Service 由一组按顺序评估的路由规则组成,Istio 据此把到该 Virtual Service 的每个请求匹配到网格中某个具体的实际目标(详见此处)。

  3. 确定正确的路由目标之后,所谓的 Destination Rule 就开始发挥作用。

    • Destination Rule 允许你在完成路由后进一步指定与流量相关的策略。你配置的规则会应用在 Virtual Service 指定的目标上。

    • 在很多场景中,这包括在目标工作负载的不同子集之间做负载均衡。

      提示 - 这在 A/B 测试场景或本地故障转移场景中尤其有用。

    • 流量来源(网格内或网格外)对 Destination Rule 并不重要。

    • 在示例场景中,Destination Rule 用于确保发往 Application Router 的流量保持会话粘性。

      提示 - 这样可以确保客户端基于会话 cookie 始终被路由到同一个 Pod。

      Istio 文档 - 你可以把 Virtual Service 理解为“流量如何路由到给定目标”,然后用 Destination Rule 配置“到达该目标后的流量如何处理”。Destination Rule 在 Virtual Service 路由规则评估之后生效,因此作用于流量的“真实”目标(详见此处)。

  4. 视使用场景而定,请求最终到达目标 Service 之前还会应用其他 Istio 特性。

    提示 - Virtual Service 与 Destination Rule 始终绑定到特定 host,并确保到目标 Service 的正确路由;而 Request Authentication 与 Authorization Policy 定义则作用于工作负载,它们规定工作负载支持哪些认证方式,并在服务网格中启用对工作负载的访问控制。如有需要,它们也可以应用在命名空间甚至网格级别(例如在整个服务网格中强制 mTLS)。

    • 如果需要校验请求是否已正确通过认证,可以使用 Request Authentication。

      • 在本场景中,这可以确保发往 SaaS API Service 的请求携带由提供方子账户的 SAP XSUAA 租户签发的有效 JWT token。如果认证信息有效,请求中就会带有所谓的已认证身份,供后续检查使用。与 Authorization Policy 配合,可防止 API 被恶意的未授权攻击者访问。

    • 如果想限制对某个工作负载的访问,可以使用 Authorization Policy。

      • 示例场景中的 Authorization Policy 会检查已认证身份(由 Request Authentication 资源校验),只有当身份信息匹配某个特定值时,才允许访问目标 Service。

  5. 最后,在所有策略都已应用、请求已通过认证且入站身份确认无误之后,流量经由同一 Pod 中的 Istio Sidecar 代理到达你的工作负载。

重要 - 如前所述——整条路径上的网格内流量(从 Ingress Gateway 到工作负载的 Istio Sidecar 代理)都经过 mTLS 加密!

出口流量

出站通信同样可以由 Istio 服务网格处理。在本场景中,当我们将请求转发到 SAP API Management 并施加 API 策略时,流量会离开服务网格。每当用户尝试调用 SaaS API Service 时都会发生这一过程,从而确保限流(Rate Limiting)等流量策略由 SAP API Management 强制执行。请求通过 SAP API Management 之后会被重定向回 Kyma,再由我们的 API Service 处理。

提示 - 这一 SAP API Management 集成场景的搭建细节,会在“高级功能”部分说明。

  1. 与其他入站流量一样,发往 API Service 的外部请求经由 Istio(Ingress)Gateway 到达 Kyma 集群。

  2. 在这种情况下,负责 API Service 工作负载流量的 Virtual Service 会(在第一轮中)把请求路由到 SAP API Management。

    提示 - Virtual Service 依据一个自定义头部判断请求是否已经过 SAP API Management。

  3. 所需的 SAP API Management 主机以所谓的 Service Entry 定义,Istio 可以像访问网格内 Service 一样访问它(例如在 Virtual Service 中)。

  4. 单独的 Destination Rule(指定如何处理发往该 Service Entry 的流量)允许外部流量不受默认网格内 mTLS 通信的约束。

在这个简单场景中,出站通信没有使用单独的 Istio(Egress)Gateway。如果你的服务网格有大量出站流量,可以考虑搭建专用的 Istio Egress Gateway。Egress Gateway 是 Istio Ingress Gateway 的对等组件,从功能上看(同样)相当于部署在服务网格“边缘”的 Envoy 代理。

补充提示

在 Kyma 环境中使用 Istio 时,有几点需要留意。

  • 默认情况下,Istio 在网格内的 Service 间通信中使用所谓的 Auto mTLS。因此无需再为工作负载定义启用双向 TLS(ISTIO_MUTUAL)的 Destination Rule。只有当某个路由目标需要禁用 mTLS(例如本案例中的 SAP API Management)时,才需要在 Destination Rule 中覆盖相应设置。

    Istio 文档 - Istio 通过名为“Auto mTLS”的特性让这件事变得简单。Auto mTLS 正是这样工作的:如果 DestinationRule 中没有显式配置 TLS 设置,Sidecar 会自动判断是否应发送 Istio 双向 TLS。这意味着在无需任何配置的情况下,所有网格内流量都会经过 mTLS 加密(详见此处)。

  • 默认情况下,Kyma 在 istio-system 命名空间中启用了所谓的 STRICT Peer Authentication。Peer Authentication 规定了流量如何(在需要时)隧道传输到你的 Sidecar 代理。这一在 istio-system 命名空间级别设置的值,会应用到整个服务网格。因此,除非显式定义了不同设置,Istio Sidecar 代理只接受 mTLS 流量。

    Kyma 文档 - 在 Kyma 默认的 Istio 配置中,对等认证设置为集群范围的 STRICT 模式。这确保工作负载只接受双向 TLS 流量,客户端与服务器证书都会经过验证,所有流量均被加密。这为每个服务提供了强身份,并配套可靠的密钥与证书管理体系。

Authorization Policy(授权策略)

Authorization Policy 用于依据多种规则保护服务网格中的工作负载。在本示例中,我们使用授权规则限制服务网格内的内部通信,只允许持有已认证所谓 principal 的请求访问工作负载。下面的示例中,发往 Backend Service 的请求只有满足以下条件之一,才会被放行:

  • 请求经过 Istio Ingress Gateway,且试图调用 /-/cds/* 路径。凡是通过公网到达 Kyma 集群的请求都满足该条件,因为 CAP 的 Provisioning 或 Extensibility 端点会由 SAP BTP 或部署扩展的开发者直接调用。

  • 请求来自我们的 Application Router。由于集群内使用 mTLS 通信,Istio 会自动提取来源(此处为 Application Router)的身份,并写入 source.principal 属性。在服务网格内的 mTLS 通信中,principal 值基于来源工作负载所分配到的 Service Account,采用如下标准格式(<TRUST_DOMAIN>/ns/<Namespace>/sa/<SERVICE_ACCOUNT>),其中 ns 表示命名空间,sa 表示 Service Account。

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: susaas-srv
spec:
  selector: 
    matchLabels:
      app.kubernetes.io/name: srv
  action: ALLOW
  rules:
  # External traffic will reach the Service through Istio Ingress Gateway
  # Only /-/cds/* paths are exposed to direct external traffic
  - from: 
    - source:
        principals:
          - cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account
    to:
    - operation:
        paths: 
          - /-/cds/*
  # Traffic on all paths can reach the Service through Application Router
  - from:
    - source:
        principals: 
          - cluster.local/ns/default/sa/susaas-router

对于经过 SAP API Management 策略之后才到达 API Service 的外部请求,可以基于 requestPrincipal 属性检查其已认证身份。在下面的示例中,Authorization Policy 把 SaaS API 工作负载的访问限制为:请求能提供由 https://ci-us20.authentication.us20.hana.ondemand.com/oauth/token 签发、且 subject 以 sb-susaas-api-default! 开头的 JWT token,以证明自己的身份。在本场景中,这可以保护端点不被未持有有效 SAP XSUAA 客户端凭据的请求方访问。相应的 JWT token 由 SAP API Management 在成功应用所有流量策略后注入。

提示 - 可以看到,对于两个 Sidecar 代理之间的网格内通信(使用 mTLS),我们可以依赖来源的 principal 属性(安全地识别请求来源)。此外,还可以检查 requestPrincipals 属性,依据请求在受信任签发方签发的有效 JWT token 中提供的已认证身份来限制访问。

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: susaas-api-apim
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: api
  action: ALLOW
  rules:
  - from:
    # Grant access to requests from Istio Ingress Gateway that can proof a certain requestPrincipal value 
    - source:
        principals:
          - cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account
        requestPrincipals: 
          - https://sap-demo.authentication.us20.hana.ondemand.com/oauth/token/sb-susaas-api-default!*

如果在 Kyma API Rule 中启用了访问策略(access strategy),或使用了 mutator,请确保也授予 Ory Oathkeeper 的 Service Account principal 访问权限。在本场景中,Application Router Service 就需要这样处理:Ory 会改写传入请求,注入包含相应订阅方租户子域名的 x-custom-host 头部。这样就可以动态定义自定义域名,同时仍能依据给定的 TENANT_HOST_PATTERN 唯一识别租户。

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: susaas-router
spec:
  selector: 
    matchLabels:
      app.kubernetes.io/name: router
  action: ALLOW
  rules:
  - from: 
    - source:
        principals:
          - cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account
          - cluster.local/ns/kyma-system/sa/oathkeeper-maester-account

提示 - 为了在不使用专用订阅方租户的情况下保留 Application Router 的访问能力,另外定义了一条默认 API Rule,绕过 Ory,可用于开发或测试目的。因此,Istio Ingress Gateway 的 principal 仍然保留在 Authorization Policy 中。

Destination Rule(目标规则)

Destination Rule 用于定义流量经 Virtual Service 路由之后、发往某个 Service 的策略。在本示例中,我们用 Destination Rule 为发往 Application Router Service 的流量启用会话粘性(Session Stickiness)。由于 Application Router 会保存客户端会话,必须确保流量始终路由到保存相应客户端会话的同一个工作负载。为此,我们使用 loadBalancer 流量策略,基于传入请求的 JSESSIONID cookie 来路由流量。

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: susaas-router
spec:
  host: susaas-router.default.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      consistentHash:
        httpCookie:
          name: JSESSIONID
          path: /
          ttl: 0s

另一个需要 Destination Rule 的场景,是与 SAP API Management 的网格外通信。每当我们从服务网格访问 SAP API Management 时,下面的 Destination Rule 会确保上游通信使用普通 TLS 连接(而不是默认的集群内部 mTLS 通信)。

提示 - 对于服务网格内的通信,除非被 Destination Rule 显式覆盖,否则 Istio 会强制使用 mTLS。

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: susaas-apim
spec:
  host: sap-demo.prod.apimanagement.eu10.hana.ondemand.com
  trafficPolicy:
    portLevelSettings:
      - port:
          number: 443
        tls:
          mode: SIMPLE

Destination Rule 的另一个用途,是通过所谓的 subset 在不同工作负载版本之间做负载均衡。虽然本示例场景没有用到,但这可以支持 A/B 测试之类的场景:只把一定比例的流量转发到最新版本的工作负载,其余流量继续发往旧版本。点击此处了解更多细节。

提示 - 要启用 subset 路由,请确保 Virtual Service 添加了相应的标签。

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: susaas-sample
spec:
  host: susaas-sample.default.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      simple: LEAST_REQUEST
  subsets:
  - name: latestfeatures
    labels:
      version: v2
    trafficPolicy:
      loadBalancer:
        simple: ROUND_ROBIN

Request Authentication(请求认证)

Istio 的 Request Authentication 可以检查传入请求是否带有有效的认证信息,例如基于请求头部中的 JWT token。在示例场景中,我们采用一种策略:依据一组所谓的受信任签发方(trusted issuer)来校验 JWT token 是否有效。

也就是说,只要请求能够出示由受信任签发方(在本例中是提供方子账户的 XSUAA 租户)签发的 JWT token(位于自定义头部 x-jwt-assertion 中),其认证信息就被视为有效,并可供后续处理使用(例如已认证身份)。如果请求无法提供有效的 JWT token,它不会被拒绝,只是不包含有效的认证信息(如已认证身份)。

提示 - Request Authentication 定义与所谓的 Authorization Policy 配合使用时尤其有用。这些策略会基于提取出的认证信息,决定请求最终是否允许到达某个服务。

apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: susaas-api
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: api
  # List of authentication rules applied to requests targeting the workload 
  jwtRules:
    # List of trusted JWT token issuers
    - issuer: https://sap-demo.authentication.us20.hana.ondemand.com/oauth/token
      jwksUri: https://sap-demo.authentication.us20.hana.ondemand.com/token_keys
      # Custom header field of JWT token is not in "Authorization"
      fromHeaders:
        - name: x-jwt-assertion

使用 XSUAA 时,可按下面的格式确定 issuer 与 jwksUri 信息。请务必填写 SAP BTP 提供方子账户的子域名与区域。

issuer(JWT 签发方地址) - https://<SUBDOMAIN>.authentication.<REGION>.hana.ondemand.com/oauth/token
jwksUri(用于校验签名的 JWKS 公钥地址) - https://<SUBDOMAIN>.authentication.<REGION>.hana.ondemand.com/token_keys

Service Entry(服务条目)

要让服务网格能够与 SAP API Management 这类外部服务通信,需要定义所谓的 Istio Service Entry。除了外部服务的 host,该资源类型还定义端口、协议以及 host 的解析方式——在本例中采用基于 DNS 的解析。

Service Entry 定义之后会出现在 Istio 的服务注册表中,随后即可在服务网格中使用。在示例场景中,它是某个 Virtual Service 路由定义的一部分,你可以在本章后面的部分找到(见下文)。

apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: susaas-apim
spec:
  hosts: 
    - sap-demo.prod.apimanagement.us20.hana.ondemand.com
  location: MESH_EXTERNAL
  ports:
  - number: 443
    name: https
    protocol: TLS
  resolution: DNS

Sidecar(边车)

默认情况下,Istio 会为网格中所有 Service 之间启用通信,并把所需细节保存在每个 Sidecar 代理中。在小型示例场景里这还不是大问题,但随着服务网格中 Service 数量增长,这会带来巨大的开销——毕竟一个微服务通常只需要与少数几个其他微服务通信,而不是整个网格。为了优化 Service 之间的通信(以及 Sidecar 代理中存储的所需配置),可以定义所谓的 Sidecar 资源。

这些 Sidecar 资源可以指定某个工作负载在网格内需要访问哪些 Service。在下面的示例中,我们告诉 Istio:Application Router 的 Sidecar 代理只需要访问同一命名空间(./*)以及 istio-system 命名空间中的 Service。这样即使将来网格中有成千上万个 Service,也只会从 Istio 控制平面获取少数 Service 所需的配置并存入 Sidecar 代理,从而降低 Istio 控制平面与 Sidecar 代理的 CPU、内存和磁盘占用。

提示 - 本示例场景没有涉及,但在这一上下文中还可以进一步指定入站流量设置。更多内容请查阅官方文档。

apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: susaas-router
spec:
  # Workload selector which this Sidecar configuration is applied to 
  workloadSelector: 
    labels:
      app.kubernetes.io/name: router
  # Only fetches and stores Istio configuration for certain hosts
  # In this case for egress traffic in the same and the istio-system namespace
  egress:
    - hosts:
      - ./*
      - istio-system/*

Virtual Service(虚拟服务)

Virtual Service 让你可以依据多种条件,把流量路由到与工作负载关联的 Service。在示例场景中,大多数 Virtual Service 都根据传入请求最初访问的 host 来定义流量规则。在下面的示例里,只要有发往 susaas-router-default.sap-demo.com 主机的请求经 Istio Ingress Gateway 到达,就需要告诉 Istio 该流量要路由到哪个 Service。显然,此处流量是给 Application Router 工作负载的,所以我们只需在 route 的 destination 中提供 Application Router 工作负载的 Cluster IP Service 信息即可。

提示 - 此示例使用了自定义域名。在默认配置中,会使用 Kyma 默认的 kyma-system/kyma-gateway Gateway 以及默认集群域名(例如 susaas-router-default.a1b2c3.kyma.ondemand.com)。

本示例场景所需的 Virtual Service(除一个例外)都由所谓的 Kyma API Rule 自动创建和管理。也就是说,每当你创建或更新一条 API Rule,都会创建或更新相应的 Virtual Service。这虽然降低了灵活性(API Rule 只提供 Virtual Service 特性的一个子集),但简化了大多数只涉及简单暴露工作负载的场景。

在下面的示例中,该 Virtual Service(由同名 API Rule 创建)会匹配经名为 cdomain-gateway 的 Istio Gateway 到达、目标为 susaas-router-default.sap-demo.com 主机的所有请求。所有匹配的请求都会被路由到 Application Router 工作负载的 Cluster IP Service,同时附加一个保留最初目标主机的 x-forwarded-host 头部。

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-router
spec:
  # Handle requests of the cdomain-gateway Gateway
  gateways:
    - default/cdomain-gateway
  # Handle requests targeting the susaas-router-default host
  hosts:
    - susaas-router-default.sap-demo.com
  http:
    # Match requests for all paths 
    - match:
      - uri:
          regex: /.*
      # Add x-forwarded-host header to retain initial target host
      headers:
        request:
          set:
            x-forwarded-host: susaas-router-default.sap-demo.com
      # Route to Cluster IP Service of Application Router
      route:
        - destination:
            host: susaas-router.default.svc.cluster.local
            port:
              number: 5000

正如 API Rule 部分已经说明的,为订阅方租户创建的 Virtual Service 结果会略有不同。由于我们需要额外的 x-custom-host 头部来唯一标识订阅方租户的子域名,Virtual Service 会经由 Ory Oathkeeper 路由流量。根据我们的 API Rule 定义,Ory 会添加相应的头部。

下面是这样一个生成的 Virtual Service 实例示例:它服务于某个订阅方租户,并经由 Ory 路由流量以完成所需的头部改写。

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-tenant-e1771-25rzp
spec:
  gateways: ["default/cdomain-gateway"]
  hosts: ["subscriber.sap-demo.com"]
  http:
    - headers:
        # Original target host is retained in header
        request:
          set:
            x-forwarded-host: subscriber.sap-demo.com
      match:
        - uri:
            regex: /.*
      route:
        # Route traffic to the Cluster IP Service of Ory Oathkeeper
        # x-custom-host header added by Ory Oathkeeper
        - destination:
            host: ory-oathkeeper-proxy.kyma-system.svc.cluster.local
            port:
              number: 4455
          weight: 100

SAP API Management 的集成是唯一例外:在示例应用的 Helm chart 中为其定义了专用的 Virtual Service 实例。在这种情况下,发往 API Service 主机(例如 susaas-api-default.sap-demo.com)的任何请求都会检查是否带有名为 x-jwt-assertion 的自定义头部。

该自定义头部由 SAP API Management 在验证相关 API 策略(例如限流)之后添加。只有经过 SAP API Management 且包含该自定义头部的请求,才会匹配第二个 HTTP 匹配规则,从而被路由到 API Service 工作负载的 Cluster IP Service。其他情况下,请求(缺少该自定义头部)会被路由到 SAP API Management(已定义为网格外的 Service Entry)。

重要 - 到目前为止,API Rule 不支持为同一 host 配置多条路由,因此需要专用的 Virtual Service 来满足这一路由需求。

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-api
spec:
  # Handle requests of the cdomain-gateway Gateway
  gateways: 
    - default/cdomain-gateway
  # Handle requests targeting the susaas-api-default host
  hosts: 
    - susaas-api-default.sap-demo.com
  http:
    # Match requests containing the custom x-jwt-assertion header
    - match:
        - headers:
            x-jwt-assertion: {}
      # Route requests to the Cluster IP Service of the SaaS API Service workload
      route:
      - destination:
          host: susaas-api.default.svc.cluster.local
          port:
            number: 5000
    # Match requests without the custom x-jwt-assertion header
    - match:
        - withoutHeaders:
            x-jwt-assertion: {}
      # Rewrite the URL and add the API Proxy path of SAP API Management
      rewrite:
        uri: /kyma-api-susaas/
        authority: sap-demo.prod.apimanagement.us20.hana.ondemand.com
      # Route request to SAP API Management based on Istio Service Entry 
      route:
      - destination:
          host: sap-demo.prod.apimanagement.us20.hana.ondemand.com
          port:
            number: 443

想进一步了解 SAP API Management 的集成,请阅读“高级功能”中的相应章节(点击此处)。

集群内部路由

本示例场景没有使用 Virtual Service 来施加网格内的流量路由规则。因此,当 Application Router 向 Backend Service 发送请求时,不会使用任何 Virtual Service 规则,流量会直接发送到工作负载对应的 Cluster IP Service。

如果你也希望用 Virtual Service 做网格内路由,请看下面的示例:其中额外添加了 Gateway 与 Host 以启用网格内路由。在这个示例中(从功能角度看大概没什么实际意义),外部流量被发送到 subset v1,而内部流量被路由到相应的 subset v2。这个 subset 标签随后可用于在后续 Destination Rule 中施加进一步的负载均衡策略。

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-router
spec:
  gateways: 
    - default/cdomain-gateway
    - mesh # Enables Virtual Service for mesh internal usage
  hosts: 
    - susaas-router-default.sap-demo.com
    - susaas-router.default.svc.cluster.local 
  http:
    # HTTP route mapping based on Gateway
    - match:
        - gateways:
            - default/cdomain-gateway
      route:
        - destination:
            host: susaas-router.default.svc.cluster.local
            subset: v1
    - match:
        - gateways:
            - mesh
      route:
        - destination:
            host: susaas-router.default.svc.cluster.local
            subset: v2

Istio 相关的文档内容到此结束。下面继续介绍示例应用使用的其余 Kubernetes 与 Kyma 资源。

Job(任务)

Job 是在 Kubernetes 集群中运行一次性工作负载的便捷方式。当关联的 Pod 成功终止后,Job 即结束。在示例中,我们用 Job 满足两项需求。

#1 —— 把共享数据库模型部署到 SAP HANA Cloud HDI 数据库容器

#2 —— 把 SAPUI5 组件部署到 HTML5 Application Repository 实例

这两项部署都是一次性操作,只在数据模型或任一 UI5 应用发生变化时才需要执行。变更成功部署到相应的 SAP BTP Service Instance 之后,关联的 Pod 就可以终止,Job 也会被删除。

下面这个 Job 负责把 SAPUI5 应用部署到绑定在工作负载上的 HTML5 Application Repository。与常规 Deployment 定义类似,Job 会根据所提供的配置启动一个新 Pod。一旦容器中的进程表明所分配任务成功完成(例如最新的 UI5 应用已成功部署到 HTML5 Application Repository),Pod 就会成功终止,Job 也会从集群中移除。

apiVersion: batch/v1
kind: Job
metadata:
  name: susaas-html5-apps-deployer
spec:
  # Number of retries of a Job fails 
  backoffLimit: 4
  template:
    # Istio Sidecar Injection is not required for this Pod and can be disabled
    metadata:
      labels:
        sidecar.istio.io/inject: "false"
    spec:
      restartPolicy: Never
      # Volumes required by the workload incl. SAP BTP Service Bindings
      volumes:
        - name: html5-apps-repo-secret
          secret:
            secretName: "susaas-html5-apps-deployer-html5-apps-repo"
      # Containers to be placed into the Pod (e.g., HTML5 Apps Deployer)
      containers:
        - name: html5-deployer
          image: sap-demo/susaas-html5-deployer:latest
          imagePullPolicy: Always
          volumeMounts:
            - name: html5-apps-repo-secret
              mountPath: /bindings/html5-apps-repo
              readOnly: true
          resources:
            limits:
              cpu: 500m
              memory: 500M
            requests:
              cpu: 300m
              memory: 500M
          # Environment variables
          env:
            - name: SERVICE_BINDING_ROOT
              value: /bindings
              # Will ensure the process exits after upload - process.exit()
              # Signals successful completion of Job to Kubernetes
            - name: EXIT_PROCESS_AFTER_UPLOAD
              value: "true"
            - name: ASYNC_UPLOAD
              value: "true"
            - name: PORT
              value: "5000"

Job 成功终止后的删除操作由相应的 Helm Hook 触发。下面的示例会在集群中创建新的 Job 资源之前,以及 Job 成功终止之后,触发关联 Kubernetes 资源(在本例中是 Job)的删除。这样可以避免在多次升级 Helm 安装后留下几十个无主的 Job。

提示 - 如果想保留 Job,需要修改或移除 Helm 模板中相应的 hook-delete-policy。

annotations:
  "helm.sh/hook": "post-install,post-upgrade"
  "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded

Network Policy(网络策略)

延伸阅读
Kubernetes 网络策略文档:https://kubernetes.io/docs/concepts/services-networking/network-policies/
Istio 博客:在服务网格中使用网络策略:https://istio.io/latest/blog/2017/0.1-using-network-policy/

Network Policy 在 L3 和 L4 层(网络/传输层)提供额外的安全能力,而 Istio Authorization Policy 在应用/服务层(L7)提供类似能力。因此,建议同时使用这两种资源,以零信任的思路尽可能保护你的工作负载。

如果 Sidecar 代理使用的 Istio 镜像出现问题,导致应用层(L7)出现安全漏洞,你的工作负载仍然不会被 Network Policy 中未列出的工作负载访问。Authorization Policy 作用于 Pod 层级,而 Network Policy 在节点层级强制执行。

在下面的示例中,Network Policy 确保发往 API Service Broker 的网络流量只允许来自 Istio Ingress Gateway 的工作负载。这可以保护 Service Broker 不被集群中其他工作负载恶意访问。在禁用 Istio Sidecar 注入的场景中,Network Policy 尤为有用。

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: susaas-broker
spec:
  policyTypes:
    - Ingress
  podSelector:
    matchLabels:
      app.kubernetes.io/name: broker
      app.kubernetes.io/instance: susaas
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: istio-ingressgateway
          namespaceSelector:
            matchLabels:
              name: istio-system

再看另一个示例。除了允许来自 Istio Ingress Gateway 的访问,下面这个 Backend Service 的 Network Policy 还允许来自 Application Router 工作负载的访问。这是为了让 Application Router 在完成认证并确定租户标识之后,能够与 Backend Service 通信。

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: susaas-srv
spec:
  policyTypes:
    - Ingress
  podSelector:
    matchLabels:
      app.kubernetes.io/name: srv
      app.kubernetes.io/instance: susaas
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: router
              app.kubernetes.io/instance: susaas
          namespaceSelector:
            matchLabels:
              name: default
        - podSelector:
            matchLabels:
              app: istio-ingressgateway
          namespaceSelector:
            matchLabels:
              name: istio-system

如果在 Kyma API Rule 中启用了访问策略,或使用了 mutator,除了 Istio Ingress Gateway 的工作负载之外,还请授予 Ory Oathkeeper 工作负载访问权限。在本场景中,Application Router 工作负载就需要这样处理:Ory 负责注入 x-custom-host 头部,流量并非直接从 Istio Ingress Gateway 路由到我们的 Service。

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: susaas-broker
spec:
  policyTypes:
    - Ingress
  podSelector:
    matchLabels:
      app.kubernetes.io/name: broker
      app.kubernetes.io/instance: susaas
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: istio-ingressgateway
          namespaceSelector:
            matchLabels:
              name: istio-system
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: oathkeeper
              app.kubernetes.io/instance: ory
          namespaceSelector:
            matchLabels:
              name: kyma-system

Network Policy 还可以用来阻止集群内绕过潜在 Istio Egress Gateway 的通信。做法是只允许来自相应 Istio Egress Gateway 工作负载的集群级出站流量。

Ory

虽然本示例场景没有大量使用,但多个 Ory 组件已预配置在 Kyma 集群中,提供额外的安全能力,防止对工作负载的未授权访问。

其中包括名为 Ory Hydra 的 OAuth 服务器、可用于注入自定义头部的 mutator 能力,以及在 Kyma API Rule 中启用、由所谓的 Ory Oathkeeper 处理的访问策略。Ory Oathkeeper 的主要职责是对传入的 HTTP 请求进行认证与授权。

下面是一个假设性的 API Rule 示例,它使用基于 JWT 的访问策略,校验请求的 JWT token 是否由受信任的 XSUAA 租户签发。

apiVersion: gateway.kyma-project.io/v1beta1
kind: APIRule
metadata:
  name: susaas-api
spec:
  # The API Rule will handle requests arriving for this Istio Gateway
  gateway: default/cdomain-gateway
  # The API Rule will handle all requests arriving for this host
  host: susaas-api-default.sap-demo.com
  rules:
    # Traffic on all paths will be routed to the Cluster IP service
    - methods:
        - GET
        - POST
        - PUT
        - DELETE
        - HEAD
      path: /.*
      # Access strategies defined here will result in Ory Oathkeeper Rules
      accessStrategies:
        - handler: jwt
          config:
            jwks_urls:
              - https://sap-demo.authentication.us20.hana.ondemand.com/token_keys
            trusted_issuers:
              - https://sap-demo.authentication.us20.hana.ondemand.com/oauth/token
  # Cluster IP Service to which the traffic is routed
  service:
    name: susaas-api
    port: 5000

在 API Rule 中启用访问策略(由 Ory Oathkeeper 校验)也会更新自动生成的 Virtual Service。此时,由 Kyma API Rule 生成的 Virtual Service 不再直接把请求路由到相应的 Cluster IP Service,而是先把流量路由到 Ory Oathkeeper 的 Service 工作负载。Ory 会先校验所提供的访问策略细节,然后再把流量重定向到预期的目标 Service。

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: susaas-api
spec:
  gateways:
    - default/cdomain-gateway
  hosts:
    - susaas-api-default.sap-demo.com
  http:
    - match:
        - uri:
            regex: /.*
      ...
      # Route to Ory Oathkeeper instead of the API Service
      headers:
        # Original host is retained in header
        request:
          set:
            x-forwarded-host: susaas-api-default.sap-demo.com
      route:
        # Virtual Service routes traffic to Ory Oathkeeper Service
        - destination:
            host: ory-oathkeeper-proxy.kyma-system.svc.cluster.local
            port:
              number: 4455

下面是一个自定义的所谓 Ory Rule 的简单定义(部署上述 API Rule 时会以类似方式自动创建)。在这个示例中,Ory Rule 确保发往 susaas-api-default.sap-demo.com 主机的请求必须提供由受信任 XSUAA 租户签发的有效 JWT token,否则请求不会获得访问所谓 upstream 目标(即 API Service 的 Cluster IP Service)的权限。

重要 - Ory 组件(首先是 Ory Hydra OAuth 服务器)将在后续 Kyma 版本中移除。虽然 Kyma API Rule 现有的大部分能力会被替换(例如由相应的 Istio 特性提供),我们仍强烈建议不要再使用原生 Ory 对象。这里提及 Ory 相关细节,只是帮助你理解在创建带访问策略的 API Rule 时底层发生了什么。

apiVersion: oathkeeper.ory.sh/v1alpha1
kind: Rule
metadata:
    name: susaas-api
spec:
  authenticators:
    - handler: jwt
      config: 
        jwks_urls:
          - https://sap-demo.authentication.us20.hana.ondemand.com/token_keys
        trusted_issuers:
          - https://sap-demo.authentication.us20.hana.ondemand.com/oauth/token
  authorizer:
    handler: allow
  match:
    methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"]
    url: <http|https>://susaas-api-default.sap-demo.com/<.*>
  upstream:
    url: http://susaas-api.default.svc.cluster.local:5000

在订阅方租户的 API Rule 中实际用到的另一组 Ory 特性,是所谓的 mutator。在本场景中,mutator 负责注入租户识别所需的 x-custom-host 头部。下面的示例给出了相应的 mutator 定义。

提示 - 未来这可能被基于 Istio 的方式取代,由 Istio 来设置自定义头部。

apiVersion: gateway.kyma-project.io/v1beta1
kind: APIRule
metadata:
  name: susaas-tenant-e1771
spec:
  # Handle requests arriving for this Istio Gateway
  gateway: default/cdomain-gateway
  # Handle requests for this custom Subscriber subdomain
  host: subscriber.sap-demo.com
  rules:
    - methods:
        - GET
        - POST
        - PUT
        - DELETE
        - HEAD
      path: /.*
      accessStrategies:
        - handler: noop
      # Mutator definition injecting a custom header 
      mutators:
        - config:
            headers:
              x-custom-host: subscriber-a1b2c3-susaas-router-default.sap-demo.com
          handler: header
      path: /.*
  # Cluster IP Service the traffic is routed after passing Ory Oathkeeper
  service:
    name: susaas-router
    port: 5000

Pod Autoscaler(Pod 自动扩缩容)

Horizontal Pod Autoscaler(顾名思义)会依据 CPU 利用率等已定义的指标对工作负载做水平扩缩容。Autoscaler 可作用于 Deployment 或 Replica Set 这类副本控制器。在本例中,Horizontal Pod Autoscaler 分配给了示例应用的各个 Deployment,演示了基于工作负载 CPU 消耗的基础扩缩容示例。

下面的 Autoscaler 定义确保 API Service 工作负载至少有一个 Pod 始终在集群中运行。此外,当现有 API Service 工作负载的平均 CPU 利用率达到 80% 时,它会自动扩展到最多三个 Pod。

提示 - 在简单的示例场景中,Horizontal Pod Autoscaler 可能并非必需,但随着工作负载增长会变得非常重要!请注意,minReplica 设置为 1 无法实现高可用。这种情况下至少需要两个 Pod(最好位于不同节点)。

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: susaas-api
spec:
  # Set minReplicas value > 2 if High Availability is required
  minReplicas: 1
  maxReplicas: 3
  # HPAs can be applied to Replication Controllers
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: susaas-api
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 80

Pod Disruption Budget(Pod 中断预算)

延伸阅读
Kubernetes 文档:配置 Pod 中断预算:https://kubernetes.io/docs/tasks/run-application/configure-pdb/
Kubernetes 文档:Pod 中断与中断预算:https://kubernetes.io/docs/concepts/workloads/pods/disruptions/#pod-disruption-budgets

与 Horizontal Pod Autoscaler 一样,Pod Disruption Budget 在我们这个小示例场景中并不算特别重要。Pod Disruption Budget 针对的是所谓的自愿中断(voluntary disruption),例如管理员计划关闭某个节点(如进行更新)。在这些场景中,Pod Disruption Budget 确保在发生相应中断之前,满足特定的可用性条件。

在下面的示例中,Pod Disruption Budget 确保发生自愿中断时,Service Broker 工作负载在集群剩余节点上至少还有两个 Pod 可用。虽然 Horizontal Pod Autoscaler 会介入并拉起新 Pod(当你关闭承载一定数量 Pod 的节点时),但扩缩容过程需要一些时间,新 Pod 才能就绪。使用 Pod Disruption Budget 后,如果剩余节点无法为该工作负载提供所需的最少 Pod 数量,管理员就无法关闭该节点。

重要 - Pod Disruption Budget 不覆盖断电等非计划中断。在这类情况下,可能出现集群中 Pod 数量暂时低于要求的状态,直到 Deployment 或 Autoscaler 在剩余节点上拉起新 Pod。

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: susaas-broker
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app.kubernetes.io/name: broker

提示 - minAvailable 为 1、且对应副本数/minReplica(Deployment/Autoscaler)为 1 的 Pod Disruption Budget 并不能保证高可用。只有当集群中至少有两个 Pod 运行在不同节点上时,minAvailable 为 1 才能在自愿中断场景中确保高可用。在 1 对 1 的情况下,只有现有 Pod 成功终止后,新 Pod 才会被创建。

Role Binding(角色绑定)

Role Binding 用于把现有的或自定义的 Cluster Role 分配给 Service Account。在示例场景中,它用于为 Backend Service 的 Service Account 提供运行时创建 API Rule 所需的权限。相应权限定义在对应的 Cluster Role 中。

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: susaas-srv
# Subject to assign the Cluster role to (e.g., Service Account)
subjects:
  - kind: ServiceAccount
    name: susaas-srv
    namespace: susaas
# Cluster role which is supposed to be assigned to subject
roleRef:
  name: susaas-srv
  kind: ClusterRole
  apiGroup: rbac.authorization.k8s.io

Secret(机密)

Kubernetes Secret 用于在集群中存储密码等机密值,或任何其他类型的敏感信息。Secret 可以在工作负载定义中被引用,例如让凭据值在运行时以环境变量的形式被安全使用。

在本场景中,Secret 有两种不同用法。下面的示例覆盖最常见的 Secret 用途——存储自定义凭据,例如本场景中唯一的 Broker 密码与用户。相应的 Secret 可以方便地在 Deployment 的容器定义中引用,并作为环境变量注入。

apiVersion: v1
kind: Secret
metadata:
  name: susaas-broker
type: Opaque
data:
  BROKER_USER : "YnJva2VyLXVzZXI="
  BROKER_PASSWORD : "a2RweTRhZ3oxSCV0ExckkzeDN0VXU="
  BROKER_HASH : "c2hhMjU2OlRYaFl"

下面展示了如何在容器定义中引用该 Secret。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-broker
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: broker
  template:
    metadata:
      labels:
        app.kubernetes.io/name: broker
    spec:
      containers:
      - image: sap-demo/susaas-broker:latest
        name: broker
        envFrom:
        - secretRef:
            name: susaas-broker

Secret 的第二个重要用途是 SAP BTP Service Binding。当 Kyma 工作负载需要某个 SAP BTP Service Binding 时,相应的 Kyma Service Binding 资源会自动生成一个 Secret,其中包含客户端凭据或 X.509 密钥。

这些“Service Binding”Secret 随后会通过 bindings 路径挂载到容器的文件系统中。这样,SAP BTP Service Binding 凭据就对工作负载和 CAP 等框架可用,它们可以在运行时通过 @sap/xsenv 包使用这些凭据。

kind: Secret
apiVersion: v1
metadata:
  name: susaas-broker-xsuaa-api
data:
  apiurl: https://api.authentication.us20.hana.ondemand.com
  clientid: sb-susaas-api!b8342
  clientsecret: 53e9f606-...-bb44-898903
  credential-type: binding-secret
  ...
type: Opaque

下面是一个引用所生成的 SAP BTP Service Binding Secret 的 Deployment。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-broker
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: broker
  template:
    metadata:
      labels:
        app.kubernetes.io/name: broker
    spec:
      containers:
      - image: sap-demo/susaas-broker:latest
        name: broker
        env:
        # File system path where you mount your Service Binding Secrets
        - name: SERVICE_BINDING_ROOT
          value: /bindings
        # Volumes mounted on respective /bindings/ path
        volumeMounts:
        - mountPath: /bindings/xsuaa-api/
          name: "xsuaa-api"
          readOnly: true
      ...
      # SAP BTP Service Binding Secrets provided as volumes
      volumes:
      - name: xsuaa-api
        secret:
          secretName: susaas-broker-xsuaa-api

Service(服务)

Kubernetes Service 为工作负载提供稳定的通信接口,形式多种多样。本场景使用默认的 Service 类型 Cluster IP(集群内稳定的内部 IP),此外还有 Load Balancer 等其他类型。Load Balancer Service 为工作负载分配静态外部 IP,而 Cluster IP Service 只使用内部 IP 范围。

提示 - 工作负载通常由多个 Pod 组成(它们的内部 IP 各不相同且会变化),而 Cluster IP Service 提供稳定的内部 IP 地址,并把流量负载均衡到目标工作负载的各个 Pod(例如采用轮询方式)。

在本场景中,内部 IP 地址已经够用,因为所有发往工作负载的外部流量都由 Istio Ingress Gateway 处理。因此,集群中只需要一个 Load Balancer 类型的 Service 实例,供 Istio Ingress Gateway 使用。流量通过 Gateway 之后,请求会依据最初的目标主机在内部路由到相应的 Cluster IP Service 实例。

提示 - 这一方面让我们能用上 Istio 的强大能力,另一方面相比为所有工作负载预留外部 IP 地址也省下了一大笔开销!

apiVersion: v1
kind: Service
metadata:
  name: susaas-api
spec:
  # Workload selector defining the traffic targets
  selector:
    app.kubernetes.io/name: api
  ports:
    - port: 5000
      targetPort: 5000
      protocol: TCP

Service Account(服务账户)

Service Account 可以为工作负载中运行的进程赋予所谓的身份。进程凭借该身份及其权限,可以在运行时与集群 API 交互。在我们的示例用例中,订阅流程需要这一机制,以便通过 SaaS Backend Service 在运行时创建新的 API Rule。如果没有为工作负载分配专用 Service Account,则会使用 default Service Account。下面是 SaaS Backend Service 工作负载所用专用 Service Account 的定义。

可以使用现有或新建的 Cluster Role 定义向 Service Account 授予自定义权限。这些 Cluster Role 可以通过 Role Binding 绑定到 Service Account。Service Account 在 Deployment 定义中附加到工作负载(见下方示例)。如有需要,所谓的 Service Account Token 可以自动挂载,从而让工作负载进程能够代表该 Service Account 与集群 API 交互。

apiVersion: v1
kind: ServiceAccount
metadata:
  # Name of the Service Account to be created
  name: susaas-srv

下面是一个使用专用 Service Account 以及上述 auto-mount 特性的 Deployment 定义示例。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: susaas-srv
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: srv
  template:
    metadata:
      labels:
        app.kubernetes.io/name: srv
    spec:
      # Enables the auto-mount feature of the Service Account Token
      automountServiceAccountToken: true
      # Assign a dedicated Service Account to the workload
      serviceAccountName: susaas-srv
      containers:
        - image: sap-demo/susaas-srv:latest
        ...

Service Binding(服务绑定)

Service Binding 是 Kyma 的自定义资源,可简化 SAP BTP Service Instance 的集成。为相应的 Service Instance 创建新的 Service Binding 资源,会生成新的客户端凭据或 X.509 证书。这些凭据或证书会自动存入 Kubernetes Secret。随后,把这些 Secret 作为卷挂载到容器中的特定路径,就可以在工作负载中使用。更多内容请参阅关于 Secret 的相应文档。借助 @sap/xsenv 之类的 npm 包,CAP 可以像在 Cloud Foundry 环境中那样使用这些绑定。

下面的示例为 susaas-api-uaa Service Instance 创建 Service Binding,供 susaas-broker 工作负载使用(从名称即可看出)。

apiVersion: services.cloud.sap.com/v1
kind: ServiceBinding
metadata:
  name: susaas-broker-xsuaa-api-uaa
spec:
  # Service Instance for which a new Service Binding is required
  serviceInstanceName: susaas-api-uaa

下面是由上述 Service Binding 创建的 Secret 示例。可以看到,它包含你在 Cloud Foundry 环境中已经熟悉的典型客户端凭据。

kind: Secret
apiVersion: v1
metadata:
  name: susaas-broker-xsuaa-api
data:
  apiurl: https://api.authentication.us20.hana.ondemand.com
  clientid: sb-susaas-api!b8342
  clientsecret: 53e9f606-...-bb44-898903
  credential-type: binding-secret
  ...
type: Opaque

Service Instance(服务实例)

与 Service Binding 类似,SAP BTP Service Instance 也是 Kyma 的自定义资源,二者在某种意义上互为对应。借助 SAP BTP Service Manager(每个 Kyma 集群中都可用),你可以直接在集群内创建和维护 SAP BTP Service Instance。这类 Service Instance 的定义方式,与 Cloud Foundry 环境中基于 mta.yaml 的定义类似。

除了指定所需服务产品(service offering,例如 xsuaa 或 hana)及相应服务计划(service plan,例如 application 或 hdi-shared)的名称,你还可以定义所有必需的 Service Instance 参数。这适用于 Kyma 运行时上可用的任何服务类型,如下方 Destination Service 的示例所示。

提示 - 如果你通过引用一个 JSON 文件来提供实例参数(在处理 xsuaa 时很常见),请确保该文件与该 Service Instance 的 Helm 模板位于同一目录。

提示 - 在从 Kyma 集群内创建 Service Instance 之前,请先为相应的 SAP BTP 子账户分配所需的权益(entitlement)。大部分 SAP BTP 服务已在 Kyma 运行时可用,但仍有一些例外,例如 SAP Build Workzone。遇到这类情况,需要先在 Cloud Foundry 中创建 Service Instance,然后手动把生成的 Service Binding 凭据以 Secret 的形式提供给 Kyma 集群。

apiVersion: services.cloud.sap.com/v1
kind: ServiceInstance
metadata:
  name: susaas-dest
spec:
  serviceOfferingName: destination
  servicePlanName: lite
  externalName: susaas-dest
  parameters:
    HTML5Runtime_enabled: false
    init_data:
      instance:
        destinations:
        - Authentication: NoAuthentication
          HTML5.DynamicDestination: true
          HTML5.ForwardAuthToken: true
          Name: susaas-srv-api
          ProxyType: Internet
          Type: HTTP
          URL: http://susaas-srv:8080
        existing_destinations_policy: update
    version: 1.0.0

从消费方子账户取消订阅

  • Kyma ✅

  • Cloud Foundry ✅

重要 - 如果你接下来计划搭建高级版本,可以把本部分教程视为可选内容!

如果某个子账户订阅了我们的多租户 SaaS 示例应用,并为相关的 SaaS API 创建了服务实例,那么该子账户的状态与下面截图类似。

消费方子账户已订阅 SaaS 应用并创建服务实例

以下步骤介绍如何取消订阅 SaaS 应用,以及如何从该租户子账户中移除 API Service Broker 实例。

  • 从消费方子账户取消订阅

      1. 删除服务实例并取消订阅

      1. 检查取消订阅是否成功

      1. 更多信息

1. 删除服务实例并取消订阅

1.1. 移除 Sustainable SaaS API 服务实例的服务绑定。

在 SAP BTP Cockpit 中删除服务绑定

1.2. 删除 Sustainable SaaS API 服务实例。

在 SAP BTP Cockpit 中删除服务实例

1.3. 取消订阅 Sustainable SaaS 示例应用。

在 SAP BTP Cockpit 中取消订阅 SaaS 应用

2. 检查取消订阅是否成功

请检查 Sustainable SaaS API Service Broker 是否已成功注销注册。在消费方子账户中取消订阅 Sustainable SaaS 应用时,Sustainable SaaS API Service Broker 会自动注销注册。

因此,当从该消费方子账户再次尝试创建服务实例时,Sustainable SaaS API Service 不应再出现在该子账户中。如下图所示,Sustainable SaaS API 服务已不再可见,只剩实际的 SaaS 应用本身。

检查服务代理已注销、相关服务不再出现在目录中

提示 - 如果 Service Broker 没有自动注销注册,必须借助 SAP BTP CLI 使用这个命令手动注销。请确保 Service Broker 已注销注册,否则将无法删除相应的子账户。

3. 更多信息

可通过以下链接进一步了解上述主题:

取消部署 SaaS 应用

  • Kyma ✅

  • Cloud Foundry ✅

重要 - 如果你接下来计划搭建高级版本,可以把本部分教程视为可选内容!

如果你想从 Kyma 集群或 Cloud Foundry 环境中取消部署 SaaS 应用及其所有相关服务和资源,请按以下步骤操作。

  • 取消部署 SaaS 应用

      1. 取消部署 SaaS 应用

      1. 检查取消部署是否成功

      1. 更多信息

重要 - 要从 Kyma 集群或 Cloud Foundry 环境中取消部署 SaaS 解决方案,必须先删除所有 Service Binding 和 Service Instance,然后删除每个消费方子账户中现有的所有 SaaS 订阅!否则,已有的凭据克隆(例如 XSUAA 在依赖回调期间创建的克隆)不会被正确移除,相应的 Service Instance 也无法顺利删除!

1. 取消部署 SaaS 应用

1.1. 在从 Cloud Foundry 环境或 Kyma 集群取消部署实际的 SaaS 应用之前,先删除 消费方子账户中的所有 API Service 实例。

1.2. 接下来,在开始取消部署流程之前,请确保已在所有消费方子账户中成功取消订阅该 SaaS 应用。

提示 - 你可以使用 Subscription Management Dashboard 查看并移除现有订阅(点击此处了解详情)。

1.3. 确保你的 API Service Broker 已从所有消费方子账户中正确注销注册(点击此处)。该 API Service 不应再出现在任何订阅方账户的服务选择列表或 Marketplace 菜单中。

重要 - 我们反复强调这一点:逐个消费方子账户正确取消订阅(注销所有 Service Broker 注册)能为你省去大量痛苦的手工操作。

Kyma

1.4. 在提供方子账户的 Kyma 集群中,执行以下命令卸载 SaaS 应用的 Helm Release。

helm uninstall <ReleaseName> -n <Namespace>

# Example #
helm uninstall susaas -n default

可选——在提供方子账户的 Kyma 集群中,执行以下命令取消部署 SAP Alert Notification Service 实例。

helm uninstall alert-notification -n <Namespace>

# Example #
helm uninstall alert-notification -n default

Cloud Foundry

1.4. 在提供方子账户的 Cloud Foundry 环境中取消部署 SaaS 应用。

$ cf login -a https://api.cf.<<region>>.hana.ondemand.com
$ cf undeploy susaas --delete-services --delete-service-keys

警告 - 请确保已安装最新版本的 Cloud Foundry CLI,并且你的 multiapps 插件(点击此处)为最新版本。在旧版 multiapps 插件中,尚不存在 --delete-service-keys 选项!

2. 检查取消部署是否成功

Cloud Foundry

在 SAP BTP Cockpit 中或使用 Cloud Foundry CLI,检查提供方子账户的 Cloud Foundry 环境中是否已成功移除所有应用、Service Instance 和 Service Binding。如果仍有残留对象,请尝试手动删除。请务必按以下顺序手动删除:

  • 应用实例

  • 服务密钥

  • 服务实例

如果删除失败(例如 XSUAA、Destination Service 或 SaaS Registry),请查看下方的常规部分!

Kyma

在 Kyma 集群中检查是否已成功移除所有 Service Binding、Service Instance、Secret 和 Deployment。可以使用 Kyma Dashboard 或 kubectl 命令行工具。如果提供方子账户的 Kyma 集群中仍有残留对象,请按以下顺序删除:

  • 应用工作负载(Deployment、ReplicaSet、Job、Pod)

  • SAP BTP Service Binding

  • SAP BTP Service Instance

  • 其余对象(Secret、ConfigMap)

同时请再次确认所有 Istio 相关对象以及 Network Policy、ConfigMap 是否都已成功移除。如果删除失败(例如 XSUAA、Destination Service 或 SaaS Registry),请查看下方的常规部分。

常规

你可能会遇到 Authorization & Trust Management、SaaS Provisioning 或 Destination Service 删除失败的情况。如果你没有正确取消订阅所有现有 SaaS 租户,或没有在消费方子账户中注销所有 Service Broker 注册,就很可能出现这种问题。

要注销现有的 Service Broker 注册,请重新部署应用,并使用例如 SAP BTP CLI 注销残留的 Service Broker 注册。如果现有的消费方子账户订阅没有被正确移除,可以采用同样的办法:重新部署后再移除这些订阅。

或者,你也可以使用 Subscription Management Dashboard,通过跳过依赖回调来删除剩余订阅。

3. 更多信息

可通过以下链接进一步了解上述主题: