From bb037649183d1be98dccb48c431097f062b861f8 Mon Sep 17 00:00:00 2001 From: Tarik Megzari Date: Mon, 31 Jan 2022 15:38:38 +0100 Subject: [PATCH] fix: Catch unexpected failures (#140) Signed-off-by: Tarik Megzari Co-authored-by: Tarik Megzari --- lib/common.sh | 14 ++++++++++++++ lib/main.sh | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/lib/common.sh b/lib/common.sh index 9a9a1cb..9c91783 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -103,6 +103,20 @@ debug() { if [ "$MACHINE_LOG_LEVEL" -ge 5 ]; then _logger "$GRAY" "[DBG ] $*"; fi } +exception() { + # Trap exit code is the same as the trapped one unless we call an explicit exit + TRAP_CODE=$? + if [ "$ACTIONS_DONE" -ne 1 ]; then + if [ "$BATCH_MODE" -eq 1 ]; then + BATCH_OUTPUT="KO $SCRIPT_NAME $BATCH_OUTPUT KO{Unexpected exit code: $TRAP_CODE}" + becho "$BATCH_OUTPUT" + else + crit "Check failed with unexpected exit code: $TRAP_CODE" + fi + exit 1 # Means critical status + fi +} + # # sudo wrapper # issue crit state if not allowed to perform sudo diff --git a/lib/main.sh b/lib/main.sh index 330dcf0..14f77e5 100644 --- a/lib/main.sh +++ b/lib/main.sh @@ -11,6 +11,7 @@ status="" forcedstatus="" SUDO_CMD="" SAVED_LOGLEVEL="" +ACTIONS_DONE=0 if [ -n "${LOGLEVEL:-}" ]; then SAVED_LOGLEVEL=$LOGLEVEL @@ -111,6 +112,9 @@ if [ -z "$status" ]; then exit 2 fi +# We want to trap unexpected failures in check scripts +trap exception EXIT + case $status in enabled | true) info "Checking Configuration" @@ -128,6 +132,7 @@ audit) ;; disabled | false) info "$SCRIPT_NAME is disabled, ignoring" + ACTIONS_DONE=1 exit 2 # Means unknown status ;; *) @@ -135,6 +140,8 @@ disabled | false) ;; esac +ACTIONS_DONE=1 + if [ "$CRITICAL_ERRORS_NUMBER" -eq 0 ]; then if [ "$BATCH_MODE" -eq 1 ]; then BATCH_OUTPUT="OK $SCRIPT_NAME $BATCH_OUTPUT"