systemd服务在其他服务启动之前和之后运行

问题描述 投票:0回答:1

我想在autofs启动之前和之后运行脚本。我有两个系统服务:

backup1.service在autofs之前运行

[Unit]
Description=Backup mount

[Service]
ExecStart=/backup/sw/bmount before


[Install]
WantedBy=autofs.service

backup2.service在autofs之后运行

[Unit]
Description=Backup mount
PartOf=autofs.service
After=autofs.service

[Service]
ExecStart=/backup/sw/bmount after

[Install]
WantedBy=autofs.service

我可以确定bmount脚本中的after / before状态,因此我可以不带参数调用它,而我只能使用一项服务,但不知道如何。

有可能吗?

linux service systemd
1个回答
0
投票

有几种方法可以做到这一点:

编辑autofs.service

根据设计,服务文件应可在网站上维护。在基于Debian的平台上,供应商提供的服务文件位于/lib/systemd/system/中,我认为redhat在/usr/lib/systemd/system/中具有它们,但是您可以在/etc/systemd/system/中使用站点管理的服务文件来覆盖它们。

在那种情况下,我想

cp /lib/systemd/system/autofs.service /etc/systemd/system/autofs.service

然后在[Service]部分中,添加:

ExecStartPre=/backup/sw/bmount before
ExecStartPost=/backup/sw/bmount after

systemd.service联机帮助说:

[ExecStart =命令仅在所有ExecStartPre =命令成功退出后才运行。

ExecStartPost =命令仅在成功调用ExecStart =中指定的命令之后运行,如Type =所确定(即,对于Type = simple或Type = idle已启动该进程,对于该Type,最后一个ExecStart =进程已成功退出= oneshot,...)。

引入服务参数

一种与上述操作相同的更优雅的方法是使用插件。只需使用以下内容创建/etc/systemd/system/autofs.service.d/backup.conf

[Service]
ExecStartPre=/backup/sw/bmount before
ExecStartPost=/backup/sw/bmount after

关系

也许autofs.service已经有ExecStartPreExecStartPost命令,您担心会干扰该服务。在这种情况下,您可以使用关系来启动/停止服务。

[Unit]
Description=Backup mount
PartOf=autofs.service
Before=autofs.service

[Service]
Type=oneshot
ExecStart=/backup/sw/bmount before

[Install]
WantedBy=autofs.service


[Unit]
Description=Backup mount
PartOf=autofs.service
After=autofs.service

[Service]
Type=oneshot
ExecStart=/backup/sw/bmount after

[Install]
WantedBy=autofs.service

在这种情况下:

  • [PartOf=autofs.service的意思是“当systemd停止或重新启动autofs.service时,操作将传播到backup.service”]
  • [Before=autofs.service的意思是“如果两个单元都在启动,则autofs.service的启动将延迟到backup.service完成启动。”
  • [WantedBy=autofs.service表示“如果backup.service是,则将启动autofs.service
  • [Type=oneshot意味着即使ExecStart=进程完成,该服务仍将被视为正在运行。

请确保运行systemctl daemon-reload,以便systemd读取新服务。还要运行systemctl enable backup.service以确保WantedBy=成为Wants=autofs.service

我认为您的解决方案非常接近。

© www.soinside.com 2019 - 2024. All rights reserved.