Jeroen De Meerleer
bdb9ee05e7
This commit adds the check-systemctl-service.sh script which can be used to check if a systemd unit is active. The script takes in a unit file as an argument and has an optional flag to check for running within the current user. It returns exit codes based on whether the service is active, inactive or unknown.
94 lines
2.0 KiB
Bash
94 lines
2.0 KiB
Bash
#!/bin/bash
|
|
|
|
#
|
|
#/
|
|
#/ Usage:
|
|
#/ check-systemctl-service.sh <unit-file>
|
|
#/
|
|
#/ Options:
|
|
#/ -u, --user Check for running within current user
|
|
#/
|
|
#/ Checks if a systemd unit is active
|
|
#/
|
|
#/ Exit Codes:
|
|
#/ 0 Everything OK
|
|
#/ 2 Unit is not running
|
|
#/ 3 Unknown status
|
|
#/
|
|
|
|
|
|
Usage() {
|
|
grep '^#/' "${script_dir}/${script_name}" | sed 's/^#\/\w*//'
|
|
}
|
|
|
|
GetOptions() {
|
|
# https://stackoverflow.com/a/29754866
|
|
OPTIONS=u
|
|
LONGOPTS=user
|
|
|
|
# -use ! and PIPESTATUS to get exit code with errexit set
|
|
# -temporarily store output to be able to check for errors
|
|
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
|
|
# -pass arguments only via -- "$@" to separate them correctly
|
|
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
|
|
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
|
|
# e.g. return value is 1
|
|
# then getopt has complained about wrong arguments to stdout
|
|
Usage
|
|
exit 2
|
|
fi
|
|
|
|
# read getopt's output this way to handle the quoting right:
|
|
eval set -- "$PARSED"
|
|
|
|
# now enjoy the options in order and nicely split until we see --
|
|
while true; do
|
|
case "$1" in
|
|
-u|--user)
|
|
user='--user'
|
|
shift 1
|
|
;;
|
|
--)
|
|
shift
|
|
break
|
|
;;
|
|
*)
|
|
echo "SERVICE UNKNOWN - ${1} is not a valid parameter"
|
|
exit 3
|
|
;;
|
|
esac
|
|
done
|
|
|
|
if [ -z ${1+x} ]; then
|
|
echo "SERVICE UNKNOWN - Unitfile not given"
|
|
exit 3
|
|
else
|
|
service=${1}
|
|
fi
|
|
}
|
|
user=''
|
|
service=''
|
|
LC_NUMERIC="C"
|
|
GetOptions "$@"
|
|
|
|
if [[ $(systemctl ${user} list-unit-files "${service}*" | wc -l) -gt 3 ]]; then
|
|
result=$(systemctl ${user} is-active ${service})
|
|
else
|
|
result='inexistent'
|
|
fi
|
|
|
|
|
|
if [[ $result == 'active' ]]; then
|
|
rval=0
|
|
rmsg="OK"
|
|
elif [[ $result == 'inexistent' ]]; then
|
|
rval=1
|
|
rmsg="WARNING"
|
|
else
|
|
rval=2
|
|
rmsg="CRITICAL"
|
|
fi
|
|
|
|
echo "SERIVCE ${rmsg} - Service $service $result"
|
|
exit $rval
|