Среды разработки с помощью vcluster

Антонио Бербен

В Solo.io мы прислушиваемся к мнению сообщества и пробуем лучшие технологии, чтобы помочь командам достичь своих целей. Это включает в себя как работу над проектами с открытым исходным кодом, так и предоставление поддержки и продуктов, которые могут помочь вам лучше использовать технологии. 

Gloo Mesh — один из таких продуктов. Он представляет собой хороший пример того, как можно свести к минимуму сложность управления всей сетью приложений в вашей инфраструктуре. Как можно понять, это подразумевает многокластерные архитектуры.

В таких сценариях, как можно проверить правильность многокластерной конфигурации в локальной среде, прежде чем переходить к более обширной среде?

Давайте рассмотрим это в контексте. Ваша команда (или команда разработчиков) хочет выпустить новую функцию. Они хотят вызвать некоторый хаос в системе. Gloo Mesh предлагает эту функциональность и многие другие сквозные политики (FailOver, внедрение ошибок, обнаружение выбросов, повторные попытки, тайм-ауты, зеркалирование, ограничение скорости и многое другое). Но вы, как оператор платформы и Gloo Mesh, можете быть не уверены, какая конфигурация является правильной. Сначала необходимо провести исследование в среде разработки или тестирования.

В смоделированном производственном сценарии, в котором используются три кластера (один для управления и два для рабочих нагрузок), первая проблема очевидна: стоимость. Развертывание трех кластеров в общедоступных облаках стоит дорого.

Вторая проблема: сетевое взаимодействие. Допустим, вы решите сначала провести исследование в своей локальной среде. Развернуть целых три кластера на собственной рабочей станции не так-то просто. Вы можете выбрать такие решения, как multiple kind (kubernetes-in-docker) или k3d. Оба они развертывают кластеры в контейнерах поверх хост-машины. Один кластер, один контейнер. Если вы попробуете один из этих подходов, вам, вероятно, придется настраивать сеть между контейнерами и хост-машиной.

Третья проблема: ПРОЦЕССОР. Чтобы развернуть все в своей локальной среде, нужно убедиться, что у вас достаточно «мускулов».

Теперь… Что если мы начнем рассматривать «кластер внутри кластера»? 

vcluster

Надеюсь, вы смотрели культовый фильм «Начало». Мне он очень понравился, и я время от времени смотрю его снова. Идея была довольно запоминающейся: «Сон внутри сна».

Технология виртуализации следует той же идее. Если вы знакомы с Docker, то много лет назад возникла необходимость в docker-in-docker. Сегодня это очень распространенный подход в конвейерах CI/CD. Скажем, например, задачи выполняются в контейнере, но вам нужно протестировать приложение, уже встроенное в другой контейнер. Это и будет примером использования docker-in-docker.

Учитывая эту идею, что мешает нам попробовать кластер-в-кластере? Именно здесь на помощь приходит vcluster, который предлагает некоторые преимущества. vcluster позволяет создавать и управлять виртуальными кластерами Kubernetes. Виртуальный кластер — это, по сути, плоскость управления, которая работает в пространстве имен на общем хост-кастере. Вот визуализация:

На рисунке видно, что Gloo Mesh, которому раньше требовалось три кластера для моделирования среды, готовой к производству, теперь нужен всего один кластер с тремя виртуальными кластерами.

Быстрые преимущества:

  • Экономическая эффективность: Теперь ваши затраты составляют всего один кластер. Правда, он должен быть больше, чем раньше, но вы экономите деньги, развертывая один кластер вместо трех.
  • Экономия времени: когда вы работаете в локальной среде, вы не хотите тратить время на создание новых кластеров. Если вы используете kind, создание трех новых кластеров может занять несколько минут. С помощью vcluster вы можете получить три новых кластера примерно за 20 секунд.

Давайте докажем все это на семинаре.

Руки вверх!

На этом семинаре за считанные секунды вы развернете Istio на двух кластерах рабочей нагрузки, демонстрационное приложение для использования в лабораториях и Gloo Mesh для тестирования сетевых возможностей приложения (многокластерный трафик, разделение трафика, внедрение сбоев и т.д.). Все это основано всего лишь на одном хост-кластере Kubernetes, содержащем три виртуальных кластера.

Ваша архитектура будет выглядеть следующим образом:

Предварительные условия

  • Кластер Kubernetes, который будет являться хост-кластером (kind, k3s, k0s и т.д.).
  • vcluster CLI. Это было протестировано с версией 0.10.2
  • Helm v3
  • Kubectl
  • meshctl

Начало работы

Давайте проверим, сколько времени потребуется на развертывание. Тест проводился с использованием виртуальной машины, имеющей всего три процессора. Поэтому вы также развернете компоненты с минимальными ресурсами.

Начните с настройки некоторых переменных окружения:

# Context name for the host cluster
export MAIN_CONTEXT=$(kubectl config current-context)

# Context names for the gloo mesh clusters (vclusters)
export MGMT_CLUSTER=devmgmt
export CLUSTER_1=devcluster1
export CLUSTER_2=devcluster2
Войти в полноэкранный режим Выйти из полноэкранного режима

Установите окружения

Сначала создадим управляющий кластер:

cat << EOF > vcluster-values.yaml
isolation:
  enabled: false
  limitRange:
    enabled: false
  podSecurityStandard: privileged
  resourceQuota:
    enabled: false
rbac:
  clusterRole:
    create: true
syncer:
  resources:
    limits:
      cpu: 100m
      memory: 1Gi
    requests:
      cpu: 100m
      memory: 128Mi
  extraArgs:
  - --fake-nodes=false
  - --sync-all-nodes
vcluster:
  resources:
    limits:
      cpu: 200m
      memory: 2Gi
    requests:
      cpu: 100m
      memory: 256Mi
  extraArgs:
  - --kubelet-arg=allowed-unsafe-sysctls=net.ipv4.*
  - --kube-apiserver-arg=feature-gates=EphemeralContainers=true
  - --kube-scheduler-arg=feature-gates=EphemeralContainers=true
  - --kubelet-arg=feature-gates=EphemeralContainers=true
  image: rancher/k3s:v1.22.5-k3s1
EOF


vcluster create $MGMT_CLUSTER -n $MGMT_CLUSTER --upgrade --connect=false --expose -f vcluster-values.yaml --context $MAIN_CONTEXT

vcluster connect $MGMT_CLUSTER -n $MGMT_CLUSTER --kube-config-context-name $MGMT_CLUSTER --update-current --context $MAIN_CONTEXT

kubectl --context $MGMT_CLUSTER get namespaces
Войти в полноэкранный режим Выйти из полноэкранного режима

Далее, кластер рабочей нагрузки 1:

vcluster create $CLUSTER_1 -n $CLUSTER_1 --upgrade --connect=false --expose -f vcluster-values.yaml --context $MAIN_CONTEXT

vcluster connect $CLUSTER_1 -n $CLUSTER_1 --kube-config-context-name $CLUSTER_1 --update-current --context $MAIN_CONTEXT

kubectl --context $CLUSTER_1 get namespaces
Войдите в полноэкранный режим Выход из полноэкранного режима

И, наконец, кластер рабочей нагрузки 2:

vcluster create $CLUSTER_2 -n $CLUSTER_2 --upgrade --connect=false --expose -f vcluster-values.yaml --context $MAIN_CONTEXT

vcluster connect $CLUSTER_2 -n $CLUSTER_2 --kube-config-context-name $CLUSTER_2 --update-current --context $MAIN_CONTEXT

kubectl --context $CLUSTER_2 get namespaces
Войти в полноэкранный режим Выход из полноэкранного режима

Вот и все! Три кластера примерно за 20 секунд. Если вам интересно узнать больше, в конце этой заметки вы найдете более подробное объяснение того, что вы развернули с помощью vcluster, а также несколько советов, которые следует запомнить.

Теперь необходимо развернуть Istio в кластерах рабочих нагрузок:

Установите Gloo Mesh

Вам понадобится лицензионный ключ:

export GLOO_MESH_LICENSE_KEY=<license_key>
Войдите в полноэкранный режим Выйти из полноэкранного режима

И вам нужно определить версию Gloo Mesh:

export GLOO_MESH_VERSION=2.0.9
Войти в полноэкранный режим Выйти из полноэкранного режима

Gloo Mesh может быть установлен через графики Helm. Однако, чтобы не переполнять этот пост кодом, вы будете использовать meshctl CLI:

meshctl install --kubecontext $MGMT_CLUSTER --license $GLOO_MESH_LICENSE_KEY --version $GLOO_MESH_VERSION
Войти в полноэкранный режим Выйти из полноэкранного режима

Убедитесь, что все подсистемы запущены:

kubectl get pods -n gloo-mesh --context $MGMT_CLUSTER
Войти в полноэкранный режим Выйти из полноэкранного режима

И вы увидите что-то вроде:

NAME                                     READY   STATUS    RESTARTS   AGE
gloo-mesh-mgmt-server-778d45c7b5-5d9nh   1/1     Running   0          41s
gloo-mesh-redis-844dc4f9-jnb4j           1/1     Running   0          41s
gloo-mesh-ui-749dc7875c-4z77k            3/3     Running   0          41s
prometheus-server-86854b778-r6r52        2/2     Running   0          41s
Войти в полноэкранный режим Выйти из полноэкранного режима

Регистрация кластеров рабочей нагрузки

Gloo Mesh работает на основе агентского подхода. Поэтому при регистрации кластера рабочих нагрузок необходимо указать агенту, как общаться с сервером управления. 

Обратите внимание, что в EKS служба возвращает не IP, а Адрес. Если вы используете EKS, выполните эту настройку следующими командами.

MGMT_SERVER_NETWORKING_DOMAIN=$(kubectl get svc -n gloo-mesh gloo-mesh-mgmt-server --context $MGMT_CLUSTER -o jsonpath='{.status.loadBalancer.ingress[0].ip}')

MGMT_SERVER_NETWORKING_PORT=$(kubectl -n gloo-mesh get service gloo-mesh-mgmt-server --context $MGMT_CLUSTER -o jsonpath='{.spec.ports[?(@.name=="grpc")].port}')


MGMT_SERVER_NETWORKING_ADDRESS=${MGMT_SERVER_NETWORKING_DOMAIN}:${MGMT_SERVER_NETWORKING_PORT}
echo $MGMT_SERVER_NETWORKING_ADDRESS
Войти в полноэкранный режим Выйти из полноэкранного режима

Зарегистрируйте кластер рабочей нагрузки. Это также приведет к развертыванию агента:

meshctl cluster register 
  --remote-context=$CLUSTER_1 
  --relay-server-address $MGMT_SERVER_NETWORKING_ADDRESS 
  --kubecontext $MGMT_CLUSTER 
  $CLUSTER_1
Войти в полноэкранный режим Выйдите из полноэкранного режима

И вы увидите:

Registering cluster
📃 Copying root CA relay-root-tls-secret.gloo-mesh to remote cluster from management cluster
📃 Copying bootstrap token relay-identity-token-secret.gloo-mesh to remote cluster from management cluster
💻 Installing relay agent in the remote cluster
Finished installing chart 'gloo-mesh-agent' as release gloo-mesh:gloo-mesh-agent
📃 Creating remote.cluster KubernetesCluster CRD in management cluster
⌚ Waiting for relay agent to have a client certificate
         Checking...
         Checking...
🗑 Removing bootstrap token
✅ Done registering cluster!
Войти в полноэкранный режим Выход из полноэкранного режима

Зарегистрируйте второй кластер рабочей нагрузки:

meshctl cluster register 
  --remote-context=$CLUSTER_2 
  --relay-server-address $MGMT_SERVER_NETWORKING_ADDRESS 
  --kubecontext $MGMT_CLUSTER 
  $CLUSTER_2

#### Check that the resource is created in management:

Войти в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl get kubernetescluster -n gloo-mesh —context $MGMT_CLUSTER


And you will see:

Войдите в полноэкранный режим Выйти из полноэкранного режима

Bash
ИМЯ ВОЗРАСТ
devcluster1 27s
devcluster2 23с


#### Install Istio

Istio by default requires some resources. In your local environment, you might not have the resources to deploy three clusters fully functional and two Istio service meshes. Therefore, we need to reduce the required resources for Istio. That’s fine as this is just a development environment.

NOTE: This post is using Istio v1.12.6:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
export ISTIO_VERSION=1.12.6


Install Istio’s CRDs:

Вход в полноэкранный режим Выйти из полноэкранного режима

Bash

Установите Istio CRDS кластер1

helm upgrade —install istio-base istio/base
-n istio-system
—version $ISTIO_VERSION
—kube-context $CLUSTER_1
—create-namespace

Установите Istio CRDS кластер2

helm upgrade —install istio-base istio/base
-n istio-system
—version $ISTIO_VERSION
—kube-context $CLUSTER_2
—create-namespace


Install Istiod:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
cat << EOF > istiod-common-values.yaml
meshConfig:
accessLogFile: /dev/stdout
defaultConfig:
holdApplicationUntilProxyStarts: true
envoyMetricsService:
адрес: gloo-mesh-agent.gloo-mesh:9977
envoyAccessLogService:
адрес: gloo-mesh-agent.gloo-mesh:9977
proxyMetadata:
ISTIO_META_DNS_CAPTURE: «true»
ISTIO_META_DNS_AUTO_ALLOCATE: «true»
пилот:
autoscaleEnabled: false
replicaCount: 1
env:
PILOT_SKIP_VALIDATE_TRUST_DOMAIN: «true»
ресурсы:
запросы:
процессор: 10 м
память: 2048Mi
ограничения:
процессор: 10m
память: 2048Mi
EOF

Установите кластер istiod cluster1

helm upgrade —install istiod istio/istiod
-f istiod-common-values.yaml
—set global.meshID=mesh1
—set global.multiCluster.clusterName=$CLUSTER_1
—set meshConfig.trustDomain=$CLUSTER_1
—set meshConfig.defaultConfig.proxyMetadata.GLOO_MESH_CLUSTER_NAME=$CLUSTER_1
—namespace istio-system
—version $ISTIO_VERSION
—kube-context $CLUSTER_1

Установите кластер istiod cluster2

helm upgrade —install istiod istio/istiod
-f istiod-common-values.yaml
—set global.meshID=mesh1
—set global.multiCluster.clusterName=$CLUSTER_2
—set meshConfig.trustDomain=$CLUSTER_2
—set meshConfig.defaultConfig.proxyMetadata.GLOO_MESH_CLUSTER_NAME=$CLUSTER_2
—namespace istio-system
—version $ISTIO_VERSION
—kube-context $CLUSTER_2


Install ingress gateways:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
cat << EOF > istio-ingress-common-values.yaml
replicaCount: 1
автомасштабирование:
включено: false
имя: istio-ingressgateway
securityContext: # runAsRoot
runAsUser: 1337
runAsGroup: 1337
runAsNonRoot: true
fsGroup: 1337
метки:
istio: ingressgateway
сервис:
тип: LoadBalancer
порты:

  • порт: 80targetPort: 8080 имя: http2
  • порт: 443targetPort: 8443 имя: httpsresources:limits:cpu: 10mmemory: 128Mirequests:cpu: 10mmemory: 128MiEOF

Установите Istio Ingress Gateway Cluster 1

helm upgrade —install istio-ingressgateway istio/gateway
-f istio-ingress-common-values.yaml
—namespace istio-gateways
—version $ISTIO_VERSION
—kube-context $CLUSTER_1
—create-namespace

Установка Istio Ingress Gateway Cluster 2

helm upgrade —install istio-ingressgateway istio/gateway
-f istio-ingress-common-values.yaml
—namespace istio-gateways
—version $ISTIO_VERSION
—kube-context $CLUSTER_2
—create-namespace


Install east-west gateways:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
cat << EOF > istio-eastwest-common-values.yaml
replicaCount: 1
автомасштабирование:
включено: false
имя: istio-eastwestgateway
securityContext: # runAsRoot
runAsUser: 1337
runAsGroup: 1337
runAsNonRoot: true
fsGroup: 1337
метки:
istio: eastwestgateway
сервис:
тип: LoadBalancer
порты:

  • имя: tcp-status-portport: 15021targetPort: 15021
  • имя: tlsport: 15443targetPort: 15443resources:requests:cpu: 10mmemory: 128Milimits:cpu: 10mmemory: 128MiEOF

Установка Istio Eastwest Gateway Cluster 1

helm upgrade —install istio-eastwestgateway istio/gateway
-f istio-eastwest-common-values.yaml
—namespace istio-gateways
—version $ISTIO_VERSION
—kube-context $CLUSTER_1

Установка Istio Eastwest Gateway Cluster 2

helm upgrade —install istio-eastwestgateway istio/gateway
-f istio-eastwest-common-values.yaml
—namespace istio-gateways
—version $ISTIO_VERSION
—kube-context $CLUSTER_2


#### Deploy Applications

In workload cluster 1:

Войдите в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context ${CLUSTER_1} create ns bookinfo
export bookinfo_yaml=https://raw.githubusercontent.com/istio/istio/1.11.4/samples/bookinfo/platform/kube/bookinfo.yaml
kubectl —context ${CLUSTER_1} label namespace bookinfo istio-injection=enabled

kubectl —context ${CLUSTER_1} apply -f ${bookinfo_yaml} -l ‘app,version notin (v3)’ -n bookinfo

kubectl —context ${CLUSTER_1} apply -f ${bookinfo_yaml} -l ‘account’ -n bookinfo


And in workload cluster 2:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context ${CLUSTER_2} create ns bookinfo

kubectl —context ${CLUSTER_2} label namespace bookinfo istio-injection=enabled

kubectl —context ${CLUSTER_2} apply -f ${bookinfo_yaml} -n bookinfo


Define your workspace (this is an abstraction given by Gloo Mesh to facilitate the organization of the workloads regardless the physical location):

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl apply —context $MGMT_CLUSTER -n gloo-mesh -f- <<EOF
apiVersion: admin.gloo.solo.io/v2
тип: Рабочее пространство
метаданные:
имя: разработчики
пространство имён: gloo-mesh
спецификация:
workloadClusters:

  • name: ‘*’namespaces:
    • имя: ‘*’EOF

kubectl apply —context $CLUSTER_1 -n gloo-mesh -f- <<EOF
apiVersion: admin.gloo.solo.io/v2
тип: WorkspaceSettings
метаданные:
имя: разработчики
пространство имён: gloo-mesh
спецификация:
опции:
serviceIsolation:
включено: false
федерация:
включено: false
EOF


Expose the application:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context ${CLUSTER_1} apply -f — <<EOF
apiVersion: networking.gloo.solo.io/v2
тип: VirtualGateway
метаданные:
имя: north-south-gw
пространство имен: istio-gateways
спецификация:
рабочие нагрузки:
— селектор:
метки:
istio: ingressgateway
кластер: ${CLUSTER_1}
слушатели:
— http: {}
порт:
номер: 80
allowedRouteTables:
— хост: ‘*’
EOF

kubectl —context ${CLUSTER_1} apply -f — <<EOF
apiVersion: networking.gloo.solo.io/v2
тип: RouteTable
метаданные:
имя: productpage
пространство имён: bookinfo
метки:
раскрывать: «true»
спецификация:
hosts:
— ‘*’
virtualGateways:
— имя: north-south-gw
пространство имен: istio-gateways
кластер: ${CLUSTER_1}
workloadSelectors: []
http:
— имя: productpage
матчеры:
— uri:
prefix: /
forwardTo:
направления:
— ссылка:
имя: страница продукта
пространство имён: bookinfo
порт:
номер: 9080
EOF


#### Verify the Environment

Next, let’s create a bit of traffic and see what the UI displays. For that, port-forward the Gloo Mesh UI component:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
export ENDPOINT_HTTP_GW_CLUSTER1=$(kubectl —context ${CLUSTER_1} -n istio-gateways get svc istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].*}’):80

for i in {0..100}; do curl -s -o /dev/null -w «%{http_code}
» $ENDPOINT_HTTP_GW_CLUSTER1/productpage; done


You should see:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
❯ for i in {0..100}; do curl -s -o /dev/null -w «%{http_code}
» $ENDPOINT_HTTP_GW_CLUSTER1/productpage; done
200
200
200
200
200
200


Now, let port-forward the UI:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context $MGMT_CLUSTER port-forward svc/gloo-mesh-ui -n gloo-mesh 8090


Go to: <http://localhost:8090/> and you will see all the information about your clusters and your workspaces.

![Gloo Mesh UI](https://loft.sh/blog/images/content/vcluster-gloo-4.png)

You can also see the amazing graph to help with understanding your own system: Observability

![Gloo Mesh graph](https://loft.sh/blog/images/content/vcluster-gloo-5.png)

That is all! You have achieved full control of the network in a matter of minutes in your local environment.

Now, you can test any capability that Gloo Mesh offers, including:

* Any kind of the policies that Gloo Mesh offers (such as failover, fault injection, outlier detection, retries, timeouts, traffic control, mirroring, rate limiting, and header and payload transformation)
* Access control
* Isolation of the services
* WAF
* Authentication with OIDC
* Authorization with OPA

## Tips for vcluster

Interested in learning more about vcluster? Here a simple diagram about how vcluster works:

![vcluster architecture diagram](https://loft.sh/blog/images/content/vcluster-gloo-6.png)

In the workshop you have deployed three vclusters. If you run:

Войдите в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context $MAIN_CONTEXT get sts -A


You will see:

Войти в полноэкранный режим Выйти из полноэкранного режима

Bash
ИМЯ ПРОСТРАНСТВА ИМЕН ГОТОВНОСТЬ ВОЗРАСТ
devmgmt devmgmt 1/1 3h7m
devcluster2 devcluster2 1/1 3h2m
devcluster1 devcluster1 1/1 3h3m


Each of these StatefulSets belong to one vcluster. In its attached volume is stored all the data regarding the deployed vcluster.

Getting closer, you will find that one of the containers of those StatefulSets is an entire [k3s](https://k3s.io/), a lightweight Kubernetes flavor. You could also use any of the supported kubernetes flavors: [eks, k0s and vanilla k8s](https://www.vcluster.com/docs/operator/other-distributions).

The other container is a [syncer](https://www.vcluster.com/docs/architecture/basics#vcluster-syncer), an application which copies the pods that are created within the vcluster to the underlying host cluster. This is the reason you can see all the resources if you are the admin of the “host” cluster, and only your resources if you are the admin of the vcluster.

You can think of the StatefulSet like the control plane of a vcluster. This is the reason why you need to be careful how to deploy its pods.

Let’s see it in your just created environment. In your vcluster, you will see:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context $MGMT_CLUSTER get pod -l app=gloo-mesh-mgmt-server -A

ИМЯ ПРОСТРАНСТВА ИМЕН СТАТУС ГОТОВНОСТИ

gloo-mesh gloo-mesh-mgmt-server-9fb55d686-w4n4l 1/1 Выполняется


But in the host cluster you will see:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
kubectl —context $MAIN_CONTEXT get pod -A -l vcluster.loft.sh/namespace=gloo-mesh

ИМЯ ПРОСТРАНСТВА
devcluster1 gloo-mesh-agent-df8c8c49d-jlhkh-x-gloo-mesh-x-devcluster1
devcluster2 gloo-mesh-agent-76b5b44b4f-56r5l-x-gloo-mesh-x-devcluster2
devmgmt gloo-mesh-mgmt-server-9fb55d686-w4n4l-x-gloo-mesh-x-devmgmt
devmgmt gloo-mesh-redis-794d79b7df-rlr99-x-gloo-mesh-x-devmgmt
devmgmt gloo-mesh-ui-cc98c5fc-tzq4s-x-gloo-mesh-x-devmgmt
devmgmt prometheus-server-647b488bb-r6hfc-x-gloo-mesh-x-devmgmt


Check the names. That is the translation layer that vcluster makes for you.

There are a couple of things to keep in mind when working with vclusters:

Reserve resources enough for those StatefulSet pods: It is a good practice to have nodes with resources dedicated solely to these pods and make sure that the pods are deployed in those nodes. The intention is that the StatefulSet pods (vcluster control planes) will not run out of resources which would dramatically impact the performance of the vcluster. To do this, you can play with taints and nodeselectors in the nodes.

Logs and Kubernetes metadata: Log Aggregators tools like [Fluentbit](https://fluentbit.io/) and [Grafana Promtail](https://grafana.com/docs/loki/latest/clients/promtail/) rely on the Kubernetes structure and naming convention. Log folders and files follow the kubernetes structure given by the host cluster.

From the command above, you could see that the same pod has different names in vcluster and in the host. Therefore, if you deploy one of the observability tools mentioned before in the vcluster, the expected structures will not match the one in the host cluster.The consequence is that the vcluster will not be able to leverage the Kubernetes metadata, nor the log traces from the applications in that cluster. This issue is currently being addressed by the [Loft Labs](https://loft.sh/) team at the time of writing this post.

The last interesting point to mention is the capability to pause/resume individual vcluster (StatefulSets). In case you do not want to destroy the entire environment created in the workshop you can just do:

Вход в полноэкранный режим Выход из полноэкранного режима

Bash
vcluster pause $MGMT_CLUSTER -n $MGMT_CLUSTER —context $MAIN_CONTEXT
vcluster pause $CLUSTER_1 -n $CLUSTER_1 —context $MAIN_CONTEXT
vcluster pause $CLUSTER_2 -n $CLUSTER_2 —context $MAIN_CONTEXT


And whenever you want to keep working on the tests you can do:

Войдите в полноэкранный режим Выход из полноэкранного режима

Bash
vcluster resume $MGMT_CLUSTER -n $MGMT_CLUSTER —context $MAIN_CONTEXT
vcluster resume $CLUSTER_1 -n $CLUSTER_1 —context $MAIN_CONTEXT
vcluster resume $CLUSTER_2 -n $CLUSTER_2 —context $MAIN_CONTEXT




## Conclusions

Technology changes fast. Not many years ago, we were working with monoliths. Nowadays, you can have clusters deployed within another clusters.

Through this workshop, you were able to:

* Deploy all the components of Gloo Mesh in your local environment or in a cheap remote environment.
* Basic setup to test all Gloo Mesh capabilities to handle east-west and north-south traffic between your services.
* Reduce cost of deploying multiple clusters with vcluster. You just need one actual cluster.
* Reduce time of testing things out in a local environment.

This increases exponentially the efficiency in your projects. Which, at the end, is translated into an increase in productivity.

As a final comment, you can see that being able to test things in your local environment, reproducing heavy remote environments, is one of the goals of the DevOps practices.

If you want to talk more about all these tools, you can find me easily in these Slack workspaces: [solo.io](http://solo-io.slack.com), [istio](http://istio.slack.com) and [loft.sh](http://loft-sh.slack.com)
Вход в полноэкранный режим Выход из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий