如果文件存在,则延迟 systemd 服务

Zul*_*rib 3 systemd services

如果文件存在,我想延迟服务的启动(而不是在文件存在时使服务失败,如ConditionPathExists=),但在单元文档中没有找到任何内容

systemd 在技术上可行吗?如何 ?

Dav*_*ish 9

据我所知,ConditionPathExists=不会使设备进入“失败”状态。ConditionPathExists=仅跳过该单元。

\n\n
\n

单元文件还可能包含许多 Condition\xe2\x80\xa6= 和 Assert\xe2\x80\xa6=\n 设置。在设备启动之前,systemd 将验证指定的条件是否成立。如果没有,该单元的启动将被(大部分是静默地)跳过。失败条件不会导致单元进入“失败”状态。

\n
\n\n

ExecStartPre=我发现根据文件的存在来延迟单元启动的一种方法是使用、thenRestart=on-failure和测试文件RestartSec=。这确实会使设备进入失败状态,但它会不断重试直到成功。例如:

\n\n
[Service]\n# Should cause failure if file exists\nExecStartPre=/usr/bin/test ! -f afile\nExecStart=mycommand\n\n# Restart on failure. Keep trying to create backup.\nRestartSec=10m\nRestart=on-failure\n
Run Code Online (Sandbox Code Playgroud)\n


Hau*_*ing 6

只使用一台

放入TimeoutStartSec=infinity单元文件并ExecStart=使用类似的脚本进行配置

#! /bin/bash

TIMEOUT=1000

test -f /path/to/testfile && sleep "$TIMEOUT"

exec /path/to/service/binary plus arguments
Run Code Online (Sandbox Code Playgroud)

这不能(以有用的方式)使用 完成ExecStartPre=,请参阅man systemd.service

请注意,ExecStartPre= 不能用于启动长时间运行的进程。由通过 ExecStartPre= 调用的进程分叉的所有进程将在下一个服务进程运行之前被终止。

使用辅助单元

如果您想“单独”使用 systemd 执行此操作,那么您可以创建一个辅助单元check_and_wait.target。这个得到条目

# check_and_wait.target
[Unit]
TimeoutStartSec=infinity
ConditionPathExists=/path/to/testfile
ExecStart=/usr/bin/sleep 1000
RemainAfterExit=yes
Run Code Online (Sandbox Code Playgroud)

主单元获取这些条目:

Wants=check_and_wait.target
After=check_and_wait.target
Run Code Online (Sandbox Code Playgroud)