Docker Swarm для самых маленьких

Данная статья посвящена настройке и работе с Docker Swarm.
Swarm это стандартный оркестратор для docker контейнеров, доступный из «коробки», если у вас установлен сам docker.
Что нам потребуется для освоения:
Иметь опыт работы с docker и docker compose.
Настроенный docker registry. Swarm не очень любит работать с локальными образами.
Несколько виртуальных машин для создания кластера, хотя по факту кластер может состоять из одной виртуалки, но так будет нагляднее.
Термины
Для того чтобы пользоваться swarm надо запомнить несколько типов сущностей:
Node — это наши виртуальные машины, на которых установлен docker. Есть manager и workers ноды. Manager нода управляет workers нодами. Она отвечает за создание/обновление/удаление сервисов на workers, а также за их масштабирование и поддержку в требуемом состоянии. Workers ноды используются только для выполнения поставленных задач и не могут управлять кластером.
Stack — это набор сервисов, которые логически связаны между собой. По сути это набор сервисов, которые мы описываем в обычном compose файле. Части stack (services) могут располагаться как на одной ноде, так и на разных.
Service — это как раз то, из чего состоит stack. Service является описанием того, какие контейнеры будут создаваться. Если вы пользовались docker-compose.yaml, то уже знакомы с этой сущностью. Кроме стандартных полей docker в режиме swarm поддерживает ряд дополнительных, большинство из которых находятся внутри секции deploy.
Task — это непосредственно созданный контейнер, который docker создал на основе той информации, которую мы указали при описании service. Swarm будет следить за состоянием контейнера и при необходимости его перезапускать или перемещать на другую ноду.
Создание кластера
Для того чтобы кластер корректно работал, необходимо открыть следующие порты на виртуальных машинах. Для manager node:
Для worker node
Затем заходим на виртуальную машину, которая будет у нас manager node. И выполняем следующую команду:
Если все успешно, то в ответ вы получите следующую команду:
Ее будет необходимо выполнить на всех worker node, чтобы присоединить их в только что созданный кластер.
Если все прошло успешно, выполнив следующую команду на manager ноде в консоли, вы увидите что-то подобное:
У меня виртуалка с hostname dev-2 является manager , а stage является worker нодой.
В принципе мы готовы к тому, чтобы запускать services и stacks на нашей worker node.
Если мы хотим убрать ноду из кластера, необходимо зайти на виртуалку, которая является ею, и выполнить команду:
Если затем зайти на manager ноду и выполнить docker node ls , вы заметите, что статус у нее поменялся c Ready на Down (это может занять некоторое время). Swarm больше не будет использовать данную ноду для размещения контейнеров, и вы можете спокойно заняться техническими работами, не боясь нанести вред работающим контейнерам. Для того чтобы окончательно удалить ноду, надо выполнить (на manager node):
Стэк и Сервис
Для создания нашего стэка я возьму в качестве примера compose файл для node js web server, который прослушивает порт 4003:
В начале необходимо достать image из registry и только затем задеплоить в наш кластер:
Все эти команды надо выполнять на manager node. Опция —with-registry-auth позволяет передать авторизационные данные на worker ноды, для того чтобы использовался один и тот же образ из регистра. stage это имя нашего стэка.
Посмотреть список стэков можно с помощью:
Список сервисов внутри стэка:
Подробная информация о сервисе:
Тут видно, что для этого сервиса уже запускался контейнер (40 часов назад).
Для того чтобы увидеть более подробную информацию по сервису в виде JSON:
Тут также можно увидеть, какие порты слушает сервис, в каких сетях участвует, какой у него статус и много чего еще.
Удалить стэк можно следующим образом:
Можно запускать и отдельно взятые сервисы, например:
В данном примере мы запустили сервис nginx в виде 3 экземпляров, которые swarm раскидал по 3 нодам.
Удалить сервис можно следующим образом:
Label
Swarm по умолчанию развертывает сервисы на любой доступной ноде/нодах, но как правило нам необходимо развертывать их на конкретной ноде или на специфической группе. И тут нам как раз приходят на помощь labels.
Например, у нас есть stage и prod окружение. stage используется для внутренней демонстрации продукта, а prod как можно догадаться из названия, является непосредственно продакшеном.
Для каждого из окружений у нас есть compose файл: docker-compose.stage.yaml и docker-compose.prod.yaml . По умолчанию swarm будет раскидывать service произвольно по нодам. А нам бы хотелось, чтобы сервис для stage запускался только на stage виртуалке и аналогично для prod.
В начале, добавим еще одну ноду в кластер, в качестве worker :
Затем необходимо разметить наши ноды:
Используя hostname виртуалок, мы навешиваем label. Для того чтобы убедиться, что все прошло успешно, необходимо выполнить следующую команду:
Ищем раздел Spec.Labels , где мы должны увидеть label, который добавили:
После чего в наш compose файл необходимо добавить директиву placement , где прописывается условие, которое указывает, на каких нодах разворачивать данный сервис:
Для docker-compose.prod.yaml будет аналогично, но с тэгом prod (однако для внешнего мира надо использовать другой порт, например 4004). После деплоя данных stacks вы убедитесь, что сервисы разворачиваются только на нодах с определенным тэгом.
Маршрутизация
В данный момент у нас 3 ноды: manager нода, нода для stage версии приложения и еще одна для продакшена.
И если мы попытаемся задеплоить наш стэк для docker-compose.prod.yaml на том же 4003 порту, что и для уже запущенного стэка docker-compose.stage.yaml , мы получим ошибку, связанную с тем, что порт уже занят.
Хммм. почему это произошло? И более того, если мы зайдем на виртуальную машину prod-1 и сделаем curl 127.0.0.1:4003 , то увидим, что наш сервис доступен, хотя на этой ноде мы еще не успели ничего развернуть?

Связано это с тем, что у swarm имеется ingress сеть, которая используется для маршрутизации траффика между нодами. Если у сервиса есть публичный порт, то swarm слушает его и в случае поступления запроса на него делает следующее: определяет есть ли контейнер на этой хост машине и если нет, то находит ноду, на которой запущен контейнер для данного сервиса, и перенаправляет запрос туда.

В данном примере используется внешний балансировщик HAProxy, который балансирует запросы между тремя виртуалками, а дальше swarm перенаправляет запросы в соответствующие контейнеры.
Вот почему придется для docker-compose.prod.yaml использовать любой другой публичный порт, отличный от того, который мы указали в docker-compose.stage.yaml .
Отключить автоматическую маршрутизацию трафика можно с помощью mode: host при декларации ports :
В данном случае запрос, который придет на порт 4004, swarm будет направлять только на контейнер текущей ноде и никуда больше.
Кроме того, надо упомянуть про такую настройку как mode , хотя напрямую это не относится к маршрутизации. Она может принимать следующие значения: global или replicated (по умолчанию):
Если global это означает, что данный сервис будет запущен ровно в одном экземпляре на всех возможных нодах. А replicated означает, что n-ое кол-во контейнеров для данного сервиса будет запущено на всех доступных нодах.
Кроме того, советую почитать следующую статью про то, как устроены сети в swarm.
Zero downtime deployment
Одна из очень полезных фишек, которая есть из коробки, это возможность организовать бесшовную смену контейнеров во время деплоя. Да, с docker-compose это тоже возможно, но надо писать обвязку на bash/ansible или держать дополнительную реплику контейнера (даже, если по нагрузке требуется всего одна) и на уровне балансировщика переключать трафик с одного контейнера на другой.
С docker swarm это все не нужно, необходимо лишь немного скорректировать конфиг сервиса.
Для начала нужно добавить директиву healthcheck :
Она предназначена, чтобы docker мог определить, корректно ли работает ваш контейнер.
test — результат исполнения этой команды docker использует для определения корректно ли работает контейнер.
interval — с какой частотой проверять состояние. В данном случае каждые 30 секунд.
timeout — таймаут для ожидания выполнения команды.
retries — кол-во попыток для проверки состояния нашего сервера внутри контейнера.
После добавления данной директивы в compose file мы увидим в колонке Status информацию о жизненном состоянии контейнера.
После того как вы сделаете deploy вашему стэку, вы увидите, что контейнер сначала имеет статус starting (сервер внутри нашего контейнера запускается), а через некоторое время получит статус healthy (сервер запустился), в противном случае unhealthy. Docker в режиме swarm не просто отслеживает жизненное состояние контейнера, но и в случае перехода в состояние unhealthy попытается пересоздать контейнер.
После того, как мы научили docker следить за жизненным состоянием контейнера необходимо добавить настройки для обновления контейнера:
replicas это кол-во контейнеров, которые необходимо запустить для данного сервиса.
Директива update_config описывает каким образом сервис должен обновляться:
parallelism — кол-во контейнеров для одновременного обновления. По умолчанию данный параметр имеет значение 1 — контейнеры будут обновляться по одному. 0 — обновить сразу все контейнеры. В большинстве случаев это число должно быть меньше, чем общее кол-во реплик вашего сервиса.
order — Порядок обновления контейнеров. По умолчанию stop-first , сначала текущий контейнер останавливается, а затем запускается новый. Для бесшовного обновления нам нужно использовать start-first это когда вначале запускается новый контейнер, а затем выключается старый.
failure_action — стратегия в случае сбоя. Вариантов несколько: continue , rollback , или pause (по умолчанию).
delay — задержка между обновлением группы контейнеров.
Кроме того, полезна директива rollback_config , которая описывает поведение в случае сбоя во время обновления, а также директива restart_policy , которая описывает когда и как перезапускать контейнеры в случае проблем.
condition — есть несколько возможных вариантов none , on-failure or any .
delay — как долго ждать между попытками перезапуска.
max_attempts — максимальное кол-во попыток для перезапуска.
window — как долго ждать прежде, чем определить, что рестарт удался.
Для обновления нашего сервиса в запущенном стэке надо выполнить следующую команду:
Затем, если выполнить docker container ls на worker ноде, то мы увидим, что запустился новый контейнер со статусом starting, а когда он станет healthy, то swarm переключит трафик на новый контейнер, а старый остановит.
Благодаря директивам rollback_config и restart_policy мы описали, что будет делать swarm c контейнером в случае, если не удалось его запустить и в каком случае перезапускать контейнер, а также максимальное кол-во попыток и задержек между ними.
Вот так с помощью десятка строчек мы получили бесшовный деплой для наших контейнеров.
Секреты
Swarm предоставляет хранилище для приватных данных (secrets), которые необходимы контейнерам. Как правило эта функциональность используется для хранения логинов, паролей, ключей шифрования и токенов доступа от внешних систем, БД и т.д.
Создадим yaml файл c «суперсекретным» токеном:
Создадим секрет с именем back_config :
Для того чтобы им воспользоваться нам надо добавить 2 секции. Во-первых, секцию secrets , где мы укажем, что берем снаружи (из swarm) секрет под именем back_config . Во-вторых, подключим сам секрет в сервисе (тоже директива secrets ) по пути /p/ptm/config/config.json .
Ранее мы монтировали config.yaml, как volume, теперь же мы достаем его из swarm и монтируем его по указанному пути. Если мы теперь зайдем внутрь контейнера, то обнаружим, что наш секрет находится в /p/ptm/config/config.yaml .
Portainer
Кроме того, хочу упомянуть про такой инструмент как portainer. Вместо того, чтобы лазить постоянно на manager node и выполнять рутинные команды в консоли, можно использовать web панель для управления docker swarm. Это довольно удобный инструмент, позволяющий посмотреть в одном месте данные о стэках, сервисах и контейнерах. Можно отредактировать существующие сервисы, а также запустить новые. Кроме того, можно посмотреть логи запущенных контейнеров и даже зайти внутрь них удаленно. Ко всему прочему portainer может выступать в роли docker registry, а также предоставляет управление секретами и конфигами.
Для того чтобы его установить необходимо в начале скачать .yml файл с описанием сервисов:
Затем задеплоить его в наш кластер:
На каждом node будет установлен агент, который будет собирать данные, а на manager будет установлен сервер с web панелью.
Надо не забыть открыть порт 9443 на виртуальной машине, которая является manager :
Заходим в браузере на адрес https://ip:9443 .
Соглашаемся на то, что доверяем https сертификату (portainer, по умолчанию создает самоподписанный). Создаем пользователя и наслаждаемся.

Docker Swarm это несложный оркестратор для контейнеров, который доступен из коробки. Поверхностно с ним можно разобраться за пару дней, а глубоко за неделю. И по моему мнению, он закрывает большинство потребностей для маленьких и средних команд. В отличие от Kuberneteus он гораздо проще в освоении и не требует выделения дополнительных ресурсов в виде людей (отдельного человека или даже отдела) и железа. Если ваша команда разработки меньше 100 человек и вы не запускаете сотни уникальных типов контейнеров, то вам скорее всего вполне хватит его возможностей.
Swarm Agents (Part 1/2)
![]()
The swarms are something really awesome present in nature and it is something awesome because it is a set of individual beings that behave as if they are a unique entity. This phenomenon is called emergence and that Kurzgesagt video explains it perfectly.
As the buzzwords of the Neural Networks that have been inspired by the mammals' neural cells and their networks, the swarms present in nature inspire some other computational technique that is called swarm intelligence systems. Here we are going to discuss the swarm intelligence techniques in a really basic way, drawing an analysis of the autonomous agent systems. But don't worry with all these strong expressions that make anyone seems smarter after spelling all of them in a really fast way, we'll demystify all of them.
Agents
When we work with Artificial Intelligence we use to work with a concept called agents but calm down, aren't the smith agents.
The agents in AI are the smart entities that will perform an action in order to accomplish a task, whether this task is to optimize something, or it is to complete a path or even if it's to convert text to speech.
The agents in usual AI applications are individual agents that are usually as smart as possible to accomplish a really specific task, but there's one area called swarm intelligence where the objective of the agents isn't to be as smart as possible but cooperate in order to accomplish an objective. Those agents are particularly useful in two fields, the field of optimization with some algorithms such as ACO(Ant Colony Optimization) or PSO(Particle Swarm Optimization), and in the field of robotics, specifically, nanorobotics, because there are situations where build complex units with heavily consuming processors isn't possible but build some applications with a simple rule that emerges is way more efficient.
The most basic model to represent an intelligent agent is:
This kind of agent perceives the environment them based on it the agent takes some decisions in order to generate the actions.
The environment
When we threat from intelligent agents, the environment is something that is perceived by the agent. In robotics, the environment may be formed by robot sensors, in simulations the environment can be easily defined as the positions of every single agent in canvas for example, or even by some messages passing. Every agent is designed to perform in a specific environment, so, with some rules in the most simple intelligent being, it is a good way to perform interactions with really simple agents.
More than one agent
Once we stick more than one agent together we start creating agents colony. This colony part is way important to create swarm systems because they create an emergence from the crowd simplicity.
Take for example the birds flock. They do not have any mastermind intelligence controlling every single entity to say where it should go, but, the system as a whole performs as a single and complex entity.
In nature, there are lots of other examples of individual beings performing with this pretty complex behave. But as a curious and computer's scientist, I made some simulations of the particle swarm behavior.
In order to create a swarm intelligent system, we need to pay some attention, but the main framework is to define a lot of agents and them make them take some decisions by themselves and make the emergence happen.
In the next chapter, we may understand how to build a basic swarm system, pay attention that soon that text will be available.
Настраиваем Swarm
Если вы используете Lightmass и/или Precomputed Visibility, вы наверняка заметили, что процесс постройки уровня занимает много времени.
Swarm — это встроенная в UDK система распределенной постройки Lightmass и Precomputed Visibility. То есть, это инструмент, позволяющий раскинуть данную задачу на другие компы в локальной сети.
Swarm состоит из двух частей — Coordinator и Agent.
Понятно, что координатор будет управлять распределением ресурсов, а агент и будет самим ресурсом.
В общем случае, ваша локальная сеть будет выглядеть как сервер, с подключенными к нему клиентскими компами.
Часть из них будут рабочими для дизайнеров уровней, и соответственно на них будет установлен сам UDK. Другие, возможно, будут просто ресурсом, и устанавливать там UDK не обязательно.
Из папки Binaries, установленного UDK, берем следующие файлы:
для координатора:
— SwarmCoordinator.exe
— SwarmCoordinatorInterface.dll
для агента:
— AgentInterface.dll
— SwarmAgent.exe
— SwarmCoordinatorInterface.dll
— UnrealControls.dll
Складываем их в соответствующие папки и несем все это на сервер (в принципе, координатором не обязательно быть серверу, это может быть любой комп в сети).
Кладем, например, в C:\Swarm\SwarmCoordinator и C:\Swarm\SwarmAgent.
Добавляем SwarmCoordinator.exe и SwarmAgent.exe в автозагрузку.

Запускаем SwarmAgent.exe и переходим во вкладку Settings.

Задаем следующие значения:
CacheFolder: C:\Swarm\SwarmCache
AllowedRemoteAgentGroup: Default
AllowedRemoteAgentNames: *
AvoidLocalExecution: True
CoordinatorRemotingHost: SERVER (здесь IP или сетевое имя координатора)
Здесь особое значение имеют:
— AllowedRemoteAgentGroup — группа должна быть одна для всех агентов, иначе они не подхватятся.
— AllowedRemoteAgentNames — чтобы имена были любые я поставил *.
— AvoidLocalExecution — агент должен всегда избегать выполнения задачи локально, чтобы координатор раздал задачу другим агентам.
Если вы поставите ShowDeveloperMenu: True, появится еще одна вкладка с опциями разработчика.
В ней вам могут быть интересны поля LocalJobsDefaultProcessorCount, LocalJobsDefaultProcessPriority, RemoteJobsDefaultProcessorCount и RemoteJobsDefaultProcessPriority, которые означают количество ядер для локальной/удаленной задачи и приоритеты выполнения/подключения к задаче.
Хорошо, все настроено, и теперь, если вы заглянете в координатор, то увидите там первого агента, который запущен на этой машине.

То есть, координатор также может быть и агентом, но это опционально.
Немного о полях в координаторе:
Name – имя подключенного компа/агента.
Group Name – имя группы компа/агента.
Agent Version – версия агента. Обычно с каждым новым релизом UDK она меняется, так что не забывайте обновлять файлы.
State – состояние агента, меняется в зависимости от того подключен ли он к текущей задаче, доступен или занят, закрыт.
Cores for Local, Cores for Remote – количество ядер которые будут задействованы в задаче (устанавливается в описанных выше LocalJobsDefaultProcessorCount и RemoteJobsDefaultProcessorCount).
Загляните в папку C:\Swarm\SwarmAgent. Там добавились файлы SwarmAgent.DeveloperOptions.xml и SwarmAgent.Options.xml. Это опции, которые вы только что задали.
Теперь нужно установить агентов (но не координаторов) на другие машины. Берите все содержимое папки SwarmAgent (с файлами опций, не вводить же их повторно) и несите на другие компы.
Не забывайте добавлять SwarmAgent.exe в автозагрузку.
Когда процесс настройки завершен, и в координаторе видны все агенты, попробуйте на любой машине дизайнера построить уровень. Вы увидите, что в агенте этой машины будут выводиться процессы всех подключенных к задаче агентов. И то что строилось долгие часы, будет завершено за несколько минут.
Также старайтесь ставить агентов только на мощные машины, потому что, если часть задачи попадет слабому компу, он только будет задерживать процесс своей медленной обработкой.
Unreal Swarm
An overview of Unreal Swarm, our task distribution system for computationally expensive applications, including Unreal Lightmass, the high-quality static global illumination solver in Unreal Engine 4.
Choose your operating system:





Depending on your development environment, rendering large and open worlds can take a lot of time because computing lighting, shadows, and geometry can be expensive. There are several ways to reduce your project’s build time, such as upgrading your hardware beyond our recommended specifications or by utilizing a task distribution system, which is where Unreal Swarm comes in, reducing the time it takes to perform expensive computations, such as solving for high-quality static global illumination .
What is Unreal Swarm?
Unreal Swarm is a general application and task distribution system, comprised of two application types, one being a coordinator that distributes build task(s), and the other being an agent that utilizes the host system’s resources to complete its assigned job(s).

After setting up the Swarm, a Swarm Coordinator will manage the job(s) and task(s) of Swarm Agent(s) on your network.
Requirements
Before you can begin setting up Unreal Swarm:
Install Unreal Engine 4 (UE4) on at least one Windows machine in your network. You’ll use this machine to launch the Swarm Coordinator. See Installing Unreal Engine .
On each Windows machine that you want to act as a Swarm Agent, install the prerequisites required to run the Unreal Engine and editor. You can do this in any of the following ways:
Install the required version of the DirectX End-User Runtimes, which you can download from the link on the Hardware and Software Requirements page.
Run the prerequisite installer that is bundled with Unreal Engine, as decsribed on the Hardware and Software Requirements page.
Install the Epic Games Launcher and Unreal Engine.
Unreal Swarm currently runs only under Windows. The machine that you use to start the light build, and all machines that you want to participate in the distributed computation, must be running a version of Windows that is supported by Unreal Engine.
If you’d like to set up a render farm for computationally expensive tasks, please make sure to coordinate with your IT department to set up the appropriate permissions on machine(s) that will need to host Swarm Coordinator(s) and Agent(s).
Setting up Swarm Coordinator
If you’ve identified the machines that you’d like to use, and if you’ve installed UE4; you’re ready to set up Swarm Coordinator by following these steps:
After installing UE4, navigate to [UE4ROOT]\Engine\Binaries\DotNET.
Make a new directory on the machine that will distribute tasks to other machines on the network. For illustrative purposes, we’re naming the new directory, Swarm Coordinator .
Now, move (or copy) the following files from the [UE4ROOT]\Engine\Binaries\DotNET folder into the newly created directory:
AgentInterface.dll
SwarmCommonUtils.dll
SwarmCoordinator.exe
SwarmCoordinator.exe.config
SwarmCoordinatorInterface.dll
SwarmInterface.dll
UnrealControls.dll
Finally, to verify that you can run the application on your machine, go ahead and double click on the Swarm Coordinator executable.

If you already have Swarm Agents deployed, Swarm Coordinator displays its Agent Dialog Window (1) and Restart Options Area (2).

Click for full image.
At this point, you don’t need to do anything with the application, so go ahead and move onto the next section, where you’ll set up Swarm Agent(s).
Deploying Swarm Agents
Now that you’ve set up Swarm Coordinator, you’re ready to deploy Swarm Agents. After identifying the machine(s) that you’d like to host your agents, go ahead and follow these steps:
On each of the machines that you’d like to host a Swarm Agent, make a new directory. For illustrative purposes, we’re naming our new directory, Swarm Agent .
Move (or copy) the following files from the [UE4ROOT]\Engine\Binaries\DotNET folder into the newly created directly: SwarmAgent.exe, AgentInterface.dll, SwarmCommonUtils.dll, SwarmCoordinatorInterface.dll, SwarmInterface.dll, and UnrealControls.dll.
To deploy an agent, double click on the Swarm Agent executable.
After launching Swarm Agent, the Swarm icon appears in the Windows Notification Area. Double click the Swarm icon to open the application’s main menu.

To configure Swarm Agent, click the Settings tab.

To enable Developer Settings, set the ShowDeveloperMenu flag (in Settings > Developer Settings) to True.

When you update an Agent’s settings, it’s worth noting that Swarm Agent writes settings out to SwarmAgent.Options.xml (or, if Developer Settings are enabled, to SwarmAgent.DeveloperOptions.xml ).
In the Distribution Settings drop down menu, locate the CoordinatorRemotingHost field, entering the host computer’s IPv4 Address.

If you don’t know your computer’s IPv4 Address, go ahead and run ipconfig from the Command Prompt.
If you don’t want to enter the system’s IPv4 Address into the CoordinatorRemotingHost field, you can enter the Coordinator’s DNS Name.
Finally, go ahead and open Swarm Coordinator, where you’ll find details about deployed Swarm Agent(s).

Click for full image.
Setting up Agent Groups
Setting up Agent Groups is useful for creating execution clusters. For example, one set of machines might belong to a group that isn’t part of a render farm, whereas another cluster might have machines belonging to the farm.
Getting started, go ahead and open the Settings > Distribution Settings menu.

To set up an Agent group, you’ll first want to specify which group jobs you want this Agent to be deployed to. For example, we’re specifying that this Agent will deploy to «FarmGroup» jobs in the AllowedRemoteAgentGroup setting.

If you want this Agent to be deployed to «FarmGroup» jobs, make sure that the AgentGroupName matches AllowedRemoteAgentGroup. In the following example, we’re precluding this Agent from being deployed to «FarmGroup» jobs.

If you’d like to learn more about an Agent’s Distribution Settings, the following table provides some useful notes, covering the remaining properties that can be specified for each Agent in your execution cluster(s).
Setting
Default Value
Description
AgentGroupName
This is the name of the agent group that this Swarm Agent belongs to.
AllowedRemoteAgentGroup
This is the name of the agent group jobs that this Swarm Agent can be deployed to.
AllowedRemoteAgentNames
The filter string (‘ ‘, ‘,’ or ‘;’ delimited) being used by the remote machine.
AvoidLocalExecution
Setting this flag to True means that you’d like to enable the distribution of jobs and tasks from this Swarm Agent (with no local execution).
Setting this flag is more of a suggestion (rather than a mandate) because it sets the thread priority to Idle , favoring other Agents connected on the Swarm over itself. This is due to the fact that if there aren’t any other Agents available (or if Swarm can’t find a Coordinator), you’ll still get a build running on that Agent rather than an infinite wait time (or failure).
CoordinatorRemotingHost
This is the name of the machine that’s hosting Swarm Coordinator. You can enter one of two strings into this field, either the Coordinator’s DNS Name or its IPv4 address.
EnableStandaloneMode
Setting this flag to True disables the distribution system for outgoing and incoming tasks.
Managing Swarm Cache
After you’ve deployed your Swarm Agent(s), you’ll want to manage the Agents’ Swarm Cache. Typically, managing an Agent’s Swarm Cache involves updating the Agent’s cache settings, clearing its cache, and validating its cache.
To update the Agent’s cache settings, navigate to the Settings > Cache settings menu.

From this menu, you’ll be able to update the Agent’s Cache Settings (as described below).
Setting
Default Value
Description
CacheFolder
[Folder on Disk]/SwarmCache
This is the location of the cache folder, being on a fast drive with lots of space.
MaximumCacheSize
In gigabytes, this is the approximate maximum size of the cache folder.
MaximumJobsToKeep
This is the number of previous jobs to record logs and output data.
Additionally, if you want to clear the host machine’s cache, which is used by Swarm Agent to complete its assigned tasks, invoke the Clean command in the Cache menu.

Finally, if you want to validate the machine’s cache, invoke the Validate command in the Cache menu.

It’s good practice to clean and validate your Swarm Cache on a regular basis, especially if Unreal Lightmass is crashing and causing builds to fail.
Reading Agent Logs
Clicking on the Log tab opens the Log window that Swarm Agent log messages are flushed to.

If you want to specify the amount of output being flushed to the Log window, update the MaximumJobApplicationLogLines variable (found in the Developer Settings > Log Settings menu) to change the number of output lines from a Job application before it truncates what goes to the Log window.

If you need to locate AgentLog text files for debug or maintenance purposes, it’s important to note that, at the beginning and end of every Job, Agent activity is logged to a file in [Folder on Disk]\SwarmCache\Logs .

Click for full image.
Typically, the default logging level to files on disk is set to ExtraVerbose, whereas the default logging level to a Swarm Agent’s Log window is set to Informative. If you want to change how detailed you’d like the Log output to be, update the Verbosity variable, which is found in the Settings > Log Settings menu.

Monitoring Progress
If you want to monitor an agent’s progress as it works on the jobs and tasks being assigned to it, open the Swarm Status window.

When an agent is running, you’ll see progress bars per machine, and for every progress bar, there are regions reflecting whether the application is initializing (1), preparing to do work (2) (both of which are not distributed work) or performing distributed work (3).

To get more details about a job’s progress, hover your mouse cursor over the progress bars.
Finally, the Distributed Progress bar located at the bottom tells you the percentage of a Job that has been completed (4) versus the percentage that is currently being worked on (5).

Stopping Swarm Agents
To stop a Swarm Agent, click File > Exit to close the application and kill its process.

Alternatively, right click the Swarm icon in the Windows Notification Area and select its Exit command.
At this point, Swarm Coordinator and Swarm Agent can run with minimal intervention. Given the number of lights, objects, and the quality of calculations that need processing, you’ll find that with enough agents, Unreal Lightmass builds should only take a few minutes rather than a few hours.
Depending on your development environment (including the size and complexity of the scene that you’re working on), you may want to update how many cores are reserved on your local machine to improve build performance. This can be done by tuning the LocalJobsDefaultProcessorCount variable, which is located in the Developer Settings > Local Performance Settings menu.

If you have some general questions about running Unreal Swarm, check out the following set of Frequently Asked Questions.
Frequently Asked Questions
What are some ways I can improve build times when using Swarm Agent(s) and Coordinator?
Adding Lightmass Importance Volume(s) in player-accessible areas:
This volume is used to focus where Lightmass spends its time on for accuracy and quality. The idea is that these should cover an area where the player can be. Areas outside of the volume will receive fewer photons and thus a lower quality result. Note that using single large volumes to encompass an area defeats their purpose of focusing photon calculations in key areas.
Individual Static Meshes that have high Lightmap resolutions and a lot of light contributions in a scene can increase build times, not only for the scene, but for a single Actor. Where possible, lower Lightmap resolutions for a quality result and use the Statistics window to get an idea of how long it took to build a single Actor for the Level. To get a good result for large (or complex) Static Meshes where you find you are setting higher Lightmap resolutions, you may want to consider breaking it into separate smaller meshes or rework the Lightmap UV (where possible) to get better coverage for the parts that matter.
Enabling Foliage Tool Lightmap Resolutions:
Instanced Static Meshes used when you paint Foliage into your level automatically use the Lightmap resolution of the Static Mesh that it’s referencing. When you have hundreds (or even thousands) of these painted into your level, that resolution can be too high for the system to handle. It will lead to exponentially longer build times, potential Lightmass crashes due to memory constraints, and higher texture memory consumption.
It is recommended to enable the Light Map Resolution and use the default value of 8 or possibly set it to a lower value of 4. This lowers the resolution of all instances, but the perceivable quality loss is minimal since static shadowing only needs to be displayed at a distance while dynamic shadowing is handled near the camera.

Click image for full size.
Reducing the number of scene Actors and (or) Lights:
The number of shadow casting Actors and (or) Lights in the levels means that all these interactions have to be considered when calculating lighting. Reducing light is a key way to limit the number of Actors that a single light interacts with. Reducing the influence radius for lights that don’t need to affect a large area can decrease the number of computations and thus increase the speed of the light build being processed.
Using higher than recommended system specifications:
Swarm Agent is a CPU intensive process that requires a lot of calculations. If you’re only using your local machine, a good CPU and lots of RAM can improve build process time. Keep in mind, that the other factors previously mentioned also play a role in build processing time.
Why am I not getting Agent distribution?
Remote Swarm Agents may decline to work on your job for a few different reasons, the most common among them is that they’re already busy doing someone else’s work. Another possibility is that they have determined that they are too busy to take on a job at that time, often caused by the machine doing something resource intensive, such as compiling or cooking content . In the Swarm Status tab of the Agent window, you should see a full list of all remote agents that could potentially help with your build. If one of them isn’t currently available, you’ll see a white bar ticking along with the rest of the build, and if you mouse over the bar, you will see «Waiting for remote to become available».
Also, a more advanced way to peek at the available remote agents (even when you’re not doing a build) is to click on the Log tab and select Ping Remote Agents from the Network menu. You’ll see a list of the remote machines and their current state.
How can I limit CPU usage when building lighting?
From the Swarm > DeveloperSettings tab, you can limit CPU cores used during a lighting build for your local machine and remote ones with LocalJobDefaultProcessCount and RemoteJobDefaultProcessorCount.
For your local machine, you may want to limit its contribution to only a few cores, leaving enough for it to comfortably work on other tasks. By default, a couple of cores will be left free for this, but you may find you need more cores available to work with locally leaving distributed tasks handling more of the work for light build computations.
When trying to launch Swarm Agent, I get a Windows application error for UnrealLightmass.exe, what does this mean?

This type of error means that something is preventing the application from opening in Windows that is not directly the cause of UE4. Below are some steps you can take to resolve the issue:
Make sure you have the appropriate and latest Visual Studio dependencies installed. For Unreal Engine version 4.9 and earlier, you’ll need VS2013 dependencies and for 4.10 and later, you’ll want to have VS2015 dependencies.
If that does not resolve your issue, try using a free application (for example, Dependency Walker ) to troubleshoot any DLL issues that may be preventing the UnrealLightmass.exe from loading.
Are Swarm Agent and Coordinator supported for Mac or Linux?
Currently, Swarm Agent and Coordinator are only supported for Windows. Light builds on Mac and Linux will only build locally.
Can my GPU be used to build lighting?
Swarm does not currently support GPU computations for lighting data.
What do the following errors mean?
Lightmass Crashed with «Ran out of memory allocating [some value]»

Click image for full size.
In this situation, Swarm Agent failed to process data for Lightmass because it ran out of memory. This most often happens when you’re not using Swarm Coordinator to distribute a build across multiple agents requiring a single machine to do all the work. Lightmass can run out of memory when computing a large Level with many Actors and Lights or if Lightmap resolutions are too high.
You can reduce the chances of getting this error by increasing the amount of RAM on your local machine, adding agents for distribution, lowering the Lightmap resolution of Actors where possible or even adding a Lightmass Importance Volume to focus computations for key areas that players can access.
Lightmass Crashed with «Assertion Failed: (Index >=0)&(Index<ArrayNum))»

Click image for full size.
When you receive this error, you should Clean and Validate your Swarm Cache.
Editor toast pop-up «Light Build Failed. Swarm failed to kick off.»

When you attempt to build lighting from the Unreal Editor, you may get this message. If so, the following are some common reasons:
Make sure you do not have multiple instances of Swarm Agent open and running. You can check this by looking at the task processing that is running or in Windows by looking in the Windows Notification Area.
Corrupt levels and/or Actors in the level.
Not having correct exceptions for SwarmAgent.exe for Firewall and Anti-Virus software.
Installation or corruption issue with the Engine. For users with the Launcher, select your engine version drop down and select Verify.

Source build issue with Unreal Lightmass. Rebuild the UnrealLightmass solution.
If Swarm is still failing to start, its ports could be in use by another system process.
Open your Swarm Log and check for the following error message:
Exception details: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 123.456.7.89:8009
You may need to involve your IT department to solve this issue with port assignments, especially since Swarm requires ports 8008 and 8009 to function properly. Without those ports, it will fail to initiate any agents or coordinator. It is not an issue specifically caused by UE4.