Monitor Your Web Services from Bash
I have a web service that is continually causing me grief. It always fails at inconvenient times and, really, I ought to at least know when it fails. For other things I usually just use a service like Uptime Robot, but for this one I have different requirements:
- The service I want to monitor has a firewall that only allows access from a single host.
- And on that host, I didn't have permission to install new software. (It's temporary anyway)
- But, I do have access to SSH & Bash.
Therefore, here is my solution!
The only dependencies that are needed are common commands like curl, watch, mail, and the script I'll show you about.
1. Download and install this timeout script
curl -L http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3 > timeout3 chmod +x ./timeout3
2. Craft your one-liner.
Actual code (You can call this in your terminal or save it to a file):
watch -n 300 \
./timeout3 -t 15 \
curl -q -X GET http://url \
|| { echo "Cannot access PAGE_NAME. Waited 15 seconds on `date`" \
| mail -s "Web Site Not Responding" \
garrett.bluma@gmail.com; }
3. Done!
Oh, what's that? One-liners are complex and frustrating? I totally agree -- let's break it down!
watch -n 300 \
Watch is a program for monitoring command line applications output different information between calls. It calls the same command on a given interval and displays the results. This is handy for watching processes, but here we are using it solely for it's ability to kick off an application at some time interval. For a more elegant solution feel free to remove this and actually cron the thing.
./timeout3 -t 15 \
timeout3 is the script we downloaded earlier. Passing in -t 15 means that want the command (that is about to be defined) will be allowed to run for 15 seconds -- but once it reaches that limit, timeout3 will kill it.
curl -q -X GET http://url \
With curl we are simply sending a GET request to a server (over HTTP). If we receive a response, we do nothing and fall back to the watch command and wait until the next iteration. However, if this request takes too long however, the process will be interrupted by timeout3 and exit with an error -- this signals our script to send an email.
|| { echo "Cannot access PAGE_NAME. Waited 15 seconds on `date`" \
| mail -s "Web Site Not Responding" \
garrett.bluma@gmail.com; }
If the timeout process triggers an error (which we assume means the request took more than 15 seconds), then we send an email. We do this via the mail command, which we assign some options to and pass data in via stdin. You could also read it as follows;
|| { echo "message" \
| mail -s "title" \
"recipient"; }
Pingback: AirPort Scanning from Bash | Garrett Bluma