Circuit Breaker | Circuit Breaker |
Для выявления проблемных эндпоинтов используются настройки | The |
Пример: | 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:
| yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: my-productpage-rule namespace: myns spec: hosts:
|
Балансировка gRPC | gRPC balancing |
Важно! Чтобы балансировка gRPC-сервисов заработала автоматически, присвойте name с префиксом или значением | Caution! Assign a name with the |
Locality Failover | Locality Failover |
|
|
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: |
|
|
Это полезно для межкластерного фейловера при использовании совместно с мультикластером. | This comes in handy for inter-cluster failover when used together with a multicluster. |
|
|
Пример: | 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-запросы) выполняются повторно до трех раз. |
|
Пример: | Example: |
yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: ratings-route spec: hosts:
| yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: ratings-route spec: hosts:
|
Canary | Canary |
Важно! Istio отвечает лишь за гибкую маршрутизацию запросов, которая опирается на спецзаголовки запросов (например, cookie) или просто на случайность. За настройку этой маршрутизации и «переключение» между канареечными версиями отвечает CI/CD-система. |
|
Подразумевается, что в одном пространстве имён развёрнуты два Deployment с разными версиями приложения. У подов разных версий разные лейблы ( | 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 ( |
Требуется настроить два кастомных ресурса:
| You have to configure two custom resources:
|
Пример: | Example: |
yaml apiVersion: networking.istio.io/v1beta1 kind: DestinationRule metadata: name: productpage-canary spec: host: productpage subset’ы доступны только при обращении к хосту через VirtualService из пода под управлением Istio. Эти subset’ы должны быть указаны в маршрутах. subsets:
| 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:
|
Распределение по наличию cookie | Cookie-based routing |
yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:
| yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:
|
Распределение по вероятности | Probability-based routing |
yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:
| yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: productpage-canary spec: hosts:
|
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:
| 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:
|
yaml apiVersion: v1 kind: Secret metadata: name: app-tls-secert namespace: d8-ingress-istio # Обратите внимание, пространство имён не является app-ns. type: kubernetes.io/tls data: tls.crt: | | 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: | |
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:
| 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:
|
yaml apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: vs-app namespace: app-ns spec: gateways:
| yaml apiVersion: networking.istio.io/v1beta1 kind: VirtualService metadata: name: vs-app namespace: app-ns spec: gateways:
|
NGINX Ingress | NGINX Ingress |
Для работы с NGINX Ingress требуется подготовить:
| To use Ingress, you need to:
|
Примеры: | 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 вся маршрутизация осуществляется на основе
| 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
|
yaml apiVersion: v1 kind: Service metadata: name: productpage namespace: bookinfo spec: ports:
| yaml apiVersion: v1 kind: Service metadata: name: productpage namespace: bookinfo spec: ports:
|
Примеры настройки авторизации | Authorization configuration examples |
Алгоритм принятия решения | Decision-making algorithm |
Важно! Как только для приложения создается
| The following algorithm for deciding the fate of a request becomes active after
|
Иными словами, если вы явно что-то запретили, работает только ваш запрет. Если же вы что-то явно разрешили, теперь разрешены только явно одобренные запросы (запреты никуда не исчезают и имеют приоритет). | 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). |
Важно! Для работы политик, основанных на высокоуровневых параметрах, таких как пространства имён или principal, необходимо, чтобы все вовлеченные сервисы работали под управлением Istio. Также между приложениями должен быть организован Mutual TLS. |
|
Примеры:
| Examples:
|
yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-post-requests namespace: foo spec: selector: matchLabels: app: myapp action: DENY rules:
| yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-post-requests namespace: foo spec: selector: matchLabels: app: myapp action: DENY rules:
|
|
|
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:
|
|
|
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: [] |
|
|
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:
|
Запретить все действия в рамках пространства имён foo | Deny all actions for the foo namespace |
Два способа: | There are two ways you can do that: |
|
|
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:
|
|
|
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: {} |
Запретить доступ только из пространства имён 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:
| yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-from-ns-foo namespace: myns spec: action: DENY rules:
|
Разрешить запросы только в рамках нашего пространства имён 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:
| yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-intra-namespace-only namespace: foo spec: action: ALLOW rules:
|
Разрешить из любого места в нашем кластере | 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:
| yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-my-cluster namespace: myns spec: action: ALLOW rules:
|
Разрешить любые запросы только кластеров 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:
| 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:
|
Разрешить любые запросы только кластеров foo или bar, при этом из пространства имён 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:
| 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:
|
Разрешить из любого кластера (по mTLS) | Allow from any cluster (via mTLS) |
Важно! Если есть запрещающие правила, у них будет приоритет. Смотри алгоритм. |
|
Пример: | Example: |
yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any-cluster-with-mtls namespace: myns spec: action: ALLOW rules:
| yaml apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-all-from-any-cluster-with-mtls namespace: myns spec: action: ALLOW rules:
|
Разрешить вообще откуда угодно (в том числе без 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: [{}] |
Устройство федерации из двух кластеров с помощью кастомного ресурса IstioFederation | Setting up federation for two clusters using the IstioFederation CR |
Доступно в редакциях Enterprise Edition и Certified Security Edition Pro (1.67). | Available only in 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 |
Устройство мультикластера из двух кластеров с помощью ресурса IstioMulticluster | Setting up multicluster for two clusters using the IstioMulticluster CR |
Доступно только в редакции Enterprise Edition. | Available only in 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/ |
Управление поведением data plane | Control the data-plane behavior |
Предотвратить завершение работы istio-proxy до завершения соединений основного приложения | Prevent istio-proxy from terminating before the main application’s connections are closed |
По умолчанию в процессе остановки пода все контейнеры, включая istio-proxy, получают сигнал SIGTERM одновременно. Но некоторым приложениям для правильного завершения работы необходимо время и иногда дополнительная сетевая активность. Это невозможно, если 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 preStop-хук для оценки активности прикладных контейнеров, а единственный доступный метод — это выявление сетевых сокетов приложения, и если таковых нет, тогда можно останавливать контейнер. | The annotation below adds the preStop hook to istio-proxy container in application’s Pod: |
Аннотация ниже добавляет описанный выше preStop-хук в контейнер istio-proxy прикладного пода: | yaml annotations: inject.istio.io/templates: “sidecar,d8-hold-istio-proxy-termination-until-application-stops” |
yaml annotations: inject.istio.io/templates: “sidecar,d8-hold-istio-proxy-termination-until-application-stops” |
|
Ограничения режима перенаправления прикладного трафика
| Unlike the |
В отличие от режима |
|
| Upgrading Istio |
Обновление Istio | Upgrading Istio control-plane |
Обновление control plane Istio |
|
| To find all Pods with old Istio revision (in the example — version 19), execute the command: |
Чтобы найти все поды под управлением старой ревизии Istio (в примере — версия 19), выполните команду: | shell
kubectl get pods -A -o json | jq –arg revision “v1x19” |
shell
kubectl get pods -A -o json | jq –arg revision “v1x19” | Auto upgrading istio data-plane |
Автоматическое обновление data plane Istio | Available only in Enterprise Edition. |
Доступно в редакциях Enterprise Edition и Certified Security Edition Pro (1.67). | To automate istio-sidecar upgrading, set a label |
Для автоматизации обновления istio-sidecar’ов установите лейбл |