如何找到 systemd 服务无法启动(服务的单元文件设置不正确)的确切原因?

如何找到 systemd 服务无法启动(服务的单元文件设置不正确)的确切原因?

这真的很烦人,systemd只响应说我的某个服务文件的配置是错误的,但是却没有具体说明哪里错了:

/lib/systemd/system/auto_pgha.service

[Unit]
Description=PostgreSQL High Availability
After=network.service
After=firewalld.service


[Service]
Type=simple
WorkingDirectory=/etc/repmgr
ExecStartPre=/bin/bash -c 'echo -e "\n"  `date +"%Y/%m/%d %a, %X"`": STARTING \n"  >> pgha.log'
ExecStart=/bin/bash -c "python3 pg_high_availability.py  &>> pgha.log"
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

在目录中,/etc/repmgr这两个命令运行正常。但 systemd 服务仅响应错误:

# systemctl start auto_pgha
Failed to start auto_pgha.service: Unit auto_pgha.service has a bad unit file setting.
See system logs and 'systemctl status auto_pgha.service' for details.

# systemctl status -l auto_pgha
○ auto_pgha.service - PostgreSQL High Availability
     Loaded: bad-setting (Reason: Unit auto_pgha.service has a bad unit file setting.)
......
auto_pgha.service: Unit configuration has fatal error, unit will not be be started. 

答案1

您可以使用systemd-analyze verify命令。如果我们将问题中的内容放入pgha.service,我们会看到:

$ systemd-analyze verify pgha.service
.../pgha.service:10: Failed to resolve unit specifiers in echo -e "
"  `date +"%Y/%m/%d %a, %X"`": STARTING
"  >> pgha.log: Invalid slot
pgha.service: Unit configuration has fatal error, unit will not be started.
Unit pgha.service has a bad unit file setting.

你收到此错误是因为 systemd 本身使用了%<something>令牌(请参阅systemd.unit(5)手册页的“说明符”部分

你需要写:

ExecStartPre=/bin/bash -c 'echo -e "\n"  `date +"%%Y/%%m/%%d %%a, %%X"`": STARTING \n"  >> pgha.log'

相关内容