My server watchdog had a check that could never fire: pipefail and grep -q
I have a small watchdog script on each server. Every five minutes it checks that the site answers, that the services are running and that the disk is not full, and it sends me a message when something changes. One of its checks never ran. The script looked correct, and it reported that all was well.
The line
The script starts the way careful bash scripts start, with pipefail on. Later it asks whether a service exists on this server before checking it, because the same script runs on several machines:
set -o pipefail
if systemctl list-unit-files | grep -q 'trading-engine.service'; then
check_service trading-engine
fi
On the server where that service is the whole point, the condition was false every time.
Why
Three things happen in that one line.
- grep -q stops at the first match. It has its answer, so it exits and closes its end of the pipe.
- systemctl is still writing its list. Writing to a closed pipe kills it with SIGPIPE, and its exit status is 141.
- Without pipefail, the status of a pipeline is the status of the last command: grep found it, 0, true. With pipefail, any failing command fails the pipeline. So the condition is false because grep succeeded early.
You can see it in one line in any terminal:
set -o pipefail; seq 1 100000 | grep -q 1; echo $?
It prints 141. Without pipefail it prints 0.
Whether it happens depends on how much the first command still has to write when grep exits. A short list fits in the pipe buffer and the line works. A long list does not fit. That is why this kind of line passes on a small test machine and fails on the real one.
The fix
Read the output once into a variable, then test the variable. There is no pipe, so nothing can be cut short:
units=$(systemctl list-unit-files --no-legend)
case "$units" in
*trading-engine.service*) check_service trading-engine ;;
esac
In any script that uses pipefail, I now search for a pipe into grep -q, head or anything else that stops reading early.
A check that cannot fail is worse than no check
The real lesson was not about bash. The watchdog had never once been seen to fire for that service, and I had never tried. Now each check gets tested the rude way: stop the service on purpose and wait for the message.
The other rules the watchdog follows
- Alert on a change of state, not on the state. A service that is down produces one message when it goes down and one when it comes back. A message every five minutes gets muted within the hour, and a muted alarm is no alarm.
- Report recovery. Otherwise you have to log in to learn that it fixed itself.
- Watch from outside as well. A script on the server cannot tell you that the server is gone. Each of my two servers checks the other one's public address.
- Keep it boring: cron, curl and a chat message. The watchdog must have fewer moving parts than what it watches.