From 5bf4de497150a310fba6c4b1edf2df1f1bddba39 Mon Sep 17 00:00:00 2001 From: Cyberes Date: Thu, 28 Mar 2024 22:40:46 -0600 Subject: [PATCH] check_systemd_service: account for oneshot service --- check_systemd_service.sh | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/check_systemd_service.sh b/check_systemd_service.sh index 06fbf43..acb5625 100755 --- a/check_systemd_service.sh +++ b/check_systemd_service.sh @@ -3,7 +3,7 @@ function usage { echo "Usage: -u [UNIT name] - -t Service is triggered by a timer and is allowed to be inactive" + -t Service is triggered by a timer or is a oneshot service. Is allowed to be inactive" } UNIT_NAME="" @@ -46,25 +46,29 @@ fi # Check if the unit is active active=$(systemctl is-active "$UNIT_NAME") substate=$(systemctl show "$UNIT_NAME" --property=SubState --value) +exit_code=$(systemctl show "$UNIT_NAME" --property=ExecMainStatus --value) if [ "$active" = "activating" ]; then echo "WARNING - $UNIT_NAME is activating" exit 1 -elif [ "$active" != "active" ] || { [ "$substate" = "exited" ] && [ "$IS_TIMER" = false ]; }; then +elif [ "$active" != "active" ] && [ "$IS_TIMER" = false ]; then echo "CRITICAL - $UNIT_NAME is not active" exit 2 +elif [ "$IS_TIMER" = true ] && [ "$active" = "inactive" ] && [ "$exit_code" != "0" ]; then + echo "CRITICAL - $UNIT_NAME is inactive with non-zero exit code" + exit 2 fi # Get service start time start_time=$(systemctl show "$UNIT_NAME" --property=ExecMainStartTimestamp --value) +end_time=$(systemctl show "$UNIT_NAME" --property=ExecMainExitTimestamp --value) current_time=$(date +%s) -time_diff=$((current_time - $(date -d "$start_time" +%s))) -uptime_str="Started at $start_time. | uptime=${time_diff}s" +start_time_diff=$((current_time - $(date -d "$start_time" +%s))) +end_time_diff=$((current_time - $(date -d "$end_time" +%s))) - -if [ "$IS_TIMER" = true ] && [ "$substate" = "exited" ]; then - echo "OK - $UNIT_NAME is active (exited) and enabled. $uptime_str" +if [ "$IS_TIMER" = true ] && { [ "$substate" = "exited" ] || [ "$active" = "inactive" ]; }; then + echo "OK - $UNIT_NAME is active and exited (returned $exit_code) and enabled. Exited at $end_time. | downtime=${end_time_diff}s" else - echo "OK - $UNIT_NAME is active and enabled. $uptime_str" + echo "OK - $UNIT_NAME is active and enabled. Started at $start_time. | uptime=${start_time_diff}s" fi exit 0