Systemd – Custom Status Message Configuration

systemd

I'm trying to write a systemd service which should expose the options start|stop|status|restart.

This is the current script:

[Unit]
Description=Daemon to start ark server
After=network.target

[Service]
ExecStart=/etc/init.d/arkdaemon start
ExecStop=/etc/init.d/arkdaemon stop
Type=forking

[Install]
WantedBy=multi-user.target

I can't find any way to specify a custom status command.
Is there a way I think, but how?

Best Answer

Systemd support custom status message, but here are some prerequsites that must be met:

  • type of service should be notify
  • your service must update systemd with your current service status either via /run/systemd/notify socket or by calling systemd-notify

As a reference you can check Apache HTTPD on Fedora (maybe same in other distros, don't know):

systemctl status httpd.service


● httpd.service - The Apache HTTP Server    
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Active: active (running) since Fri 2017-10-06 15:21:07 CEST; 18h ago
  Docs: man:httpd.service(8)
  Process: 14424 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)  
  Main PID: 4105 (httpd)
  Status: "Total requests: 8; Idle/Busy workers 100/0;Requests/sec: 0.000118; Bytes served/sec:   0 B/sec"

You can see that Apache is reporting status as Total requests: 8; Idle/Busy workers 100/0

So when I attached strace on pid 4105, we can see that it is periodicaly sending status updates to systemd:

sudo strace -f -p 4105

wait4(-1, 0x7ffcfab4a25c, WNOHANG|WSTOPPED, NULL) = 0
select(0, NULL, NULL, NULL, {tv_sec=1, tv_usec=0}) = 0 (Timeout)
socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 8
getsockopt(8, SOL_SOCKET, SO_SNDBUF, [212992], [4]) = 0
setsockopt(8, SOL_SOCKET, SO_SNDBUFFORCE, [8388608], 4) = 0
sendmsg(8, {msg_name={sa_family=AF_UNIX, sun_path="/run/systemd/notify"}, msg_namelen=21, msg_iov=[{iov_base="READY=1\nSTATUS=Total requests: 8"..., iov_len=110}], msg_iovlen=1, msg_controllen=0, msg_flags=0}, MSG_NOSIGNAL) = 110
close(8)                                = 0
wait4(-1, 0x7ffcfab4a25c, WNOHANG|WSTOPPED, NULL) = 0

You can see that it is sending READY=1\nSTATUS=Total requests: 8... into socket /run/systemd/notify

Recommended reading

man systemd-notify

or official documentation.

Example : Service startup in Systemd