systemd – How to Synchronize Stop Order from One Service

systemd

Suppose I have a.service which I cannot modify, and b.service which I can modify, I want to see this stop order:

Stopping b.service ...
Stopped b.service
Stopping a.service ...
Stopped a.service

instead of this:

Stopping b.service ...
Stopping a.service ...
Stopped b.service
Stopped a.service

Assume that b.service may take at least 20 seconds to finish.

Best Answer

In order to stop b.service before a.service, you need to actually order b.service after a.service, since the ordering at service stop time is the inverse of the order at start time.

So this should be enough to accomplish what you described:

# b.service unit file
[Unit]
Description=...
After=a.service

[Service]
...

See the documentation for After= in man systemd.unit, which states:

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.

You also asked about what happens if b.service takes at least 20 seconds to terminate. That is fine. If b.service is properly configured so systemd is able to monitor it until unit stop is completed (in other words, if ExecStop= is not somehow misconfigured) and if it stops before the timeout is reached (see TimeoutStopSec=), then systemd will wait until b.service is fully stopped before initializing shutdown of a.service.

Related Question