Building a Simple Health-Check Script
A health check is a short, automatic test that answers one question: is this system working right now? Earlier lessons built single checks: disk space (lesson 166), CPU, memory and load (lesson 167), and website availability (lesson 168). On a real server, an administrator wants all of them at once, plus a few more (is the database process running, is its port open, did last night's backup actually happen), and a single answer at the end: everything fine, something to look at soon, or something broken now.
This lesson builds that kind of script. The important part is not any single check, which are each a few lines, but the structure around them: a common way for every check to report its result, a single overall status that other programs can act on, time limits so that one hanging check cannot block the others, and a configuration file so the same script can check different servers.
The Status Convention
A health check needs more than "worked" and "failed". A disk that is 82% full is not an emergency, but it should be noticed; a database that does not answer is. The convention used by Nagios, Icinga and many other monitoring systems, and by most health-check scripts, has four levels, each with a fixed exit status:
| Exit status | Name | Meaning |
|---|---|---|
| 0 | OK | everything is within limits |
| 1 | WARNING | a limit is close; attention needed soon |
| 2 | CRITICAL | something is broken or past its hard limit |
| 3 | UNKNOWN | the check itself could not run (bad configuration, missing data) |
A check with a numeric measurement uses two thresholds: a warning threshold and a critical threshold. With disk usage limits of 80 and 90, a value of 75% is OK, 85% is WARNING, and 93% is CRITICAL.
UNKNOWN deserves its own status. If a check is misconfigured, for example a typing mistake in a mount point, reporting OK would hide the problem forever, and reporting CRITICAL would wake someone up for something that is not a server fault. UNKNOWN says "the check is broken", which is a different problem with a different fix.
Because the levels are ordered by severity, the overall result of many checks is simply the worst (highest) status among them, as long as UNKNOWN is treated as the highest. That is the rule the script below uses.
Following this convention has a practical benefit: the script can later be plugged into a monitoring system as a plugin, and in the meantime, any script or cron job can act on its exit status (healthcheck.sh || send-alert).
Designing the Checks
Every check in the script is a function with the same contract:
- it receives its settings as arguments (a mount point and two thresholds, a URL, and so on),
- it stores a one-line, human-readable result in a global variable
msg, - it returns 0, 1, 2 or 3 as its status.
A function can only return a number, which is why the message goes into a variable (lesson 91 compares the ways to get data out of a function). Keeping the message and the status separate means the main loop can count, print and compare results without knowing anything about individual checks, and adding a new check type means writing one function.
Comparing values with two thresholds
Several checks compare a measurement against a warning and a critical threshold. Some measurements, such as load averages, are decimal numbers, and Bash arithmetic handles only integers:
[[ 1.5 -ge 1 ]]
(( 1.5 >= 1 ))
rate.sh: line 8: [[: 1.5: syntax error: invalid arithmetic operator (error token is ".5")
rate.sh: line 9: ((: 1.5 >= 1 : syntax error: invalid arithmetic operator (error token is ".5 >= 1 ")
A small helper passes the comparison to awk, which uses floating-point numbers, and returns the result as its exit status:
rate() {
awk -v v="$1" -v w="$2" -v c="$3" 'BEGIN { exit (v >= c ? 2 : (v >= w ? 1 : 0)) }'
}
for v in 0.75 1.0 1.5 2.0 10; do
rate "$v" 1.0 2.0
echo "$v -> $?"
done
0.75 -> 0
1.0 -> 1
1.5 -> 1
2.0 -> 2
10 -> 2
rate VALUE WARN CRIT returns OK (0), WARNING (1) or CRITICAL (2) for any measurement where a higher value is worse. The values are passed with -v rather than placed inside the awk program text, so they cannot change the program (lesson 155). A BEGIN block runs without reading any input, and exit with a number sets awk's exit status. Because rate is the last command in a check function, its status becomes the function's return value.
Checking a TCP port without extra tools
To check that a service, such as a database, accepts connections, the script only needs to open a TCP connection to its port. Bash can do that by itself: a redirection to the special path /dev/tcp/HOST/PORT makes Bash open a network connection instead of a file. The path does not exist on disk; Bash recognizes it:
if : > /dev/tcp/127.0.0.1/8080; then echo "8080 open"; fi
if : > /dev/tcp/127.0.0.1/5432; then echo "5432 open"; else echo "5432 status $?"; fi
ls /dev/tcp
8080 open
tcp.sh: connect: Connection refused
tcp.sh: line 2: /dev/tcp/127.0.0.1/5432: Connection refused
5432 status 1
ls: cannot access '/dev/tcp': No such file or directory
: is the do-nothing command, so : > /dev/tcp/... opens the connection and closes it again. If nothing listens on the port, the connection is refused immediately. A host that does not answer at all (for example, behind a firewall that silently drops packets) is worse: the connection attempt can hang for minutes. That is why the check runs the redirection in a separate bash under timeout (lesson 142). /dev/tcp is a Bash feature; Dash and other shells do not have it, and some distributions build Bash without it, in which case nc -z HOST PORT from netcat is the usual alternative.
Every check needs a time limit
A health-check script that hangs is worse than no script: it reports nothing, and if it runs from cron every few minutes, hanging copies pile up. Every check that waits for something outside the machine gets a limit: the port check uses timeout, and the HTTP check uses curl's --max-time (lesson 168). Local checks, such as reading /proc/meminfo or running df, finish immediately. (On a server with a hung network file system, even df can hang; such servers would need timeout around df too.)
The checks run one after another, so the worst-case run time is the sum of the time limits. With a 5-second limit and a handful of network checks, the script finishes well within a minute even when everything is down.
The Configuration File
Hard-coding the checks would mean a different copy of the script for every server. Instead, the script reads a small configuration file with one check per line: the check type, then its values, separated by spaces. The checks for a web server might look like this:
# healthcheck.conf for web01
disk / 80 90
memory 80 90
load 1.0 2.0
process python3
port 127.0.0.1 8080
http http://127.0.0.1:8080/health
age /srv/backup/db-latest.sql.gz 26 50
The script reads each line into an array with read -r -a fields (lesson 114), takes the first word as the check type and the rest as its values, and checks both before calling anything:
- the type must be one of the known check types, listed in an associative array
NVALUESthat maps each type to the number of values it takes (lesson 102); - the number of values must match.
Only then does it call the function check_TYPE with the values as separate arguments. Because the type has been checked against a fixed list, building the function name from it is safe, and no eval is needed (lesson 157). A configuration file is data, and the script never executes anything from it.
A Complete Example: healthcheck.sh
#!/usr/bin/env bash
#
# healthcheck.sh - run simple health checks listed in a config file
#
# Usage: healthcheck.sh [-q] [-c CONFIG]
# -q quiet: print only the checks that are not OK
# -c CONFIG config file (default: /etc/healthcheck.conf)
#
# Config lines (blank lines and lines starting with # are ignored):
# disk MOUNT WARN% CRIT% disk space used on a mount point
# memory WARN% CRIT% memory in use, based on MemAvailable
# load WARN CRIT 1-minute load average per CPU, e.g. 1.0 2.0
# process NAME a process with exactly this name is running
# port HOST PORT a TCP connection can be opened
# http URL [CODE] the URL answers with CODE (default 200)
# age FILE WARN_HOURS CRIT_HOURS the file was modified recently
#
# Exit status: the worst result of all checks
# 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN (a check could not be run)
set -uo pipefail
export LC_ALL=C
readonly OK=0 WARNING=1 CRITICAL=2 UNKNOWN=3
readonly NAMES=(OK WARNING CRITICAL UNKNOWN)
readonly TIMEOUT=5 # seconds allowed for each network check
config=/etc/healthcheck.conf
quiet=0
usage() { echo "usage: ${0##*/} [-q] [-c CONFIG]" >&2; exit "$UNKNOWN"; }
is_int() { [[ $1 =~ ^[0-9]+$ ]]; }
is_number() { [[ $1 =~ ^[0-9]+(\.[0-9]+)?$ ]]; }
# rate VALUE WARN CRIT: OK, WARNING or CRITICAL for a value where higher is worse
rate() {
awk -v v="$1" -v w="$2" -v c="$3" 'BEGIN { exit (v >= c ? 2 : (v >= w ? 1 : 0)) }'
}
# Each check_TYPE function sets the global variable msg to a one-line result
# and returns OK, WARNING, CRITICAL or UNKNOWN.
check_disk() {
local mount=$1 warn=$2 crit=$3 used
is_int "$warn" && is_int "$crit" || { msg="disk $mount: invalid thresholds"; return "$UNKNOWN"; }
[[ -d $mount ]] || { msg="disk $mount: no such folder"; return "$UNKNOWN"; }
used=$(df -P -- "$mount" | awk 'NR == 2 { sub(/%/, "", $5); print $5 }')
is_int "$used" || { msg="disk $mount: could not read usage"; return "$UNKNOWN"; }
msg="disk $mount: ${used}% used (warn ${warn}%, crit ${crit}%)"
rate "$used" "$warn" "$crit"
}
check_memory() {
local warn=$1 crit=$2 total avail used
is_int "$warn" && is_int "$crit" || { msg="memory: invalid thresholds"; return "$UNKNOWN"; }
total=$(awk '$1 == "MemTotal:" { print $2 }' /proc/meminfo)
avail=$(awk '$1 == "MemAvailable:" { print $2 }' /proc/meminfo)
is_int "$total" && is_int "$avail" || { msg="memory: could not read /proc/meminfo"; return "$UNKNOWN"; }
used=$(( (total - avail) * 100 / total ))
msg="memory: ${used}% in use, $(( avail / 1024 )) MiB available (warn ${warn}%, crit ${crit}%)"
rate "$used" "$warn" "$crit"
}
check_load() {
local warn=$1 crit=$2 load1 cpus per_cpu
is_number "$warn" && is_number "$crit" || { msg="load: invalid thresholds"; return "$UNKNOWN"; }
read -r load1 _ < /proc/loadavg
cpus=$(nproc)
per_cpu=$(awk -v l="$load1" -v n="$cpus" 'BEGIN { printf "%.2f", l / n }')
msg="load: $load1 on $cpus CPUs = $per_cpu per CPU (warn $warn, crit $crit)"
rate "$per_cpu" "$warn" "$crit"
}
check_process() {
local name=$1 count
[[ -n $name ]] || { msg="process: no name given"; return "$UNKNOWN"; }
count=$(pgrep -cx -- "$name")
if (( count == 0 )); then
msg="process $name: not running"
return "$CRITICAL"
fi
msg="process $name: $count running"
return "$OK"
}
check_port() {
local host=$1 port=$2
is_int "$port" && (( port >= 1 && port <= 65535 )) || { msg="port $host:$port: invalid port"; return "$UNKNOWN"; }
# Bash opens a TCP connection when redirecting to /dev/tcp/HOST/PORT.
# It runs in a separate bash so that timeout can stop it if it hangs.
timeout "$TIMEOUT" bash -c ': > "/dev/tcp/$1/$2"' _ "$host" "$port" 2>/dev/null
case $? in
0) msg="port $host:$port: open"; return "$OK" ;;
124) msg="port $host:$port: no answer within ${TIMEOUT}s" ;;
*) msg="port $host:$port: connection failed" ;;
esac
return "$CRITICAL"
}
check_http() {
local url=$1 want=${2:-200} code rc
[[ $url == http://* || $url == https://* ]] || { msg="http $url: not an http(s) URL"; return "$UNKNOWN"; }
code=$(curl -sS -o /dev/null -w '%{http_code}' --max-time "$TIMEOUT" -- "$url" 2>/dev/null)
rc=$?
if (( rc != 0 )); then
case $rc in
6) msg="http $url: host name not found" ;;
7) msg="http $url: connection refused" ;;
28) msg="http $url: no answer within ${TIMEOUT}s" ;;
*) msg="http $url: curl failed with status $rc" ;;
esac
return "$CRITICAL"
fi
msg="http $url: status $code"
[[ $code == "$want" ]] && return "$OK"
msg+=" (expected $want)"
return "$CRITICAL"
}
check_age() {
local file=$1 warn=$2 crit=$3 mtime hours
is_int "$warn" && is_int "$crit" || { msg="age $file: invalid thresholds"; return "$UNKNOWN"; }
if ! mtime=$(stat -c %Y -- "$file" 2>/dev/null); then
msg="age $file: file not found"
return "$CRITICAL"
fi
hours=$(( (EPOCHSECONDS - mtime) / 3600 ))
msg="age $file: modified ${hours}h ago (warn ${warn}h, crit ${crit}h)"
rate "$hours" "$warn" "$crit"
}
while getopts ':qc:' opt; do
case $opt in
q) quiet=1 ;;
c) config=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 0 )) || usage
[[ -r $config ]] || { echo "${0##*/}: cannot read config file '$config'" >&2; exit "$UNKNOWN"; }
# Number of values each check type takes after its name
declare -A NVALUES=([disk]=3 [memory]=2 [load]=2 [process]=1 [port]=2 [http]="1 2" [age]=3)
worst=$OK
counts=(0 0 0 0)
line_no=0
while read -r -a fields || (( ${#fields[@]} > 0 )); do
(( line_no++ ))
if (( ${#fields[@]} == 0 )) || [[ ${fields[0]} == \#* ]]; then
continue
fi
type=${fields[0]}
values=( "${fields[@]:1}" )
if [[ -z ${NVALUES[$type]-} ]]; then
msg="line $line_no: unknown check '$type'"
status=$UNKNOWN
elif [[ " ${NVALUES[$type]} " != *" ${#values[@]} "* ]]; then
msg="line $line_no: '$type' expects ${NVALUES[$type]// / or } value(s), got ${#values[@]}"
status=$UNKNOWN
else
# $type is one of the names in NVALUES, so this calls a known function
"check_$type" "${values[@]}"
status=$?
fi
(( counts[status]++ ))
(( status > worst )) && worst=$status
if (( ! quiet || status != OK )); then
printf '%-8s %s\n' "${NAMES[status]}" "$msg"
fi
done < "$config"
if (( ! quiet || worst != OK )); then
printf -- '-- %s: %d OK, %d WARNING, %d CRITICAL, %d UNKNOWN\n' \
"${NAMES[worst]}" "${counts[@]}"
fi
exit "$worst"
How It Works
- Constants for the four levels.
OK,WARNING,CRITICALandUNKNOWNare read-only variables, so the code saysreturn "$CRITICAL"instead of a barereturn 2.NAMESturns a status back into its name for printing. export LC_ALL=Ckeeps the output ofdf,awkand other tools in a predictable format, for example a period as the decimal separator, whatever language the server is set to.- The checks.
check_diskreads the use percentage fromdf -P(the portable output format, one line per file system) and rates it.check_memorycalculates the percentage of memory in use fromMemTotalandMemAvailablein/proc/meminfo.MemAvailableis the kernel's estimate of memory that can be used without swapping, which includes reclaimable cache, so it is the right measure (lesson 167).check_loaddivides the 1-minute load average by the number of CPUs fromnproc, so the same thresholds work on a 2-CPU and a 32-CPU server.check_processcounts processes with exactly the given name usingpgrep -cx(lesson 143). On systemd servers,systemctl is-active --quiet NAME.serviceis a more precise test for a service; it is not used here because it requires systemd.check_portopens a TCP connection through/dev/tcpundertimeout. The host and port are passed to the innerbash -cas arguments (_ "$host" "$port"become$0,$1and$2), not pasted into the command string, so no value from the configuration file is ever run as code. Status 124 fromtimeoutmeans the connection attempt timed out; anything else means it failed.check_httpuses curl with-o /dev/nullto discard the page and-w '%{http_code}'to print only the HTTP status. curl's own exit status distinguishes a failed connection (7), an unknown host name (6) and a timeout (28) from a server that answered with the wrong status.check_agecompares a file's modification time (stat -c %Y, seconds since 1970) with the current time ($EPOCHSECONDS). This catches a very common silent failure: a backup job that has stopped running. The newest backup file simply gets older and older.
- Invalid settings are UNKNOWN. Each check validates its own values (a whole number for a percentage, a decimal for a load, a port between 1 and 65535) and returns UNKNOWN with a message rather than producing a wrong result.
- The main loop counts each status in the array
counts, keeps the worst status inworst, and prints one line per check, or only the problems with-q. A summary line ends the output, andexit "$worst"makes the overall result available to whatever runs the script. - A last line without a newline is still read, thanks to
|| (( ${#fields[@]} > 0 ))(lesson 114).
Running the Complete Example
The test machine had a small Python web server on port 8080 with three paths: /health answers 200, /broken answers 500, and /slow waits 10 seconds before answering. Two backup files were created with touch -d: db-latest.sql.gz dated 3 hours ago and site-latest.tar.gz dated 30 hours ago.
With the configuration shown earlier, every check passes:
$ healthcheck.sh -c all-ok.conf
OK disk /: 29% used (warn 80%, crit 90%)
OK memory: 6% in use, 7474 MiB available (warn 80%, crit 90%)
OK load: 0.00 on 2 CPUs = 0.00 per CPU (warn 1.0, crit 2.0)
OK process python3: 1 running
OK port 127.0.0.1:8080: open
OK http http://127.0.0.1:8080/health: status 200
OK age /srv/backup/db-latest.sql.gz: modified 3h ago (warn 26h, crit 50h)
-- OK: 7 OK, 0 WARNING, 0 CRITICAL, 0 UNKNOWN
[status 0]
$ healthcheck.sh -q -c all-ok.conf
[status 0]
With -q, a healthy system produces no output at all, which is what a cron job needs: no output means no mail (lesson 170).
A second configuration file contains problems: a disk warning threshold of 20% (so the 29% disk triggers it), a process that does not run (cron), a closed port (5432), the broken and slow pages, a port where nothing listens (9999), the 30-hour-old backup and a backup file that does not exist:
# the same checks with some problems
disk / 20 90
memory 80 90
load 1.0 2.0
process cron
port 127.0.0.1 5432
http http://127.0.0.1:8080/broken
http http://127.0.0.1:8080/slow
http http://127.0.0.1:9999/health
age /srv/backup/site-latest.tar.gz 26 50
age /srv/backup/missing.tar.gz 26 50
$ time healthcheck.sh -c problems.conf
WARNING disk /: 29% used (warn 20%, crit 90%)
OK memory: 6% in use, 7473 MiB available (warn 80%, crit 90%)
OK load: 0.00 on 2 CPUs = 0.00 per CPU (warn 1.0, crit 2.0)
CRITICAL process cron: not running
CRITICAL port 127.0.0.1:5432: connection failed
CRITICAL http http://127.0.0.1:8080/broken: status 500 (expected 200)
CRITICAL http http://127.0.0.1:8080/slow: no answer within 5s
CRITICAL http http://127.0.0.1:9999/health: connection refused
WARNING age /srv/backup/site-latest.tar.gz: modified 30h ago (warn 26h, crit 50h)
CRITICAL age /srv/backup/missing.tar.gz: file not found
-- CRITICAL: 2 OK, 2 WARNING, 6 CRITICAL, 0 UNKNOWN
real 0m5.061s
[status 2]
Each problem has a precise message, and the overall status is 2, the worst result. The whole run took about 5 seconds, almost all of it spent waiting for the slow page; without --max-time, it would have waited the full 10 seconds, and a page that never answers would have blocked the script indefinitely. With -q, the two OK lines are left out and everything else is the same.
To test the port timeout, the firewall of the test machine was told to silently drop all packets to 192.0.2.1 (an address reserved for documentation) with iptables -A OUTPUT -d 192.0.2.1 -j DROP, and a one-line configuration checked port 22 there:
$ time healthcheck.sh -c drop.conf
CRITICAL port 192.0.2.1:22: no answer within 5s
-- CRITICAL: 0 OK, 0 WARNING, 1 CRITICAL, 0 UNKNOWN
real 0m5.007s
[status 2]
The connection attempt received no answer at all, timeout stopped it after 5 seconds with status 124, and the check reported the timeout separately from the immediate refusal on port 5432. (The firewall rule was removed afterwards.)
A configuration file with mistakes produces UNKNOWN results instead of wrong answers:
disk /srv/nowhere 80 90
disk / high 90
dsik / 80 90
port 127.0.0.1 99999
http ftp://example.com/
load 1.0 2.0 3.0
process
http http://127.0.0.1:8080/health 200 extra
$ healthcheck.sh -c bad.conf
UNKNOWN disk /srv/nowhere: no such folder
UNKNOWN disk /: invalid thresholds
UNKNOWN line 3: unknown check 'dsik'
UNKNOWN port 127.0.0.1:99999: invalid port
UNKNOWN http ftp://example.com/: not an http(s) URL
UNKNOWN line 6: 'load' expects 2 value(s), got 3
UNKNOWN line 7: 'process' expects 1 value(s), got 0
UNKNOWN line 8: 'http' expects 1 or 2 value(s), got 3
-- UNKNOWN: 0 OK, 0 WARNING, 0 CRITICAL, 8 UNKNOWN
[status 3]
A missing configuration file and an unknown option are also UNKNOWN, with status 3:
$ healthcheck.sh -c nope.conf
healthcheck.sh: cannot read config file 'nope.conf'
[status 3]
$ healthcheck.sh -x
usage: healthcheck.sh [-q] [-c CONFIG]
[status 3]
A configuration file whose last line has no newline (created with printf 'process python3') is read completely:
OK process python3: 1 running
-- OK: 1 OK, 0 WARNING, 0 CRITICAL, 0 UNKNOWN
Running It Regularly
Because a healthy run with -q prints nothing and a problem prints a short report, the script fits directly into cron, which mails any output to MAILTO:
MAILTO=admin@example.com
*/5 * * * * /usr/local/bin/healthcheck.sh -q -c /etc/healthcheck.conf
This mails every five minutes for as long as a problem lasts, which is noisy but hard to ignore. The next lesson, on sending notifications from Bash scripts, shows how to send alerts to chat systems and how to report a problem once instead of every five minutes. The exit status can also drive other actions directly:
if ! /usr/local/bin/healthcheck.sh -q -c /etc/healthcheck.conf > /tmp/health.txt; then
# the report is in /tmp/health.txt; the status says how bad it is
...
fi
Adding a new kind of check means writing one check_NAME function that sets msg and returns a status, and adding its name and number of values to NVALUES; nothing else in the script changes.