В этой статье предполагается, что вы уже запустили apache-airflow на машине с Ubuntu и теперь хотите, чтобы он запускался как системная служба или так называемая служба демона.

В Ubuntu есть встроенный механизм для создания настраиваемых служб, позволяющий им запускаться во время загрузки системы и запускать / останавливать их как службу. В этом посте я расскажу о простом и элегантном способе создания служебной оболочки для вашего веб-сервера apache-airflow, чтобы вы могли запускать ее как службу.

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



Давайте начнем!

В документации Apache Airflow приведены начальные шаги для настройки воздушного потока как службы systemd, но в документации представлены сценарии только для RedHat Linux и четко указано, что необходимо внести изменения, чтобы можно было запускать сценарии на любой другой платформе Linux. .

Вы можете найти ссылку на документацию по apache-airflow ниже



Теперь давайте опишем шаги по созданию службы демона Apache Airflow в Ubuntu 18.04.

Чтобы запустить apache-airflow как службу, нам нужно создать две служебные записи: одну для airflow-webserver, а другую - для airflow-scheduler. Давайте обсудим один из них, вы можете создать другой самостоятельно, просто изменив первый.

Шаг I. Создание службы

Сначала создайте файл с именем airflow-webserver.service, используя следующую команду

sudo touch /etc/systemd/system/airflow-webserver.service

Шаг II: запись конфигурации службы

Теперь откройте файл airflow-webserver.service с помощью редактора nano и вставьте в него следующие строки.

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# “License”); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
[Unit]
Description=Airflow webserver daemon
After=network.target postgresql.service mysql.service
Wants=postgresql.service mysql.service
[Service]
EnvironmentFile=/etc/environment
User=airflow
Group=airflow
Type=simple
ExecStart= /usr/local/bin/airflow webserver
Restart=on-failure
RestartSec=5s
PrivateTmp=true
[Install]
WantedBy=multi-user.target

Вам может быть интересно, что делают все эти директивы, позвольте мне описать вам некоторые из них:

Description : As the name suggestes it is a small description about      the service
After :It simply means that your service must be started after the services that are required for your deamon to run, like for apache-airflow we need network, postgresql and mysql to be ready before it gets started. If your apache-airflow installation requires redis or rabbitmq services than you can specify the dependency here
EnvironmentFile : it specifies the file where service will find its environment variables in ubuntu its /etc/environment
User : set your actual username here, the specified userid will be used to invoke the service
ExecStart : here you can specify the command to be executed or set the proper path to your script that needs to be excuted. in our case we simple need to run the command airflow webserver
Restart : by default, systemd does not restart your service if the program exits for whatever reason. This is usually not what you want for a service that must be always available, so we’re instructing it to always restart on-failure
RestartSec : by default, systemd attempts a restart after 100ms. You can specify the number of seconds to wait before attempting a restart, using RestartSec.

Шаг III: загрузка, включение и запуск службы

Вот и все. Теперь мы можем запустить службу:

Давайте сначала загрузим службу, используя следующую команду:

sudo systemctl daemon-reload

Теперь включите службу airflow-webserver.service

sudo systemctl enable airflow-webserver.service

и вы можете просто запустить службу:

sudo systemctl start airflow-webserver.service

or

sudo service airflow-webserver start

Шаг IV: проверьте статус обслуживания

Вы можете проверить статус услуги:

sudo systemctl status airflow-webserver.service

or

sudo service airflow-webserver status

Шаг V: Остановите обслуживание

Чтобы остановить службу, используйте следующую команду

sudo systemctl stop airflow-webserver.service

or

sudo service airflow-webserver stop

Двигаясь дальше вперед

Создать службу для планировщика воздушного потока

Чтобы создать службу для планировщика, процесс такой же, вам просто нужно сделать другую запись службы, создав файл

sudo touch /etc/systemd/system/airflow-schedluer.service

Теперь вставьте в него приведенный ниже код конфигурации

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# “License”); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
[Unit]
Description=Airflow scheduler daemon
After=network.target postgresql.service mysql.service 
Wants=postgresql.service mysql.service
[Service]
EnvironmentFile=/etc/environment
User=airflow
Group=airflow
Type=simple
ExecStart=/usr/local/bin/airflow scheduler
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target

Вот и все,

ваше здоровье…