Compare languages | Модуль istio: примеры

Circuit Breaker

Circuit Breaker

Для выявления проблемных эндпоинтов используются настройки outlierDetection в custom resource DestinationRule. Более подробно алгоритм Outlier Detection описан в документации Envoy.

The outlierDetection settings in the DestinationRule custom resource help to determine whether some endpoints do not behave as expected. Refer to the Envoy documentation for more details on the Outlier Detection algorithm.

Пример:

Example:

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: reviews-cb-policy spec: host: reviews.prod.svc.cluster.local trafficPolicy: connectionPool: tcp: maxConnections: 100 # Максимальное число коннектов в сторону host, суммарно для всех эндпоинтов. http: maxRequestsPerConnection: 10 # Каждые 10 запросов коннект будет пересоздаваться. outlierDetection: consecutive5xxErrors: 7 # Допустимо 7 ошибок (включая пятисотые, TCP-таймауты и HTTP-таймауты) interval: 5m # в течение пяти минут, baseEjectionTime: 15m # после которых эндпоинт будет исключен из балансировки на 15 минут.

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: reviews-cb-policy spec: host: reviews.prod.svc.cluster.local trafficPolicy: connectionPool: tcp: maxConnections: 100 # The maximum number of connections to the host (cumulative for all endpoints) http: maxRequestsPerConnection: 10 # The connection will be re-established after every 10 requests outlierDetection: consecutive5xxErrors: 7 # Seven consecutive errors are allowed (including 5XX, TCP and HTTP timeouts) interval: 5m # over 5 minutes. baseEjectionTime: 15m # Upon reaching the error limit, the endpoint will be excluded from balancing for 15 minutes.

А также для настройки HTTP-таймаутов используется ресурс VirtualService. Эти таймауты также учитываются при подсчете статистики ошибок на эндпоинтах.

Additionally, the VirtualService resource is used to configure the HTTP timeouts. These timeouts are also taken into account when calculating error statistics for endpoints.

Пример:

Example:

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: my-productpage-rule namespace: myns spec: hosts:

  • productpage http:
  • timeout: 5s route:
  • destination: host: productpage

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: my-productpage-rule namespace: myns spec: hosts:

  • productpage http:
  • timeout: 5s route:
  • destination: host: productpage

Балансировка gRPC

gRPC balancing

Важно! Чтобы балансировка gRPC-сервисов заработала автоматически, присвойте name с префиксом или значением grpc для порта в соответствующем Service.

Caution! Assign a name with the grpc prefix or value to the port in the corresponding Service to make gRPC service balancing start automatically.

Locality Failover

Locality Failover

При необходимости ознакомьтесь с основной документацией.

Read the main documentation if you need.

Istio позволяет настроить приоритетный географический фейловер между эндпоинтами. Для определения зоны Istio использует лейблы узлов с соответствующей иерархией:

Istio allows you to configure a priority-based locality (geographic location) failover between endpoints. Istio uses node labels with the appropriate hierarchy to define the zone:

  • topology.istio.io/subzone;
  • topology.kubernetes.io/zone;
  • topology.kubernetes.io/region.
  • topology.istio.io/subzone
  • topology.kubernetes.io/zone
  • topology.kubernetes.io/region

Это полезно для межкластерного фейловера при использовании совместно с мультикластером.

This comes in handy for inter-cluster failover when used together with a multicluster.

Важно! Для включения Locality Failover используется ресурс DestinationRule, в котором также необходимо настроить outlierDetection.

Caution! The Locality Failover can be enabled using the DestinationRule CR. Note that you also have to configure the outlierDetection.

Пример:

Example:

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: helloworld spec: host: helloworld trafficPolicy: loadBalancer: localityLbSetting: enabled: true # Включили LF. outlierDetection: # outlierDetection включить обязательно. consecutive5xxErrors: 1 interval: 1s baseEjectionTime: 1m

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: helloworld spec: host: helloworld trafficPolicy: loadBalancer: localityLbSetting: enabled: true # LF is enabled outlierDetection: # outlierDetection must be enabled consecutive5xxErrors: 1 interval: 1s baseEjectionTime: 1m

Retry

Retry

С помощью ресурса VirtualService можно настроить Retry для запросов.

You can use the VirtualService resource to configure Retry for requests.

Внимание! По умолчанию при возникновении ошибок все запросы (включая POST-запросы) выполняются повторно до трех раз.

Caution! All requests (including POST ones) are retried three times by default.

Пример:

Example:

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: ratings-route spec: hosts:

  • ratings.prod.svc.cluster.local http:
  • route:
  • destination: host: ratings.prod.svc.cluster.local retries: attempts: 3 perTryTimeout: 2s retryOn: gateway-error,connect-failure,refused-stream

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: ratings-route spec: hosts:

  • ratings.prod.svc.cluster.local http:
  • route:
  • destination: host: ratings.prod.svc.cluster.local retries: attempts: 3 perTryTimeout: 2s retryOn: gateway-error,connect-failure,refused-stream

Canary

Canary

Важно! Istio отвечает лишь за гибкую маршрутизацию запросов, которая опирается на спецзаголовки запросов (например, cookie) или просто на случайность. За настройку этой маршрутизации и «переключение» между канареечными версиями отвечает CI/CD-система.

Caution! Istio is only responsible for flexible request routing that relies on special request headers (such as cookies) or simply randomness. The CI/CD system is responsible for customizing this routing and “switching” between canary versions.

Подразумевается, что в одном namespace выкачено два Deployment с разными версиями приложения. У подов разных версий разные лейблы (version: v1 и version: v2).

The idea is that two Deployments with different versions of the application are deployed in the same namespace. The Pods of different versions have different labels (version: v1 and version: v2).

Требуется настроить два custom resource:

  • DestinationRule с описанием, как идентифицировать разные версии вашего приложения (subset’ы);
  • VirtualService с описанием, как распределять трафик между разными версиями приложения.

You have to configure two custom resources:

  • A DestinationRule – defines how to identify different versions of your application (subsets);
  • A VirtualService – defines how to balance traffic between different versions of your application.

Пример:

Example:

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: productpage-canary spec: host: productpage subset’ы доступны только при обращении к хосту через VirtualService из пода под управлением Istio. Эти subset’ы должны быть указаны в маршрутах. subsets:

  • name: v1 labels: version: v1
  • name: v2 labels: version: v2

yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: productpage-canary spec: host: productpage subsets are only available when accessing the host via the VirtualService from a Pod managed by Istio. These subsets must be defined in the routes. subsets:

  • name: v1 labels: version: v1
  • name: v2 labels: version: v2

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:

  • productpage http:
  • match:
  • headers: cookie: regex: “^(.;?)?(canary=yes)(;.)?” route:
  • destination: host: productpage subset: v2 # Ссылка на subset из DestinationRule.
  • route:
  • destination: host: productpage subset: v1

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:

  • productpage http:
  • match:
  • headers: cookie: regex: “^(.;?)?(canary=yes)(;.)?” route:
  • destination: host: productpage subset: v2 # The reference to the subset from the DestinationRule.
  • route:
  • destination: host: productpage subset: v1

Распределение по вероятности

Probability-based routing

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:

  • productpage http:
  • route:
  • destination: host: productpage subset: v1 # Ссылка на subset из DestinationRule. weight: 90 # Процент трафика, который получат поды с лейблом version: v1.
  • route:
  • destination: host: productpage subset: v2 weight: 10

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:

  • productpage http:
  • route:
  • destination: host: productpage subset: v1 # The reference to the subset from the DestinationRule. weight: 90 # Percentage of traffic that the Pods with the version: v1 label will be getting.
  • route:
  • destination: host: productpage subset: v2 weight: 10

Ingress для публикации приложений

Ingress to publish applications

Istio Ingress Gateway

Istio Ingress Gateway

Пример:

Example:

yaml apiVersion: deckhouse.io/v1alpha1 kind: IngressIstioController metadata: name: main spec: ingressGatewayClass содержит значение селектора меток, используемое при создании ресурса Gateway. ingressGatewayClass: istio-hp inlet: HostPort hostPort: httpPort: 80 httpsPort: 443 nodeSelector: node-role/frontend: ‘’ tolerations:

  • effect: NoExecute key: dedicated operator: Equal value: frontend resourcesRequests: mode: VPA

yaml apiVersion: deckhouse.io/v1alpha1 kind: IngressIstioController metadata: name: main spec: ingressGatewayClass contains the label selector value used to create the Gateway resource ingressGatewayClass: istio-hp inlet: HostPort hostPort: httpPort: 80 httpsPort: 443 nodeSelector: node-role/frontend: ‘’ tolerations:

  • effect: NoExecute key: dedicated operator: Equal value: frontend resourcesRequests: mode: VPA

yaml apiVersion: v1 kind: Secret metadata: name: app-tls-secert namespace: d8-ingress-istio # Обратите внимание, что namespace не является app-ns. type: kubernetes.io/tls data: tls.crt: |

tls.key: |

yaml apiVersion: v1 kind: Secret metadata: name: app-tls-secert namespace: d8-ingress-istio # note the namespace isn’t app-ns type: kubernetes.io/tls data: tls.crt: |

tls.key: |

yaml apiVersion: networking.istio.io/v1beta1 kind: Gateway metadata: name: gateway-app namespace: app-ns spec: selector: Селектор меток для использования Istio Ingress Gateway main-hp. istio.deckhouse.io/ingress-gateway-class: istio-hp servers:

  • port: Стандартный шаблон для использования протокола HTTP. number: 80 name: http protocol: HTTP hosts:
  • app.example.com
  • port: Стандартный шаблон для использования протокола HTTPS. number: 443 name: https protocol: HTTPS tls: mode: SIMPLE Secret с сертификатом и ключем, который должен быть создан в d8-ingress-istio namespace. Поддерживаемые форматы Secret’ов можно посмотреть по ссылке https://istio.io/latest/docs/tasks/traffic-management/ingress/secure-ingress/#key-formats. credentialName: app-tls-secrets hosts:
  • app.example.com

yaml apiVersion: networking.istio.io/v1beta1 kind: Gateway metadata: name: gateway-app namespace: app-ns spec: selector: label selector for using the Istio Ingress Gateway main-hp istio.deckhouse.io/ingress-gateway-class: istio-hp servers:

  • port: standard template for using the HTTP protocol number: 80 name: http protocol: HTTP hosts:
  • app.example.com
  • port: standard template for using the HTTPS protocol number: 443 name: https protocol: HTTPS tls: mode: SIMPLE a secret with a certificate and a key, which must be created in the d8-ingress-istio namespace supported secret formats can be found at https://istio.io/latest/docs/tasks/traffic-management/ingress/secure-ingress/#key-formats credentialName: app-tls-secrets hosts:
  • app.example.com

yaml apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: vs-app namespace: app-ns spec: gateways:

  • gateway-app hosts:
  • app.example.com http:
  • route:
  • destination: host: app-svc

yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: vs-app namespace: app-ns spec: gateways:

  • gateway-app hosts:
  • app.example.com http:
  • route:
  • destination: host: app-svc

NGINX Ingress

NGINX Ingress

Для работы с NGINX Ingress требуется подготовить:

  • Ingress-контроллер, добавив к нему sidecar от Istio. В нашем случае включить параметр enableIstioSidecar у custom resource IngressNginxController модуля ingress-nginx.
  • Ingress-ресурс, который ссылается на Service. Обязательные аннотации для Ingress-ресурса:
  • nginx.ingress.kubernetes.io/service-upstream: "true" — с этой аннотацией Ingress-контроллер будет отправлять запросы на ClusterIP сервиса (из диапазона Service CIDR) вместо того, чтобы слать их напрямую в поды приложения. Sidecar-контейнер istio-proxy перехватывает трафик только в сторону диапазона Service CIDR, остальные запросы отправляются напрямую;
  • nginx.ingress.kubernetes.io/upstream-vhost: myservice.myns.svc — с данной аннотацией sidecar сможет идентифицировать прикладной сервис, для которого предназначен запрос.

To use Ingress, you need to:

  • Configure the Ingress controller by adding Istio sidecar to it. In our case, you need to enable the enableIstioSidecar parameter in the ingress-nginx module’s IngressNginxController custom resource.
  • Set up an Ingress that refers to the Service. The following annotations are mandatory for Ingress:
  • nginx.ingress.kubernetes.io/service-upstream: "true" — using this annotation, the Ingress controller sends requests to a single ClusterIP (from Service CIDR) while envoy load balances them. Ingress controller’s sidecar is only catching traffic directed to Service CIDR.
  • nginx.ingress.kubernetes.io/upstream-vhost: myservice.myns.svc — using this annotation, the sidecar container can identify the application service that serves requests.

Примеры:

Examples:

yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: productpage namespace: bookinfo annotations: Просим nginx проксировать трафик на ClusterIP вместо собственных IP подов. nginx.ingress.kubernetes.io/service-upstream: “true” В Istio вся маршрутизация осуществляется на основе Host: заголовка запросов. Чтобы не сообщать Istio о существовании внешнего домена productpage.example.com, мы просто используем внутренний домен, о котором Istio осведомлен. nginx.ingress.kubernetes.io/upstream-vhost: productpage.bookinfo.svc spec: rules:

  • host: productpage.example.com http: paths:
  • path: / pathType: Prefix backend: service: name: productpage port: number: 9080

yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: productpage namespace: bookinfo annotations: Nginx proxies traffic to the ClusterIP instead of pods’ own IPs. nginx.ingress.kubernetes.io/service-upstream: “true” In Istio, all routing is carried out based on the Host: headers. Instead of letting Istio know about the productpage.example.com external domain, we use the internal domain of which Istio is aware. nginx.ingress.kubernetes.io/upstream-vhost: productpage.bookinfo.svc spec: rules:

  • host: productpage.example.com http: paths:
  • path: / pathType: Prefix backend: service: name: productpage port: number: 9080

yaml apiVersion: v1 kind: Service metadata: name: productpage namespace: bookinfo spec: ports:

  • name: http port: 9080 selector: app: productpage type: ClusterIP

yaml apiVersion: v1 kind: Service metadata: name: productpage namespace: bookinfo spec: ports:

  • name: http port: 9080 selector: app: productpage type: ClusterIP

Примеры настройки авторизации

Authorization configuration examples

Алгоритм принятия решения

Decision-making algorithm

Важно! Как только для приложения создается AuthorizationPolicy, начинает работать следующий алгоритм принятия решения о судьбе запроса:

  • Если запрос попадает под политику DENY — запретить запрос.
  • Если для данного приложения нет политик ALLOW — разрешить запрос.
  • Если запрос попадает под политику ALLOW — разрешить запрос.
  • Все остальные запросы — запретить.

The following algorithm for deciding the fate of a request becomes active after AuthorizationPolicy is created for the application:

  • The request is denied if it falls under the DENY policy;
  • The request is allowed if there are no ALLOW policies for the application;
  • The request is allowed if it falls under the ALLOW policy.
  • All other requests are denied.

Иными словами, если вы явно что-то запретили, работает только ваш запрет. Если же вы что-то явно разрешили, теперь разрешены только явно одобренные запросы (запреты никуда не исчезают и имеют приоритет).

In other words, if you explicitly deny something, then only this restrictive rule will work. If you explicitly allow something, only explicitly authorized requests will be allowed (however, restrictions will stay in force and have precedence).

Важно! Для работы политик, основанных на высокоуровневых параметрах, таких как namespace или principal, необходимо, чтобы все вовлеченные сервисы работали под управлением Istio. Также между приложениями должен быть организован Mutual TLS.

Caution! The policies based on high-level parameters like namespace or principal require enabling Istio for all involved applications. Also, there must be organized Mutual TLS between applications.

Примеры:

  • Запретим POST-запросы для приложения myapp. Отныне, так как для приложения появилась политика, согласно алгоритму выше будут запрещены только POST-запросы к приложению.

Examples:

  • Let’s deny POST requests for the myapp application. Since a policy is defined, only POST requests to the application are denied (as per the algorithm above).

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-post-requests namespace: foo spec: selector: matchLabels: app: myapp action: DENY rules:

  • to:
  • operation: methods: [“POST”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-post-requests namespace: foo spec: selector: matchLabels: app: myapp action: DENY rules:

  • to:
  • operation: methods: [“POST”]
  • Здесь для приложения создана политика ALLOW. При ней будут разрешены только запросы из NS bar, остальные запрещены.
  • Below, the ALLOW policy is defined for the application. It only allows requests from the bar namespace (other requests are denied).

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: selector: matchLabels: app: myapp action: ALLOW # default, можно не указывать. rules:

  • from:
  • source: namespaces: [“bar”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: selector: matchLabels: app: myapp action: ALLOW # The default value, can be skipped. rules:

  • from:
  • source: namespaces: [“bar”]
  • Здесь для приложения создана политика ALLOW. При этом она не имеет ни одного правила, и поэтому ни один запрос под нее не попадет, но она таки есть. Поэтому, согласно алгоритму, раз что-то разрешено, то все остальное запрещено. В данном случае все остальное — это вообще все запросы.
  • Below, the ALLOW policy is defined for the application. Note that it does not have any rules, so not a single request matches it (still, the policy exists). Thus, our decision-making algorithm suggests that if something is allowed, then everything else is denied. In this case, “everything else” includes all the requests.

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: selector: matchLabels: app: myapp action: ALLOW # default, можно не указывать. rules: []

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: selector: matchLabels: app: myapp action: ALLOW # The default value, can be skipped. rules: []

  • Здесь для приложения созданы политика ALLOW (это default) и одно пустое правило. Под это правило попадает любой запрос и автоматически получает добро.
  • Below, the (default) ALLOW policy is defined for the application. Note that it has an empty rule. Any request matches this rule, so it is naturally approved.

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all namespace: foo spec: selector: matchLabels: app: myapp rules:

  • {}

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all namespace: foo spec: selector: matchLabels: app: myapp rules:

  • {}

Запретить вообще все в рамках namespace foo

Deny all for the foo namespace

Два способа:

There are two ways you can do that:

  • Запретить явно. Здесь мы создаем политику DENY с единственным универсальным фильтром {}, под который попадают все запросы:
  • Explicitly. Here, the DENY policy is created. It has a single {} rule that covers all the requests:

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: action: DENY rules:

  • {}

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: action: DENY rules:

  • {}
  • Неявно. Здесь мы создаем политику ALLOW (по умолчанию), но не создаем ни одного фильтра, так что ни один запрос под нее не попадет и будет автоматически запрещен.
  • Implicitly. Here, the (default) ALLOW policy is created that does not have any rules. Thus, no requests will match it, and the policy will deny all of them.

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: {}

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-all namespace: foo spec: {}

Запретить доступ только из namespace foo

Deny requests from the foo NS only

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-from-ns-foo namespace: myns spec: action: DENY rules:

  • from:
  • source: namespaces: [“foo”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-from-ns-foo namespace: myns spec: action: DENY rules:

  • from:
  • source: namespaces: [“foo”]

Разрешить запросы только в рамках нашего namespace foo

Allow requests for the foo NS only

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-intra-namespace-only namespace: foo spec: action: ALLOW rules:

  • from:
  • source: namespaces: [“foo”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-intra-namespace-only namespace: foo spec: action: ALLOW rules:

  • from:
  • source: namespaces: [“foo”]

Разрешить из любого места в нашем кластере

Allow requests from anywhere in the cluster

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-my-cluster namespace: myns spec: action: ALLOW rules:

  • from:
  • source: principals: [“mycluster.local/*”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-my-cluster namespace: myns spec: action: ALLOW rules:

  • from:
  • source: principals: [“mycluster.local/*”]

Разрешить любые запросы только кластеров foo или bar

Allow any requests for foo or bar clusters

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-foo-or-bar-clusters-to-ns-baz namespace: baz spec: action: ALLOW rules:

  • from:
  • source: principals: [“foo.local/”, “bar.local/”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-foo-or-bar-clusters-to-ns-baz namespace: baz spec: action: ALLOW rules:

  • from:
  • source: principals: [“foo.local/”, “bar.local/”]

Разрешить любые запросы только кластеров foo или bar, при этом из namespace baz

Allow any requests from foo or bar clusters where the namespace is baz

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-foo-or-bar-clusters-to-ns-baz namespace: baz spec: action: ALLOW rules:

  • from:
  • source: # Правила ниже логически перемножаются. namespaces: [“baz”] principals: [“foo.local/”, “bar.local/”]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-foo-or-bar-clusters-to-ns-baz namespace: baz spec: action: ALLOW rules:

  • from:
  • source: # Logical conjunction is used for the rules below. namespaces: [“baz”] principals: [“foo.local/”, “bar.local/”]

Разрешить из любого кластера (по mTLS)

Allow from any cluster (via mTLS)

Важно! Если есть запрещающие правила, у них будет приоритет. Смотри алгоритм.

Caution! The denying rules (if they exist) have priority over any other rules. See the algorithm.

Пример:

Example:

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any-cluster-with-mtls namespace: myns spec: action: ALLOW rules:

  • from:
  • source: principals: [“*”] # To set mTLS mandatory.

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any-cluster-with-mtls namespace: myns spec: action: ALLOW rules:

  • from:
  • source: principals: [“*”] # To force the mTLS usage.

Разрешить вообще откуда угодно (в том числе без mTLS)

Allow all requests from anywhere (including no mTLS - plain text traffic)

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any namespace: myns spec: action: ALLOW rules: [{}]

yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any namespace: myns spec: action: ALLOW rules: [{}]

Устройство федерации из двух кластеров с помощью custom resource IstioFederation

Setting up federation for two clusters using the IstioFederation CR

Доступно только в редакции Enterprise Edition.

Available in Enterprise Edition only.

Cluster A:

Cluster A:

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioFederation metadata: name: cluster-b spec: metadataEndpoint: https://istio.k8s-b.example.com/metadata/ trustDomain: cluster-b.local

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioFederation metadata: name: cluster-b spec: metadataEndpoint: https://istio.k8s-b.example.com/metadata/ trustDomain: cluster-b.local

Cluster B:

Cluster B:

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioFederation metadata: name: cluster-a spec: metadataEndpoint: https://istio.k8s-a.example.com/metadata/ trustDomain: cluster-a.local

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioFederation metadata: name: cluster-a spec: metadataEndpoint: https://istio.k8s-a.example.com/metadata/ trustDomain: cluster-a.local

Устройство мультикластера из двух кластеров с помощью ресурса IstioMulticluster

Setting up multicluster for two clusters using the IstioMulticluster CR

Доступно только в редакции Enterprise Edition.

Available in Enterprise Edition only.

Cluster A:

Cluster A:

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioMulticluster metadata: name: cluster-b spec: metadataEndpoint: https://istio.k8s-b.example.com/metadata/

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioMulticluster metadata: name: cluster-b spec: metadataEndpoint: https://istio.k8s-b.example.com/metadata/

Cluster B:

Cluster B:

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioMulticluster metadata: name: cluster-a spec: metadataEndpoint: https://istio.k8s-a.example.com/metadata/

yaml apiVersion: deckhouse.io/v1alpha1 kind: IstioMulticluster metadata: name: cluster-a spec: metadataEndpoint: https://istio.k8s-a.example.com/metadata/

Управление поведением data plane

Control the data-plane behavior

[экспериментальная функция] Предотвратить завершение работы istio-proxy до завершения соединений основного приложения

[experimental feature] Prevent istio-proxy from terminating before the main application’s connections are closed

По умолчанию в процессе остановки пода все контейнеры, включая istio-proxy, получают сигнал SIGTERM одновременно. Но некоторым приложениям для правильного завершения работы необходимо время и иногда дополнительная сетевая активность. Это невозможно, если istio-proxy завершился раньше. Решение — добавить в istio-proxy preStop-хук для оценки активности прикладных контейнеров, а единственный доступный метод — это выявление сетевых сокетов приложения, и если таковых нет, тогда можно останавливать контейнер. Аннотация ниже добавляет описанный выше preStop-хук в контейнер istio-proxy прикладного пода: inject.istio.io/templates: sidecar,d8-hold-istio-proxy-termination-until-application-stops.

By default, during termination, all containers in a Pod, including istio-proxy one, receive SIGTERM signal simultaneously. But some applications need time to properly handle the termination and sometimes they need to do some network requests. It isn’t possible when the istio-proxy stops before the application do. The solution is to add a preStop hook which evaluates the application’s activity via discovering application’s network sockets and let the sidecar stop when they aren’t in the network namespace. The annotation below adds the preStop hook to istio-proxy container in application’s Pod: inject.istio.io/templates: sidecar,d8-hold-istio-proxy-termination-until-application-stops.

Обновление Istio

Upgrading Istio

Обновление control plane Istio

Upgrading Istio control-plane

  • Deckhouse позволяет инсталлировать несколько версий control plane одновременно:
  • Одна глобальная, обслуживает namespace’ы или поды без явного указания версии (label у namespace istio-injection: enabled). Настраивается параметром globalVersion.
  • Остальные — дополнительные, обслуживают namespace’ы или поды с явным указанием версии (label у namespace или пода istio.io/rev: v1x19). Настраиваются параметром additionalVersions.
  • Istio заявляет обратную совместимость между data plane и control plane в диапазоне двух минорных версий: Istio data-plane and control-plane compatibility
  • Алгоритм обновления (для примера, на версию 1.19):
  • Добавить желаемую версию в параметр модуля additionalVersions (additionalVersions: ["1.19"]).
  • Дождаться появления соответствующего пода istiod-v1x19-xxx-yyy в namespace d8-istio.
  • Для каждого прикладного namespace, где включен istio:
  • поменять label istio-injection: enabled на istio.io/rev: v1x19;
  • по очереди пересоздать поды в namespace, параллельно контролируя работоспособность приложения.
  • Поменять настройку globalVersion на 1.19 и удалить additionalVersions.
  • Убедиться, что старый под istiod удалился.
  • Поменять лейблы прикладных namespace на istio-injection: enabled.
  • Deckhouse allows you to install different control-plane versions simultaneously:
  • A single global version to handle namespaces or Pods with indifferent version (namespace label istio-injection: enabled). It is configured by the globalVersion parameter.
  • The other ones are additional, they handle namespaces or Pods with explicitly configured versions (istio.io/rev: v1x19 label for namespace or Pod). They are configured by the additionalVersions parameter.
  • Istio declares backward compatibility between data-plane and control-plane in the range of two minor versions: Istio data-plane and control-plane compatibility
  • Upgrade algorithm (i.e. to 1.19):
  • Configure additional version in the additionalVersions parameter (additionalVersions: ["1.19"]).
  • Wait for the corresponding pod istiod-v1x19-xxx-yyy to appear in d8-istio namespace.
  • For every application Namespase with istio enabled:
  • Change istio-injection: enabled label to istio.io/rev: v1x19.
  • Recreate the Pods in namespace (one at a time), simultaneously monitoring the application’s workability.
  • Reconfigure globalVersion to 1.19 and remove the additionalVersions configuration.
  • Make sure, the old istiod Pod has gone.
  • Change application namespace labels to istio-injection: enabled.

Чтобы найти все поды под управлением старой ревизии Istio, выполните:

To find all Pods with old Istio revision, execute the following command:

shell kubectl get pods -A -o json | jq –arg revision “v1x16”
‘.items[] | select(.metadata.annotations.”sidecar.istio.io/status” // “{}” | fromjson | .revision == $revision) | .metadata.namespace + “/” + .metadata.name’

shell kubectl get pods -A -o json | jq –arg revision “v1x16”
‘.items[] | select(.metadata.annotations.”sidecar.istio.io/status” // “{}” | fromjson | .revision == $revision) | .metadata.namespace + “/” + .metadata.name’

Автоматическое обновление data plane Istio

Auto upgrading istio data-plane

Доступно только в редакции Enterprise Edition.

Available in Enterprise Edition only.

Для автоматизации обновления istio-sidecar’ов установите лейбл istio.deckhouse.io/auto-upgrade="true" на Namespace либо на отдельный ресурс — Deployment, DaemonSet или StatefulSet.

To automate istio-sidecar upgrading, set a label istio.deckhouse.io/auto-upgrade="true" on the application Namespace or on the individual resources — Deployment, DaemonSet or StatefulSet.