jteichert
jteichert

Reputation: 617

Systemd unit, check status with external script

The short version is:

I have a systemd unit that I want to check the return code of a script when I call:

systemctl status service.service

Long version: I had a lsb init script that did exactly that, when status was passed as parameter it called a script that checked the state of several processes and based on the return code the init system returned the state correctly of the software.

Now when adapting the script to systemd I can't find out how to configure this behaviour.

Upvotes: 4

Views: 7553

Answers (3)

Alex
Alex

Reputation: 11

You can use:

systemctl show -p  ExecMainStatus service.service | sed 's/ExecMainStatus=//g'

This will return the exit code of the service.

Upvotes: 1

Alexis Wilke
Alexis Wilke

Reputation: 20800

If you are in control of the code of the service you start / stop that way, then you can easily edit it and save the result in a file.

Otherwise, you can always add a wrapper that does that for you.

#!/bin/sh
/path/to/service and args here
echo $? >/run/service.result

Then your status can be accessed using the contents of that file:

STATUS=`cat /run/service.result`
if test $STATUS = 1
then
  echo "An error occurred..."
fi

(Side note: /run/ is only writable by root, use /tmp/ if you are not root.)

Upvotes: 0

intelfx
intelfx

Reputation: 2764

Short answer

This is impossible in systemd. The systemctl status verb always does the same thing, it cannot be overrided per-unit to a custom action.

Long answer

You can write a foo-status.service unit file with Type=oneshot and ExecStart= pointing to your custom status script, and then run systemctl start foo-status. However, this will only provide a zero/nonzero information (any nonzero exit code will be converted to 1).

To get the real exit code of your status script, run systemctl show -pExecMainStatus foo-status, however, if you go this far, then it is simpler to run your script directly.

Upvotes: 4

Related Questions