monitoring-scripts/check_systemd_unit

54 lines
1.4 KiB
Plaintext
Raw Normal View History

2021-08-18 18:44:27 -05:00
#! /bin/bash
#
# check_systemd_unit.sh
# Copyright (C) 2021 Vintage Salt <rehashedsalt@cock.li>
#
# Distributed under terms of the MIT license.
#
# Usage: Set the first argument to be a systemd unit. The script will respond with the following:
# The unit is running OK
# The unit is dead
service="$1"
# If the service is null, be critical
if [ -z "$service" ]; then
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - Service is undefined"
exit 2
2021-08-18 18:44:27 -05:00
# If systemctl is not present, be critical
elif ! command -v systemctl > /dev/null 2>&1; then
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - systemctl missing from PATH"
exit 2
2021-08-18 18:44:27 -05:00
# If the service is failed, be critical
elif systemctl is-failed --quiet "$service" > /dev/null 2>&1; then
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - $service is failed"
2021-08-18 18:44:27 -05:00
exit 2
# Otherwise, see what its state is
else
systemctl status "$service" > /dev/null 2>&1
case $? in
0)
2021-08-18 19:41:04 -05:00
echo "UNIT OK - $service is running"
2021-08-18 18:44:27 -05:00
exit 0
;;
1|2)
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - $service is dead"
exit 2
2021-08-18 18:44:27 -05:00
;;
3)
# In this case, the unit is not running. Whether this is an issue depends on the type of service
if systemctl cat "$service" | grep -ie '^Type=' | grep -ie 'oneshot' > /dev/null 2>&1; then
2021-08-18 19:41:04 -05:00
echo "UNIT OK - $service is type oneshot and not running"
exit 0
2021-08-18 18:44:27 -05:00
else
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - $service is not running"
exit 2
2021-08-18 18:44:27 -05:00
fi
;;
4)
2021-08-18 19:41:04 -05:00
echo "UNIT CRITICAL - $service is not present on this machine"
exit 2
2021-08-18 18:44:27 -05:00
;;
esac
fi