systemd:服务依赖“如果 A 没有运行,B 不应该运行”?

Unc*_*ook 6 linux systemd

(systemd 版本 229,fwiw)

我有一个主要服务 A 和一个辅助服务 B。主要 A 可以自己运行。但是服务 B 本身无法正确运行:它需要 A 运行(技术上 B 可以运行,但这是我希望 systemd 阻止的)。我的目标:如果 A 没有运行,B 就不应该运行。鉴于 A 和 B 正在运行,当 A 停止或死亡/崩溃时,B 应该停止。

我如何实现这一目标?

我通过将 [Unit] 项目添加到 b.service 来接近,使用

Requisite=A.service
After=A.service
Run Code Online (Sandbox Code Playgroud)

上面的结果是

1) B won't start unless A is running (good).
2) B is stopped when A is stopped (good).
3) However, if I kill A, service B continues to run (bad).
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个最后的行为 #3?我尝试使用 BindsTo 而不是 Requisite,就像在 B 的服务文件中这样:

BindsTo=A.service
After=A.service
Run Code Online (Sandbox Code Playgroud)

我得到:

1) If A is not running and I start B, then A is also started
    (I want an error, I don't want A started)
2) B is stopped when A is stopped (good).
3) B is stopped when A is killed (good)
Run Code Online (Sandbox Code Playgroud)

所以现在#3 是好的,但#1 不是想要的行为。PartOf 和 BindsTo 似乎都不能解决问题,但也许我没有正确的选项组合咒语?从手册页我不清楚可以组合哪些选项。

使用 BindsTo,我还尝试使用 ExecStartPre 使 B 的启动失败,但这当然不起作用,因为 B 的启动已经确定它需要 A 运行(并启动它),然后才启动 B。

有没有办法在 Requisite 和 BindsTo 之间获得行为?我上面列出的 1-2-3?

提前谢谢!

小智 2

我也在寻找更优雅的解决方案。这里有一个开放的 systemd 请求增强请求:https://github.com/systemd/systemd/issues/5966

目前我的解决方法如下:B.service

Requisite=A.service
After=A.service
Run Code Online (Sandbox Code Playgroud)

A.服务

OnFailure=Stop-B.service
Run Code Online (Sandbox Code Playgroud)

停止B.服务

[Service]
Type=oneshot
TimeoutSec=0
ExecStart=/bin/systemctl stop B.service
Run Code Online (Sandbox Code Playgroud)