Compare languages | The istio module: examples

Circuit Breaker

Circuit Breaker

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.

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

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 # 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.

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 минут.

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

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

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 balancing

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

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

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

Locality Failover

Locality Failover

Read the main documentation if you need.

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

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:

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

  • 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.

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

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

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

Example:

Пример:

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

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

Retry

Retry

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

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

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

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

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

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.

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

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).

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

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.

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

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

Example:

Пример:

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: 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: 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

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

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 # 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

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

Ingress to publish applications

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

Istio Ingress Gateway

Istio Ingress Gateway

Example:

Пример:

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: 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: 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: 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: 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/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: 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/v1alpha3 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

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.

Для работы с 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 сможет идентифицировать прикладной сервис, для которого предназначен запрос.

Examples:

Примеры:

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: 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: 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

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

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.

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

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

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).

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

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.

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

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).

Примеры:

  • Запретим POST-запросы для приложения myapp. Отныне, так как для приложения появилась политика, согласно алгоритму выше будут запрещены только 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”]

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”]
  • Below, the ALLOW policy is defined for the application. It only allows requests from the bar namespace (other requests are denied).
  • Здесь для приложения создана политика ALLOW. При ней будут разрешены только запросы из NS 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”]

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”]
  • 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.
  • Здесь для приложения создана политика ALLOW. При этом она не имеет ни одного правила, и поэтому ни один запрос под нее не попадет, но она таки есть. Поэтому, согласно алгоритму, раз что-то разрешено, то все остальное запрещено. В данном случае все остальное — это вообще все запросы.

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: []

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

  • 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.
  • Здесь для приложения созданы политика ALLOW (это default) и одно пустое правило. Под это правило попадает любой запрос и автоматически получает добро.

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:

  • {}

Deny all for the foo namespace

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

There are two ways you can do that:

Два способа:

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

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:

  • {}
  • 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.
  • Неявно. Здесь мы создаем политику ALLOW (по умолчанию), но не создаем ни одного фильтра, так что ни один запрос под нее не попадет и будет автоматически запрещен.

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: {}

Deny requests from the foo NS only

Запретить доступ только из namespace 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”]

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

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

Allow requests for the foo NS only

Разрешить запросы только в рамках нашего namespace 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”]

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/*”]

Allow any requests for foo or bar clusters

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

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/”]

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

Разрешить любые запросы только кластеров foo или bar, при этом из namespace 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: # Logical conjunction is used for the rules below. 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: # Правила ниже логически перемножаются. namespaces: [“baz”] principals: [“foo.local/”, “bar.local/”]

Allow from any cluster (via mTLS)

Разрешить из любого кластера (по 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 force the mTLS usage.

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.

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

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

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: [{}]

Setting up federation for two clusters using the IstioFederation CR

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

Available in Enterprise Edition only.

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

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

Setting up multicluster for two clusters using the IstioMulticluster CR

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

Available in Enterprise Edition only.

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

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/

Control the data-plane behavior

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

Prevent istio-proxy from terminating before the main application’s connections are closed

Предотвратить завершение работы istio-proxy до завершения соединений основного приложения

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.

По умолчанию в процессе остановки пода все контейнеры, включая istio-proxy, получают сигнал SIGTERM одновременно. Но некоторым приложениям для правильного завершения работы необходимо время и иногда дополнительная сетевая активность. Это невозможно, если istio-proxy завершился раньше.

The annotation below adds the preStop hook to istio-proxy container in application’s Pod:

Решение — добавить в istio-proxy preStop-хук для оценки активности прикладных контейнеров, а единственный доступный метод — это выявление сетевых сокетов приложения, и если таковых нет, тогда можно останавливать контейнер.

yaml annotations: inject.istio.io/templates: “sidecar,d8-hold-istio-proxy-termination-until-application-stops”

Аннотация ниже добавляет описанный выше preStop-хук в контейнер istio-proxy прикладного пода:

CNIPlugin application traffic redirection mode restrictions

yaml annotations: inject.istio.io/templates: “sidecar,d8-hold-istio-proxy-termination-until-application-stops”

Unlike the InitContainer mode, the redirection setting is done at the moment of Pod creating, not at the moment of triggering the istio-init init-container. This means that application init-containers will not be able to interact with other services because all traffic will be redirected to the istio-proxy sidecar container, which is not yet running. Workarounds:

Ограничения режима перенаправления прикладного трафика CNIPlugin

  • Run the application init container from the user with uid 1337. Requests from this user are not intercepted under Istio control.
  • Exclude an service IP address or port from Istio control using the traffic.sidecar.istio.io/excludeOutboundIPRanges or traffic.sidecar.istio.io/excludeOutboundPorts annotations.

В отличие от режима InitContainer, настройка перенаправления осуществляется в момент создании пода, а не в момент срабатывания init-контейнера istio-init. Это значит, что прикладные init-контейнеры не смогут взаимодействовать с остальными сервисами так как весь трафик будет перенаправлен на обработку в sidecar-контейнер istio-proxy, который ещё не запущен. Обходные пути:

Upgrading Istio

  • Запустить прикладной init-контейнер от пользователя с uid 1337. Запросы данного пользователя не перехватываются под управление Istio.
  • Исключить IP-адрес или порт сервиса из-под контроля Istio с помощью аннотаций traffic.sidecar.istio.io/excludeOutboundIPRanges или traffic.sidecar.istio.io/excludeOutboundPorts.

Upgrading Istio control-plane

Обновление Istio

  • 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.

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

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

  • 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.

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’

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

Auto upgrading istio data-plane

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’

Available in Enterprise Edition only.

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

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.

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

 

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