check_systemd_service: also check uptime

This commit is contained in:
Cyberes 2024-03-28 21:12:08 -06:00
parent 9b5d5e88a8
commit 24e17a6cfc
1 changed files with 18 additions and 12 deletions

View File

@ -6,15 +6,14 @@ function usage {
-t Service is triggered by a timer and is allowed to be inactive" -t Service is triggered by a timer and is allowed to be inactive"
} }
# Initialize variables UNIT_NAME=""
UNIT=""
IS_TIMER=false IS_TIMER=false
# Parse command line arguments # Parse command line arguments
while getopts "u:t" opt; do while getopts "u:t" opt; do
case ${opt} in case ${opt} in
u ) u )
UNIT=$OPTARG UNIT_NAME=$OPTARG
;; ;;
t ) t )
IS_TIMER=true IS_TIMER=true
@ -32,33 +31,40 @@ done
shift $((OPTIND -1)) shift $((OPTIND -1))
# Check if UNIT name is provided # Check if UNIT name is provided
if [ -z "$UNIT" ]; then if [ -z "$UNIT_NAME" ]; then
usage usage
exit -1 exit -1
fi fi
# Check if the unit is enabled # Check if the unit is enabled
enabled=$(systemctl is-enabled "$UNIT") enabled=$(systemctl is-enabled "$UNIT_NAME")
if [ "$enabled" != "enabled" ]; then if [ "$enabled" != "enabled" ]; then
echo "CRITICAL - $UNIT is not enabled" echo "CRITICAL - $UNIT_NAME is not enabled"
exit 2 exit 2
fi fi
# Check if the unit is active # Check if the unit is active
active=$(systemctl is-active "$UNIT") active=$(systemctl is-active "$UNIT_NAME")
substate=$(systemctl show "$UNIT" --property=SubState --value) substate=$(systemctl show "$UNIT_NAME" --property=SubState --value)
if [ "$active" = "activating" ]; then if [ "$active" = "activating" ]; then
echo "WARNING - $UNIT is activating" echo "WARNING - $UNIT_NAME is activating"
exit 1 exit 1
elif [ "$active" != "active" ] || { [ "$substate" = "exited" ] && [ "$IS_TIMER" = false ]; }; then elif [ "$active" != "active" ] || { [ "$substate" = "exited" ] && [ "$IS_TIMER" = false ]; }; then
echo "CRITICAL - $UNIT is not active" echo "CRITICAL - $UNIT_NAME is not active"
exit 2 exit 2
fi fi
# Get service start time
start_time=$(systemctl show "$UNIT_NAME" --property=ExecMainStartTimestamp --value)
current_time=$(date +%s)
time_diff=$((current_time - $(date -d "$start_time" +%s)))
uptime_str="Started at $start_time. | uptime=${time_diff}s"
if [ "$IS_TIMER" = true ] && [ "$substate" = "exited" ]; then if [ "$IS_TIMER" = true ] && [ "$substate" = "exited" ]; then
echo "OK - $UNIT is active (exited) and enabled" echo "OK - $UNIT_NAME is active (exited) and enabled. $uptime_str"
else else
echo "OK - $UNIT is active and enabled" echo "OK - $UNIT_NAME is active and enabled. $uptime_str"
fi fi
exit 0 exit 0