Выполните произвольную команду, когда сервис перестанет работать

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

Например, если у Вас есть неудача, чтобы назвать файл -f, как Вы удалили бы его? rm -f не работал бы, потому что -f интерпретируется как опция к rm команда. Но к счастью, rm управляйте соблюдает -- конвенция, таким образом, можно удалить то использование файла:

rm -- -f
11
21.04.2015, 18:10
2 ответа

Существует Директива в разделе [Блок] , Документированный в Systemd .unit (5) . Он определяется следующим образом:

Разделенный пробел список одного или нескольких единиц, которые активируются при этом устройстве, вводят в состояние «Неудачное» состояние.

(также есть директива onfailurejobmode = в том же разделе, что позволяет устанавливать режим работы для активации onfailue = единиц.)

11
27.01.2020, 19:58

Вы также можете использовать ExecStopPostдля прямого запуска команды вместо запуска блока.

Меня не устраивала настройка OnFailure, поэтому я продолжил искать и нашел ExecStopPost.

В следующем реальном примере в случае сбоя основной задачи systemd выполнит команду git.

[Unit]
Description=SRI Dispenser Server
ConditionPathExists=|/usr/bin/
After=sri-boot-dsp.service

[Service]
WorkingDirectory=/usr/share/sri/configurations/transmitter

User=root

# This is task to run when this service starts
ExecStart=/usr/bin/python -m sri.DispenserServer

# If any of the ExecStart tasks fail, then ExecStopPost will run
ExecStopPost=/bin/git checkout --.

Restart=always
RestartSec=10
KillSignal=SIGKILL


[Install]
WantedBy=multi-user.target

https://www.freedesktop.org/software/systemd/man/systemd.service.html

ExecStopPost= Additional commands that are executed after the service is stopped. This includes cases where the commands configured in ExecStop= were used, where the service does not have any ExecStop= defined, or where the service exited unexpectedly. This argument takes multiple command lines, following the same scheme as described for ExecStart=. Use of these settings is optional. Specifier and environment variable substitution is supported. Note that – unlike ExecStop= – commands specified with this setting are invoked when a service failed to start up correctly and is shut down again.

It is recommended to use this setting for clean-up operations that shall be executed even when the service failed to start up correctly. Commands configured with this setting need to be able to operate even if the service failed starting up half-way and left incompletely initialized data around. As the service's processes have been terminated already when the commands specified with this setting are executed they should not attempt to communicate with them.

Note that all commands that are configured with this setting are invoked with the result code of the service, as well as the main process' exit code and status, set in the $SERVICE_RESULT, $EXIT_CODE and $EXIT_STATUS environment variables, see systemd.exec(5) for details.

6
27.01.2020, 19:58

Теги

Похожие вопросы