如何在升级依赖项时重新启动我的 systemd 服务

Ren*_*nex 16 dependencies systemd services

我编写了一个使用 Postgres 数据库的程序,并为它编写了一个 systemd 服务文件。目前我的服务在启动时启动得很好,当 Postgres 停止升级时它会停止(通过apt upgrade)。但是,当升级完成并再次启动Postgres 时,我的服务并没有自动启动。

我可以定义一些依赖项来让我的服务再次自动启动吗?

这是我的服务在 Postgres 升级期间自动停止后的状态:

? tabill.service - My service
   Loaded: loaded (/srv/tabill/tabill.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Tue 2017-07-04 00:29:24 EEST; 44min ago
 Main PID: 1048 (code=killed, signal=TERM)
Run Code Online (Sandbox Code Playgroud)

请注意,我可以再次手动启动该服务就好了。

这是我的服务文件:

[Unit]
Description=My service
Wants=nginx.service
Requires=postgresql.service
After=postgresql.service

[Service]
Type=simple
ExecStart=/srv/tabill/app/serve
Restart=always
TimeoutSec=60

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

我试过添加PartOf=postgresql.serviceand BindsTo=postgresql.service,然后手动停止和启动 Postgres,但都没有帮助。

当然,我可以删除Requires,但最好同时停止这两个服务,前提是它们都可以重新启动。

Ren*_*nex 17

我找到了答案:我需要将服务文件的最后一行更改为:

WantedBy=postgresql.service
Run Code Online (Sandbox Code Playgroud)

这样,每当 Postgres 启动时,我的服务也会启动 - 但如果我的服务失败,则不会停止 Postgres。

[Install]节中的指令仅影响单元的启用和禁用。但是当我的服务已经启用时,事情就没有这么简单了:

# systemctl enable tabill.service
Failed to execute operation: Too many levels of symbolic links
Run Code Online (Sandbox Code Playgroud)

错误消息具有误导性。修复它很简单:

# systemctl disable tabill.service
Removed symlink /etc/systemd/system/tabill.service.
Removed symlink /etc/systemd/system/multi-user.target.wants/tabill.service.

# systemctl enable tabill.service
Failed to execute operation: No such file or directory

# systemctl enable /srv/tabill/tabill.service
Created symlink from /etc/systemd/system/postgresql.service.wants/tabill.service to /srv/tabill/tabill.service.
Created symlink from /etc/systemd/system/tabill.service to /srv/tabill/tabill.service.
Run Code Online (Sandbox Code Playgroud)

现在,只要 Postgres 执行,我的服务就会停止和启动。系统启动时自然会启动 Postgres。