5

Система: ubuntu 16.04.1 (для запуска сервисов используется systemd).

Имеем: приложение-сервис, которое зависит от mongodb. Приложение и mongodb запускаются автоматически, на старте ubuntu. В .service файле приложения прописана зависимость:

After=network.target mongod.service

При этом, вероятно, из-за того, что mongodb сразу после старта ещё не готова принимать подключения, приложение падает с ошибкой "невозможно подключиться к бд".

Каким образом лучше выполнить задержку до полного старта mongodb, либо другим способом определить готовность mongodb используя возможности systemd?

2
  • Это не то, что Вы ищите: unix.stackexchange.com/questions/247755/… ?
    – nobody
    16 авг 2016 в 3:36
  • @nobody находил этот вопрос, спасибо. Но в доках монги про Type ничего не сказано, и в идеале конечно было бы использование Type=notify, когда сам сервис пошлет уведомление, что он готов. Но опять таки не нашел подтверждения, что монга посылает какие-то уведомления в systemd. 16 авг 2016 в 5:16

1 ответ 1

3
+200

В этом случае воспользуйтесь ExecStartPost и netcat:

ExecStart=
ExecStartPost=/bin/sleep 1s
ExecStartPost=/usr/bin/nc -z host port

Где host port - адрес и порт mongodb.

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

В случае если время старта может "плавать" поможет:

until [[ $(nc -z <host> <port>) -eq 1 ]]; do sleep 1s; done

until будет вызывать sleep до тех пор пока netcat возвращает -1.

ExecStartPre и ExecStartPost часть жизненного цикла запуска unita

ExecStartPre=, ExecStartPost=

Additional commands that are executed before or after the command in ExecStart=, respectively. Syntax is the same as for ExecStart=, except that multiple command lines are allowed and the commands are executed one after the other, serially.

If any of those commands (not prefixed with "-") fail, the rest are not executed and the unit is considered failed.

ExecStart= commands are only run after all ExecStartPre= commands that were not prefixed with a "-" exit successfully.

ExecStartPost= commands are only run after the service has started successfully, as determined by Type= (i.e. the process has been started for Type=simple or Type=idle, the process exits successfully for Type=oneshot, the initial process exits successfully for Type=forking, "READY=1" is sent for Type=notify, or the BusName= has been taken for Type=dbus).

Note that ExecStartPre= may not be used to start long-running processes. All processes forked off by processes invoked via ExecStartPre= will be killed before the next service process is run.

Note that if any of the commands specified in ExecStartPre=, ExecStart=, or ExecStartPost= fail (and are not prefixed with "-", see above) or time out before the service is fully up, execution continues with commands specified in ExecStopPost=, the commands in ExecStop= are skipped.

В случае если между unit'ами указана зависимость Before или After systemd откладывает старт зависящего сервиса до тех пор пока другой не запустится:

Before=, After=

A space-separated list of unit names. Configures ordering dependencies between units. If a unit foo.service contains a setting Before=bar.service and both units are being started, bar.service's start-up is delayed until foo.service is started up. Note that this setting is independent of and orthogonal to the requirement dependencies as configured by Requires=. It is a common pattern to include a unit name in both the After= and Requires= option, in which case the unit listed will be started before the unit that is configured with these options. This option may be specified more than once, in which case ordering dependencies for all listed names are created. After= is the inverse of Before=, i.e. while After= ensures that the configured unit is started after the listed unit finished starting up, Before= ensures the opposite, i.e. that the configured unit is fully started up before the listed unit is started. Note that when two units with an ordering dependency between them are shut down, the inverse of the start-up order is applied. i.e. if a unit is configured with After= on another unit, the former is stopped before the latter if both are shut down. Given two units with any ordering dependency between them, if one unit is shut down and the other is started up, the shutdown is ordered before the start-up. It doesn't matter if the ordering dependency is After= or Before=. It also doesn't matter which of the two is shut down, as long as one is shut down and the other is started up. The shutdown is ordered before the start-up in all cases. If two units have no ordering dependencies between them, they are shut down or started up simultaneously, and no ordering takes place.

9
  • Это к монговскому .service файлу надо добавить? 18 авг 2016 в 23:46
  • Да - в unit файле mongodb. Если этот unit находится в /usr то можно написать drop-in (Так при обновлении mongodb не потеряются изменения).
    – Alex
    19 авг 2016 в 5:45
  • В первом примере, строка ExecStartPost=/usr/bin/nc -z host port это для страховки? (насколько понял, смысл в паузе в 1сек.) 19 авг 2016 в 5:54
  • В первом примере ждем секунду для страховки. Если за это время mongodb не начнет слушать на порту netcat вернет -1 и unit перейдет в состояние error. В случае если время старта всегда разное, лучше использовать команду until. С помощью неё unit будет в состоянии запуска до тех пор пока: mongodb не начнет слушать на порту, не истечет время на страрт unit'а;
    – Alex
    19 авг 2016 в 6:16
  • Понял, спасибо. Можете ещё ткнуть в документацию, не могу найти подтверждения, что последующие зависимые сервисы стартуют после успешного ExecStartPost (а не сразу после ExecStart). 19 авг 2016 в 6:18

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.