Что такое pod openshift

Тестирование в Openshift: Внутреннее устройство кластера

Это продолжение серии из трех статей (первая статья, третья статья) об автоматизированном тестировании программных продуктов в Openshift Origin. В данной статье будут описаны основные объекты Openshift, а также описаны принципы работы кластера. Я осознано не делаю попытку описать все возможные объекты и их особенности, так как это очень трудоемкая задача, которая выходит за рамки данной статьи.

Кластер:

Что такое pod openshift. Смотреть фото Что такое pod openshift. Смотреть картинку Что такое pod openshift. Картинка про Что такое pod openshift. Фото Что такое pod openshift

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

Для запуска контейнеров требуется Docker образа, которые могут быть загружены из внутреннего или внешнего регистра. Непосредственно запуск контейнеров происходит в различных контекстах безопасности (политики безопасности, которые ограничивают доступ контейнера к различным ресурсам).

По умолчанию контейнеры из разных проектов могут коммуницировать друг с другом с помощью overlay сети (выделяется одна большая подсеть, которая разбивается на более мелкие подсети для всех рабочих узлов кластера). Запущенному на рабочем узле контейнеру выделяется IP-адрес из той подсети, которая была назначена данному узлу. Сама overlay сеть построена на базе Open vSwitch, который использует VXLAN для связи между рабочими узлами.

На каждом рабочем узле запускается выделенныё экземпляр Dnsmasq, который перенаправляет все DNS запросы контейнеров на SkyDNS во внутреннюю сервисную подсеть.

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

Стоит отметить что:

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

По умолчанию используется LVM в качестве хранилища Docker Engine. Это далеко не самое быстрое решение, но можно использовать любой другой тип хранилища (BTRFS, например).

Стоит иметь ввиду, что название сервиса (см. Service) — это DNS имя, которое влечет за собой ограничения на длину и допустимые символы.

Чтобы сократить временные и аппаратные издержки при сборке Docker образов можно использовать так называемый «слоистый» подход (multi-stage в Docker). В данном подходе используются базовые и промежуточные образа, которые дополняют друг друга. Имеем базовый образ «centos:7» (полностью обновлен), имеем промежуточный образ «centos:7-tools» (установлены иструменты), имеем финальный образ «centos:7-app» (содержит «centos:7» и «centos:7-tools»). То есть вы можете создавать задачи сборки, которые основываются на других образах (см. BuildConfig).

Достаточно гибким решением является подход, когда существует один проект, который занимается только сборкой Docker образов с последующей «линковкой» данных образов в другие проекты (см. ImageStream). Это позволяет не плодить лишних сущностей в каждом проекте и приведет к некой унификации.

Большинству объектов в кластере можно присвоить произвольные метки, с помощью которых можно совершать массовые операции над данными объектами (удаление определенных контейнеров в проекте, например).

Стоит сразу побеспокоиться об удалении старых образов и забытых окружений. Если первое решается с помощью сборщика мусора/oadm prune, то второе требует проработки и ознакомлении всех участников с правилами совместной работы в Openshift Origin.

Любой кластер ограничен ресурсами, поэтому очень желательно организовать мониторинг хотя бы на уровне рабочих узлов (возможен мониторинг на уровне приложения в контейнере). Сделать это можно как с помощью готового решения Openshift Metrics, так и с помощью сторонних решений (Sysdig, например). При наличии метрик загруженности кластера (в целом или по проектно) можно организовать гибкую диспетчерезацию поступающих задач.

Особенно хочется отметить тот факт, что рабочие узлы могут быть динамически проинициализированы, а это значит, что вы можете расширить свой кластер Openshift Origin на существующих мощностях IaaS. То есть, во время предрелизного тестирования вы можете существенно расширить свои мощности и сократить время тестирования.

Объекты:

Project — объект является Kubernetes namespace. Верхний уровень абстракции, который содержит другие объекты. Созданные в проекте объекты не пересекаются с объектами в других проектах. На проект могут быть выставлены квоты, привилегии, метки узлов кластера и т.д. Вложенная иерархия и наследование между проектами отсутствуют, доступна «плоская» структура проектов. Существуюет несколько системных проектов (kube-system, openshift, openshift-infra), которые предназначены для нормального функционирования кластера.

Создание нового проекта:

Редактирование настроек проекта:

Pod — объект, который стал одним из решающих факторов, так как позволяет запускать произвольные команды внутри контейнера с помощью специальных хуков (и не только). Pod является основной рабочей единицей в кластере. Любой запущенный в кластере контйенер — Pod. По своей сути — группа из одного и более контейнеров, которые работают в единых для этих контейнеров namespaces (network, ipc, uts, cgroup), используют общее хранилище данных, секреты. Контейнеры, из которых состоит Pod, всегда запущены на одном узле кластера, а не распределены в одинаковых пропорциях по всем узлам (если Pod будет состоять из 10 контейнеров, все 10 будут работать на одном узле).

Secret — может являться строкой или файлом, предназначен для проброса чувствительной (хранится в открытом виде в etcd (поддержка шифрования в Kubernetes 1.7)) информации в Pod. Один Secret может содержать множество значений.

Использование Secret в BuildConfig:

ServiceAccount — специальный тип объекта, который предназначен для взаимодействия с ресурсам кластера. По своей сути является системным пользователем.

По умолчанию новый проект содержит три ServiceAccount:

Перечисленные служебные аккаунты:

Добавление прав администратора проекта ServiceAccount:

DeploymentConfig — это объект, который оперирует всё теми же Pod, но при этом привносит ряд дополнительных механизмов для управления жизненным циклом запущенных приложений, а именно:

ImageStream — по своей сути является «контейнером» для «ссылок» (ImageStreamTag), которые указывают на Docker образа или другие ImageStream.

Создание тага/ссылки на Docker образ между проектами:

Создание тага/ссылки на Docker образ, который расположен на Docker Hub:

BuildConfig — объект является сценарием того, как будет собран Docker образ и куда он будет помещен. Сборка нового образа может базироваться на других образах, за это отвечает секция «from:»

Источники сборки (то место, где размещены исходные данные для сборки):

Стратегии сборки (каким образом следует интерпретировать источник данных):

Назначение сборки (куда будет выгружен собранный образ):

Какие операции выполнит данный BuildConfig:

Service — объект, который стал одним из решающих факторов при выборе системы запуска сред, так как он позволяет гибко настраивать коммуникации между средами (что очень важно в тестировании). В случаях с использованием других систем требовались подготовительные манипуляции: выделить диапазоны IP-адресов, зарегистрировать DNS имена, осуществить проброс портов и т.д. и т.п. Service может быть объявлен до фактического развертывания приложения.

Что происходит во время публикации сервиса в проекте:

Разрешение DNS имени:

Заключение:

Все объекты кластера можно описать с помощью YAML, это, в свою очередь, дает возможность полностью автоматизировать любые процессы, которые протекают в Openshift Origin. Вся сложность в работе с кластером заключается в знании приципов работы и механизмов взаимодействия объектов. Такие рутинные операции как инициализация новых рабочих узлов берут на себя сценарии Ansible. Доступность API открывает возможность работать с кластером напрямую минуя посредников.

Источник

OpenShift — базовая концепция

Прежде чем начать с фактической настройки и развертывания приложений, нам необходимо понять некоторые основные термины и понятия, используемые в OpenShift V3.

Контейнеры и изображения

Изображений

Это основные строительные блоки OpenShift, которые формируются из образов Docker. В каждом модуле OpenShift кластер имеет свои собственные изображения, работающие внутри него. Когда мы настраиваем модуль, у нас есть поле, которое будет объединено в реестр. Этот файл конфигурации извлечет образ и развернет его на узле кластера.

Чтобы вытащить и создать из него образ, выполните следующую команду. OC — ​​это клиент для связи со средой OpenShift после входа в систему.

Контейнер

Это создается, когда образ Docker развертывается в кластере OpenShift. При определении любой конфигурации мы определяем секцию контейнера в файле конфигурации. Внутри одного контейнера может быть несколько образов, и все контейнеры, работающие на узле кластера, управляются OpenShift Kubernetes.

Ниже приведены спецификации для определения контейнера, в котором работает несколько изображений.

В приведенной выше конфигурации мы определили многоконтейнерный модуль с двумя образами Tomcat и MongoDB внутри.

Стручки и Услуги

Pod можно определить как коллекцию контейнера и его хранилище внутри узла кластера OpenShift (Kubernetes). В общем, у нас есть два типа контейнеров, начиная с одного контейнера и заканчивая несколькими контейнерами.

Single Container Pod — Они могут быть легко созданы с помощью команды OC или файла базовой конфигурации yml.

Создайте его с помощью простого файла yaml следующим образом.

Как только вышеуказанный файл будет создан, он сгенерирует модуль с помощью следующей команды.

Multi-Container Pod — это несколько контейнеров, в которых у нас работает более одного контейнера. Они создаются с использованием файлов yaml следующим образом.

После создания этих файлов мы можем просто использовать тот же метод, что и выше, для создания контейнера.

Сервис — Поскольку у нас есть набор контейнеров, работающих внутри модуля, таким же образом у нас есть сервис, который можно определить как логический набор модулей. Это абстрактный слой поверх модуля, который предоставляет одно имя IP и DNS, через которое можно получить доступ к модулям. Сервис помогает управлять конфигурацией балансировки нагрузки и очень легко масштабировать модуль. В OpenShift сервис — это объект REST, обожествление которого можно опубликовать в apiService на главном сервере OpenShift для создания нового экземпляра.

Строит и Потоки

Строит

В OpenShift сборка — это процесс преобразования изображений в контейнеры. Это обработка, которая преобразует исходный код в изображение. Этот процесс сборки работает по заранее определенной стратегии построения исходного кода для изображения.

Сборка обрабатывает несколько стратегий и источников.

Стратегии сборки

Source to Image — это в основном инструмент, который помогает в создании воспроизводимых изображений. Эти образы всегда находятся в состоянии готовности к запуску с помощью команды запуска Docker.

Сборка Docker — это процесс, в котором изображения создаются с использованием файла Docker с помощью простой команды сборки Docker.

Custom Build — это сборки, которые используются для создания базовых образов Docker.

Source to Image — это в основном инструмент, который помогает в создании воспроизводимых изображений. Эти образы всегда находятся в состоянии готовности к запуску с помощью команды запуска Docker.

Источник

Pods and Services

OpenShift Container Platform leverages the Kubernetes concept of a pod, which is one or more containers deployed together on one host, and the smallest compute unit that can be defined, deployed, and managed.

Pods are the rough equivalent of a machine instance (physical or virtual) to a container. Each pod is allocated its own internal IP address, therefore owning its entire port space, and containers within pods can share their local storage and networking.

Pods have a lifecycle; they are defined, then they are assigned to run on a node, then they run until their container(s) exit or they are removed for some other reason. Pods, depending on policy and exit code, may be removed after exiting, or may be retained in order to enable access to the logs of their containers.

OpenShift Container Platform treats pods as largely immutable; changes cannot be made to a pod definition while it is running. OpenShift Container Platform implements changes by terminating an existing pod and recreating it with modified configuration, base image(s), or both. Pods are also treated as expendable, and do not maintain state when recreated. Therefore pods should usually be managed by higher-level controllers, rather than directly by users.

The recommended maximum number of pods per OpenShift Container Platform node host is 110.

Bare pods that are not managed by a replication controller will be not rescheduled upon node disruption.

Below is an example definition of a pod that provides a long-running service, which is actually a part of the OpenShift Container Platform infrastructure: the integrated container registry. It demonstrates many features of pods, most of which are discussed in other topics and thus only briefly mentioned here:

This pod definition does not include attributes that are filled by OpenShift Container Platform automatically after the pod is created and its lifecycle begins. The Kubernetes API documentation has complete details of the pod REST API object attributes, and the Kubernetes pod documentation has details about the functionality and purpose of pods.

Pod Restart Policy

A pod restart policy determines how OpenShift Container Platform responds when containers in that pod exit. The policy applies to all containers in that pod.

The possible values are:

Once bound to a node, a pod will never be bound to another node. This means that a controller is necessary in order for a pod to survive node failure:

Pods that are expected to terminate (such as batch computations)

OnFailure or Never

Pods that are expected to not terminate (such as web servers)

Pods that need to run one-per-machine

If an entire pod fails, OpenShift Container Platform starts a new pod. Developers need to address the possibility that applications might be restarted in a new pod. In particular, applications need to handle temporary files, locks, incomplete output, and so forth caused by previous runs.

For details on how OpenShift Container Platform uses restart policy with failed containers, see the Example States in the Kubernetes documentation.

Init Containers

An init container is a container in a pod that is started before the pod app containers are started. Init containers can share volumes, perform network operations, and perform computations before the remaining containers start. Init containers can also block or delay the startup of application containers until some precondition is met.

When a pod starts, after the network and volumes are initialized, the init containers are started in order. Each init container must exit successfully before the next is invoked. If an init container fails to start (due to the runtime) or exits with failure, it is retried according to the pod restart policy.

A pod cannot be ready until all init containers have succeeded.

See the Kubernetes documentation for some init container usage examples.

Init containers can include activeDeadlineSeconds on the pod and livenessProbe on the container to prevent init containers from failing forever. The active deadline includes init containers.

Services

A Kubernetes service serves as an internal load balancer. It identifies a set of replicated pods in order to proxy the connections it receives to them. Backing pods can be added to or removed from a service arbitrarily while the service remains consistently available, enabling anything that depends on the service to refer to it at a consistent address. The default service clusterIP addresses are from the OpenShift Container Platform internal network and they are used to permit pods to access each other.

To permit external access to the service, additional externalIP and ingressIP addresses that are external to the cluster can be assigned to the service. These externalIP addresses can also be virtual IP addresses that provide highly available access to the service.

Services are assigned an IP address and port pair that, when accessed, proxy to an appropriate backing pod. A service uses a label selector to find all the containers running that provide a certain network service on a certain port.

Like pods, services are REST objects. The following example shows the definition of a service for the pod defined above:

12345
The service name docker-registry is also used to construct an environment variable with the service IP that is inserted into other pods in the same namespace. The maximum name length is 63 characters.
The label selector identifies all pods with the docker-registry=default label attached as its backing pods.
Virtual IP of the service, allocated automatically at creation from a pool of internal IPs.
Port the service listens on.
Port on the backing pods to which the service forwards connections.

The Kubernetes documentation has more information on services.

Service externalIPs

In addition to the cluster’s internal IP addresses, the user can configure IP addresses that are external to the cluster. The administrator is responsible for ensuring that traffic arrives at a node with this IP.

The externalIPs must be selected by the cluster adminitrators from the externalIPNetworkCIDRs range configured in master-config.yaml file. When master-config.yaml is changed, the master services must be restarted.

1
List of external IP addresses on which the port is exposed. This list is in addition to the internal IP address list.

Service ingressIPs

In non-cloud clusters, externalIP addresses can be automatically assigned from a pool of addresses. This eliminates the need for the administrator manually assigning them.

The pool is configured in /etc/origin/master/master-config.yaml file. After changing this file, restart the master service.

The ingressIPNetworkCIDR is set to 172.29.0.0/16 by default. If the cluster environment is not already using this private range, use the default range or set a custom range.

If you are using high availability, then this range must be less than 256 addresses.

Service NodePort

Setting the service type=NodePort will allocate a port from a flag-configured range (default: 30000-32767), and each node will proxy that port (the same port number on every node) into your service.

To specify a custom port just place the port number in the nodePort field. The custom port number must be in the configured range for nodePorts. When ‘master-config.yaml‘ is changed the master services must be restarted.

The service will be visible as both the :spec.ports[].nodePort and spec.clusterIp:spec.ports[].port

Setting a nodePort is a privileged operation.

Service Proxy Mode

OpenShift Container Platform has two different implementations of the service-routing infrastructure. The default implementation is entirely iptables-based, and uses probabilistic iptables rewriting rules to distribute incoming service connections between the endpoint pods. The older implementation uses a user space process to accept incoming connections and then proxy traffic between the client and one of the endpoint pods.

The iptables-based implementation is much more efficient, but it requires that all endpoints are always able to accept connections; the user space implementation is slower, but can try multiple endpoints in turn until it finds one that works. If you have good readiness checks (or generally reliable nodes and pods), then the iptables-based service proxy is the best choice. Otherwise, you can enable the user space-based proxy when installing, or after deploying the cluster by editing the node configuration file.

Headless services

If your application does not need load balancing or single-service IP addresses, you can create a headless service. When you create a headless service, no load-balancing or proxying is done and no cluster IP is allocated for this service. For such services, DNS is automatically configured depending on whether the service has selectors defined or not.

Services with selectors: For headless services that define selectors, the endpoints controller creates Endpoints records in the API and modifies the DNS configuration to return A records (addresses) that point directly to the pods backing the service.

Services without selectors: For headless services that do not define selectors, the endpoints controller does not create Endpoints records. However, the DNS system looks for and configures the following records:

For ExternalName type services, CNAME records.

For all other service types, A records for any endpoints that share a name with the service.

Creating a headless service

Creating a headless service is similar to creating a standard service, but you do not declare the ClusterIP address. To create a headless service, add the clusterIP: None parameter value to the service YAML definition.

For example, for a group of pods that you want to be a part of the same cluster or service.

You can define the headless service as:

123
Name of the headless service.
Setting clusterIP variable to None declares a headless service.
Selects all pods that have frontend label.

Also, headless service does not have any IP address of its own.

Endpoint discovery by using a headless service

The benefit of using a headless service is that you can discover a pod’s IP address directly. Standard services act as load balancer or proxy and give access to the workload object by using the service name. With headless services, the service name resolves to the set of IP addresses of the pods that are grouped by the service.

When you look up the DNS A record for a standard service, you get the loadbalanced IP of the service.

But for a headless service, you get the list of IPs of individual pods.

Labels

Labels are used to organize, group, or select API objects. For example, pods are «tagged» with labels, and then services use label selectors to identify the pods they proxy to. This makes it possible for services to reference groups of pods, even treating pods with potentially different containers as related entities.

Most objects can include labels in their metadata. So labels can be used to group arbitrarily-related objects; for example, all of the pods, services, replication controllers, and deployment configurations of a particular application can be grouped.

Labels are simple key/value pairs, as in the following example:

A pod consisting of an nginx container, with the label role=webserver.

A pod consisting of an Apache httpd container, with the same label role=webserver.

A service or replication controller that is defined to use pods with the role=webserver label treats both of these pods as part of the same group.

The Kubernetes documentation has more information on labels.

Endpoints

The servers that back a service are called its endpoints, and are specified by an object of type Endpoints with the same name as the service. When a service is backed by pods, those pods are normally specified by a label selector in the service specification, and OpenShift Container Platform automatically creates the Endpoints object pointing to those pods.

In some cases, you may want to create a service but have it be backed by external hosts rather than by pods in the OpenShift Container Platform cluster. In this case, you can leave out the selector field in the service, and create the Endpoints object manually.

Note that OpenShift Container Platform will not let most users manually create an Endpoints object that points to an IP address in the network blocks reserved for pod and service IPs. Only cluster admins or other users with permission to create resources under endpoints/restricted can create such Endpoint objects.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *