如何注册systemd服务的生命周期事件?

huangapple go评论72阅读模式
英文:

How do I register for systemd service lifecycle events?

问题

我想了解有关服务单元状态更改的所有信息。我知道有一个 DBUS API 可以为 UnitNew 和 UnitRemoved 提供信号,但是语义对我来说仍然不清楚。而且这些信号并没有提供我所需要的信息。

我正在使用 go 语言,并尝试使用来自 coreos 的 go-systemd 库。他们提供了一种“订阅”的方式,但实际上是轮询系统中所有可用的单元信息。我不想每隔几毫秒就这样做一次,只是为了得到状态更改的通知。

我还尝试了默认的 org.freedesktop.DBus.Properties,但无法使其工作。

如果可以的话,请帮帮我,我已经没有主意了。

英文:

I want to be informed about all state changes of service units. I know there is the DBUS API which gives me signals for UnitNew and UnitRemoved, but the semantic is still unclear to me. Also the signals doesn't provide the informations I need.

I'm using go and tried the go-systemd lib from coreos. They provide a way to "subscribe" but it's in fact polling all the unit information available in the system. I do not want to do so every few milliseconds, just to get informed about statechanges.

I also tried the default org.freedesktop.DBus.Properties but I can not get this working.

Please help If you can, I'm out of ideas.

答案1

得分: 2

包含有关服务单元启动或停止信息的 systemd API 如下:

  • systemd日志。您可以通过执行 journalctl 来监听它,或者通过网络将其转发到您的程序,或者监视磁盘上文件的更改。例如:执行 journalctl --follow -o json-pretty _PID=1(您可以添加各种过滤器,如 UNIT=gdm.service,以仅获取一个服务的日志),然后根据 systemd日志的JSON输出格式 解析 stdout,以获取systemd的日志消息。使用 MESSAGE_ID 来匹配事件的含义,并观察未知消息,以了解何时将现有消息替换为新消息。虽然这可能足够稳健地工作,但日志消息并不主要用作API。因此,我建议使用以下选项。

  • Linux cgroup通知,因为当 systemd使用cgroups 启动服务时会生成这些通知。

  • 通过它们的依赖关系(如 Wants=)来使用 systemd单元

英文:

The systemd APIs that contain information about the start or stop of service units are:

  • The systemd journal. You can listen to it by executing journalctl or forwarding it via network to your program or watching for changes to the files on disk. E.g.: execute journalctl --follow -o json-pretty _PID=1 (you can add various filters like UNIT=gdm.service to only get those for one service) and then parse stdout according to the systemd journal json output format to get the journal messages of systemd. Use the MESSAGE_ID to match what the event means and watch for unknown messages to know when an existing message got replaced with a new one. While this might work robustly enough, log messages are not primarily intended as an API. As such I would recommend to use the below options.

  • Linux cgroup notifications as they get generated when systemd uses cgroups to start a service.

  • systemd units via their dependencies (like Wants=)

huangapple
  • 本文由 发表于 2017年7月6日 18:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/44946465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定