Last active
May 29, 2018 10:25
-
-
Save ssato/491d56a0a2aa90dde43e81efd4ef0ac9 to your computer and use it in GitHub Desktop.
A sample script to monitor systemd service units forever.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# | |
# A sample script to monitor systemd service units forever. | |
# | |
# Requirements: timeout and sleep in coreutils, uuidgen in utl-linux and systemd | |
# | |
# Author: Satoru SATOH <[email protected]> | |
# License: MIT | |
# | |
set -e | |
USAGE="Usage: $0 SVC_NAME_0 [SVC_NAME_1 [SVC_NAME_2 [...]]]" | |
INTERVAL=10m # How long to sleep. See also sleep(1). | |
TIMEOUT=3m # How long to wait for 'systemctl is-active ...' finished. See also timeout(1). | |
HELP_TXT="$USAGE | |
Options: | |
-I INTERVAL Interval to monitor services [${INTERVAL}]. | |
The format is same as sleep(1). | |
-T TIMEOUT Timeout to wait for getting the status of each service [${TIMEOUT}]. | |
The format is same as timeout(1). | |
-v Verbose mode | |
-h Show this help" | |
function show_help () { | |
cat << EOH | |
${HELP_TXT:?} | |
EOH | |
} | |
function log () { | |
logger --journald << EOM | |
PRIORITY=err | |
MESSAGE_ID=$(uuidgen) | |
MESSAGE=$@ | |
EOM | |
} | |
function vecho () { :; } # Do nothing. | |
while getopts I:T:vh OPT | |
do | |
case "${OPT}" in | |
I) INTERVAL=${OPTARG} | |
;; | |
T) TIMEOUT=${OPTARG} | |
;; | |
v) vecho () { echo "$@"; } | |
;; | |
h) show_help; exit 0 | |
;; | |
\?) echo '[Error] Invalid option[s] and/or arguments!' > /dev/stderr; exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
test $# -gt 0 || { echo $USAGE; exit 1; } | |
SVC_NAMES="$@" | |
while true; do | |
for svc in ${SVC_NAMES}; do | |
vecho "[Info] Checking if the service ${svc} is running..." | |
timeout ${TIMEOUT:?} systemctl is-active ${svc}.service >/dev/null 2>/dev/null || \ | |
{ log "${svc} does not look active (running)"; exit $?; } | |
done | |
sleep ${INTERVAL:?} | |
done | |
# vim:sw=2:ts=2:et: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment