How to synchronize systemd stop order from one service?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

If you merely want to stop these in a given order you can invoke the call to systemctl like this:

 $ systemctl stop a.service && systemctl stop b.service

or

 $ systemctl stop a.service; systemctl stop b.service


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x