如何启动和停止一个 systemd 单元与另一个 systemd 单元?

如何启动和停止一个 systemd 单元与另一个 systemd 单元?

我正在使用 CoreOS 和 fleet 调度 systemd 单元。我有两个单元(firehose.servicefirehose-announce.service。我试图让firehose-announce.service和 一起启动和停止firehose.service。以下是 的单元文件firehose-announce.service

[Unit]
Description=Firehose etcd announcer
BindsTo=firehose@%i.service
After=firehose@%i.service
Requires=firehose@%i.service

[Service]
EnvironmentFile=/etc/environment
TimeoutStartSec=30s
ExecStartPre=/bin/sh -c 'sleep 1'
ExecStart=/bin/sh -c "port=$(docker inspect -f '{{range $i, $e := .NetworkSettings.Ports }}{{$p := index $e 0}}{{$p.HostPort}}{{end}}' firehose-%i); echo -n \"Adding socket $COREOS_PRIVATE_IPV4:$port/tcp to /firehose/upstream/firehose-%i\"; while netstat -lnt | grep :$port >/dev/null; do etcdctl set /firehose/upstream/firehose-%i $COREOS_PRIVATE_IPV4:$port --ttl 300 >/dev/null; sleep 200; done"
RestartSec=30s
Restart=on-failure

[X-Fleet]
X-ConditionMachineOf=firehose@%i.service

我试图使用的启动和停止也会启动或停止BindsTo的概念。但这永远不会正确发生。如果停止,则进入失败状态。但是当我启动 时, 却没有启动。firehose.servicefirehose-announce.servicefirehose.servicefirehose-announce.servicefirehose.servicefirehose-announce.service

我在这里做错了什么?

答案1

我似乎终于找到了正确的组合,可以让它按预期工作。

在我的firehose-announce.service单位中,我只设置了BindsTo。整个单位是:

[Unit]
Description=Firehose etcd announcer
BindsTo=firehose@%i.service

[Service]
EnvironmentFile=/etc/environment
TimeoutStartSec=30s
ExecStartPre=/bin/sh -c 'sleep 1'
ExecStart=/bin/sh -c "port=$(docker inspect -f '{{range $i, $e := .NetworkSettings.Ports }}{{$p := index $e 0}}{{$p.HostPort}}{{end}}' firehose-%i); echo -n \"Adding socket $COREOS_PRIVATE_IPV4:$port/tcp to /firehose/upstream/firehose-%i\"; while netstat -lnt | grep :$port >/dev/null; do etcdctl set /firehose/upstream/firehose-%i $COREOS_PRIVATE_IPV4:$port --ttl 300 >/dev/null; sleep 200; done"
RestartSec=30s
Restart=on-failure

[X-Fleet]
X-ConditionMachineOf=firehose@%i.service

这将导致firehose-announce.service设备在需要时停止firehose.service。很好。但是我们如何重新启动它呢?

我将依赖关系反转到我的firehose.service单位,如下所示:

[Unit]
Description=Firehose server
Wants=firehose-announce@%i.service
Before=firehose-announce@%i.service

[Service]
ExecStartPre=/usr/bin/docker pull firehose/server
ExecStartPre=-/usr/bin/docker rm -f firehose-%i
ExecStart=/usr/bin/docker run --name firehose-%i -p 7474 --env-file /home/core/firehose.env firehose/server
ExecStop=/usr/bin/docker rm -f firehose-%i
User=core
TimeoutStartSec=5m
TimeoutStopSec=20s
RestartSec=30s
Restart=on-failure

[Install]
WantedBy=multi-user.target

[X-Fleet]
X-Conflicts=firehose@*.service

这表示firehose.service想要在 启动时启动(但如果无法启动firehose-announce.service则不会失败)。它还确保在 之前启动。firehose-announce.servicefirehose.servicefirehose-announce.service

我对此进行了测试,现在各个单元似乎可以按照需要一起停止和启动。

相关内容