- Как создать свою службу в Linux
- Шаг 1. Создание скрипта
- Список инструкций Данный список взят по одной из ссылок в конце записи, описания нуждаются в доработке
- Список виртуальных объектов Та же хрень, что и с предыдущим списком
- Шаг 2+3. Оформление скрипта в качестве службы
- Creating a Linux service with systemd
- The program
- Turning it into a service
- Going further
- Starting in the right order
- Restarting on exit
- Avoiding the trap: the start limit
- Is that really it?
- Systemd: Service File Examples
- Create Systemd Service File
- Systemd Service File Options
- Important [Unit] Section Options
- Important [Install] Section Options
- Important [Service] Section Options
А файл с заявлением на увольнение назывался ПНХ.doc
Как создать свою службу в Linux
23.08.11 03:12 / Обновлено 25.08.11 20:59 | Версия для печати | Ubuntu | Debian |
- Создаём скрипт для управления сервисом, в специальном формате.
- Помещаем его в хранилище сервисных скриптов. Это каталог /etc/init.d
- Обрабатываем скрипт специальной утилитой update-rc.d (или insserv)
Шаг 1. Создание скрипта
Вот шаблон, чтобы не запутаться:
Шаблон от разработчиков находится по адресу /etc/init.d/skeleton
Обратите внимание на блок, ограниченный метками [ ### BEGIN INIT INFO ] и [ ### END INIT INFO ]. Он выделен жирным.
Этот блок полностью закомментирован, то есть при выполнении скрипта его содержимое игнорируется. Однако, он содержит инструкции для утилиты update-rc.d, которая прочитает их, поймёт и раскидает ссылки на этот скрипт по уровням запуска системы.
Подробнее про процессы, службы, уровни запуска и устройство каталогов запуска можно прочитать здесь.
Этот блок обязателен для скрипта, управляющего сервисом. Остановимся на нём подробнее.
### BEGIN INIT INFO — метка начала списка инструкций
### END INIT INFO — метка конца списка инструкций
Все строки между ними должны быть в формате:
# Инструкция: арг1 [арг2. ]
Строка начинается со знака # и последующего одного пробела. После инструкции должно стоять двоеточие, агрументы разделяются пробелами.
Список инструкций
Данный список взят по одной из ссылок в конце записи, описания нуждаются в доработке
Provides | Описывает предоставляемые этим скриптом объекты (арг1, агр2, . ) таким способом, что, когда скрипт запускается с аругментом start, данные объекты считаются существующими, и, следовательно, другие скрипты в init, которые требуют существование этих объектов, смогут запуститься на более поздней стадии. Обычно, можно использовать имя скрипта в качестве объекта, но так же можно использовать имя сервиса, которую он заменяет. Виртуальные объекты тут не указываются. Они определены вне скриптов init.d |
Required-Start | Задаёт объекты, которые должны существовать, чтобы запустить скрипт. Можно использовать при необходимости виртуальные объекты, как описано ниже. Если объекты не указаны, то этот скрипт может быть запущен сразу после старта, не требуя подключенных локальных файловых систем, запущенного системного журнала и т.д. |
Required-Stop | Задаёт объекты, используемые сервисом, предоставляемой скриптом. Объект, предоставляемый этим скриптом должен завершиться до завершения перечисленных здесь объектов, чтобы избежать конфликтов. Обычно, здесь указывают те же объекты, что и в Required-Start |
Should-Start | Задаёт объекты, которые, если существуют, должны должны быть запущены перед сервисом, предоставляемым данным скриптом. Это допускает слабые зависимости, которые не приводят сервис к ошибке, если объекты не доступны. Можно использовать при необходимости виртуальные объекты, как описано ниже. |
Should-Stop | Задаёт объекты, если существуют должны быть остановлены уже после данного сервиса. Обычно, здесь указывают те же объекты, что и в Should-Start |
Default-Start Default-Stop | Задаёт уровни запуска, на которых скрипт должен быть запущен (остановлен) по умолчанию. Например, если сервис должен быть запущен на только уровнях 3, 4 и 5, укажите «Default-Start: 3 4 5» и «Default-Stop: 0 1 2 6». |
Short-Description | Задаёт короткое описание действия скрипта. Ограничено одной строкой. |
Description | Задаёт более подробное описание действия скрипта. Может быть в несколько строк, в этом случае, каждая строка описания должна начинаться с символа # с последующим знаком табуляции или как минимум 2-мя символами пробела. Описание заканчивается перед линией, не совпадающим с этим условием. |
X-Start-Before X-Stop-After | Задаёт обратные зависимости, которые значат то же, как если бы они были указаны в should-start и should-stop в пакетах, указанных тут. |
Уровни запуска определяют, в какие из каталогов /etc/rcX.d будут помещены ссылки на текущий скрипт.
Для отслеживания зависимостей важны инструкции Provides, Required- и Should-. Остальные не используются. На основе зависимостей утилита update-rc.d (или insserv) упорядочивает скрипты в каталоге определённого уровня запуска ( /etc/rcX.d ).
Список виртуальных объектов
Та же хрень, что и с предыдущим списком
$local_fs | Все локальные фаловые системы подключены. Все скрипты, которые производят запись в /var/ должны зависеть от этого, если они уже не зависят от $remote_fs |
$network | низкоуровневая сеть, т.е. сетевые карты, может подразумеваться PCMCIA запущеной |
$named | Демоны, которые могут предоставлять разрешение доменных имён предполагаются запущенными. Например, DNS, NIS+ или LDAP |
$portmap | Демоны, предоставляющие сервис SunRPC/ONCRPC portmapping как указано в 1833 (если они есть) |
$remote_fs | Все файловые системы подключены. Скрипты, которые должны быть запущены во время остановки системы до того, как всем процессам будет отправлен сигнал уничтожения, должны зависеть от $remote_fs. |
$syslog | системный журнал функционирует |
$time | установленно корректное системное время, например, ntp или rdate, или RTC |
$all | Запускает скрипт как можно последним |
Шаг 2+3. Оформление скрипта в качестве службы
Допустим, имя нашего самописного скрипта somestuff. Именно так, somestuff, без всяких расширений.
Делаем его исполняемым:
chmod +x ./somestuff
Копируем в хранилище сервисных скриптов:
cp ./somestuff /etc/init.d
И делаем прописку в каталогах уровней запуска:
update-rc.d somestuff defaults
Полный путь давать не надо, только имя в /etc/init.d/
Для выписки (удаления всех симлинков на этот скрипт из всех каталогов уровней запуска) делаем:
Источник
Creating a Linux service with systemd
Sep 5, 2017 · 3 min read
While writing web applications, I often need to offload compute-heavy tasks to an asynchronous worker script, schedule tasks for later, or even write a daemon that listens to a socket to communicate with clients directly.
While there might sometimes be better tools for the job — always consider using existing software first, such as a task queue server —writing your own service can give you a level of flexibility you’ll never get when bound by the constraints of third-party software.
The cool thing is th a t it’s fairly easy to create a Linux service: use your favourite programming language to write a long-running program, and turn it into a service using systemd.
The program
Let’s create a small server using PHP. I can see your eyebrows rising, but it works surprisingly well. We’ll listen to UDP port 10000, and return any message received with a ROT13 transformation:
And test it in another terminal:
Cool, it works. Now we want this script to run at all times, be restarted in case of a failure (unexpected exit), and even survive server restarts. That’s where systemd comes into play.
Turning it into a service
Let’s create a file called /etc/systemd/system/rot13.service :
- set your actual username after User=
- set the proper path to your script in ExecStart=
That’s it. We can now start the service:
And automatically get it to start on boot:
Going further
Now that your service (hopefully) works, it may be important to dive a bit deeper into the configuration options, and ensure that it will always work as you expect it to.
Starting in the right order
You may have wondered what the After= directive did. It simply means that your service must be started after the network is ready. If your program expects the MySQL server to be up and running, you should add:
Restarting on exit
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 exit:
You could also use on-failure to only restart if the exit status is not 0 .
By default, systemd attempts a restart after 100ms. You can specify the number of seconds to wait before attempting a restart, using:
Avoiding the trap: the start limit
I personally fell into this one more than once. By default, when you configure Restart=always as we did, systemd gives up restarting your service if it fails to start more than 5 times within a 10 seconds interval. Forever.
There are two [Unit] configuration options responsible for this:
The RestartSec directive also has an impact on the outcome: if you set it to restart after 3 seconds, then you can never reach 5 failed retries within 10 seconds.
The simple fix that always works is to set StartLimitIntervalSec=0 . This way, systemd will attempt to restart your service forever.
It’s a good idea to set RestartSec to at least 1 second though, to avoid putting too much stress on your server when things start going wrong.
As an alternative, you can leave the default settings, and ask systemd to restart your server if the start limit is reached, using StartLimitAction=reboot .
Is that really it?
That’s all it takes to create a Linux service with systemd: writing a small configuration file that references your long-running program.
Systemd has been the default init system in RHEL/CentOS, Fedora, Ubuntu, Debian and others for several years now, so chances are that your server is ready to host your homebrew services!
Источник
Systemd: Service File Examples
Most Linux distributions use systemd as a system and service manager.
The systemctl is the main command in systemd, used to control services.
In this tutorial i will show how to create a systemd service file that will allow you to control your service using the systemctl command, how to restart systemd without reboot to reload unit files and how to enable your new service.
I will also show and describe the most important systemd service file options with the live examples of the systemd service files.
Create Systemd Service File
Create a systemd service file /etc/systemd/system/foo-daemon.service (replace the foo-daemon with your service name):
Open the foo-daemon.service file and add the minimal service configuration options that allow this service to be controlled via systemctl :
Path To Daemon : If you don’t know the full path to a daemon, try which foo-daemon .
Once the service file is changed, it needs to reload systemd configuration:
Now you should be able to start , stop , restart and check the service status
To configure a service to start automatically on boot, you need to enable it:
To check the service logs, run:
Systemd Service File Options
The common configuration items are configured in the generic [Unit] and [Install] sections.
The service specific configuration options are configured in the [Service] section.
Important [Unit] Section Options
Option | Description |
---|---|
Description | A short description of the unit. |
Documentation | A list of URIs referencing documentation. |
Before , After | The order in which units are started. |
Requires | If this unit gets activated, the units listed here will be activated as well. If one of the other units gets deactivated or fails, this unit will be deactivated. |
Wants | Configures weaker dependencies than Requires . If any of the listed units does not start successfully, it has no impact on the unit activation. This is the recommended way to establish custom unit dependencies. |
Conflicts | If a unit has a Conflicts setting on another unit, starting the former will stop the latter and vice versa. |
A complete list of [Unit] section options:
Important [Install] Section Options
Option | Description |
---|---|
Alias | A space-separated list of additional names for the unit. Most systemctl commands, excluding systemctl enable , can use aliases instead of the actual unit name. |
RequiredBy , WantedBy | The current service will be started when the listed services are started. See the description of Wants and Requires in the [Unit] section for details. |
Also | Specifies a list of units to be enabled or disabled along with this unit when a user runs systemctl enable or systemctl disable . |
A complete list of [Install] section options:
Important [Service] Section Options
Option | Description |
---|---|
Type | Configures the process start-up type. One of: simple (default) – starts the service immediately. It is expected that the main process of the service is defined in ExecStart . forking – considers the service started up once the process forks and the parent has exited. oneshot – similar to simple , but it is expected that the process has to exit before systemd starts follow-up units (useful for scripts that do a single job and then exit). You may want to set RemainAfterExit=yes as well so that systemd still considers the service as active after the process has exited. dbus – similar to simple , but considers the service started up when the main process gains a D-Bus name. notify – similar to simple , but considers the service started up only after it sends a special signal to systemd. idle – similar to simple , but the actual execution of the service binary is delayed until all jobs are finished. |
ExecStart | Commands with arguments to execute when the service is started. Type=oneshot enables specifying multiple custom commands that are then executed sequentially. ExecStartPre and ExecStartPost specify custom commands to be executed before and after ExecStart . |
ExecStop | Commands to execute to stop the service started via ExecStart . |
ExecReload | Commands to execute to trigger a configuration reload in the service. |
Restart | With this option enabled, the service shall be restarted when the service process exits, is killed, or a timeout is reached with the exception of a normal stop by the systemctl stop command. |
RemainAfterExit | If set to True , the service is considered active even when all its processes exited. Useful with Type=oneshot . Default value is False . |
A complete list of [Service] section options:
Источник