Last active
September 22, 2015 11:07
-
-
Save byrnedo/3fe9727c33fad1ffa02e to your computer and use it in GitHub Desktop.
Check if one can get a response on a nats channel. I use it for health checking node services. Uses mailgun to email.
This file contains 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 | |
set -ueo pipefail | |
natsUrl="nats://user:pass@192.168.1.84:4222" | |
checkTimeout=6 | |
mailgunDomain=CHANGEME | |
mailgunAPIKey=CHANGEME | |
deliveryEmailAddress=CHANGEME | |
SEND_ERROR_MAIL=1 | |
echo "Polling url: ${natsUrl}" | |
function mailError { | |
local service=$1 | |
mailMessage "!ERROR! - SERVICE NOT RESPONDING: ${service} service not responding" "ERROR: a service is not responding: ${service}" | |
} | |
function mailLazerus { | |
local service=$1 | |
mailMessage "OK - SERVICE IS ALIVE: ${service}" "Service is responding: ${service}" | |
} | |
function mailMessage { | |
local subject=$1 | |
local message=$2 | |
echo "sending mail via mailgun: ${subject} | ${message}" | |
curl -s --user "api:${mailgunAPIKey}" \ | |
https://api.mailgun.net/v3/${mailgunDomain}/messages \ | |
-F from="Services Alert <mailgun@${mailgunDomain}>" \ | |
-F to=${deliveryEmailAddress} \ | |
-F subject="${subject}" \ | |
-F text="${message}" | |
} | |
for service in blog user | |
do | |
set +e | |
timeout ${checkTimeout} /usr/local/bin/nats-request "${service}.system.up" '{}' -n1 -t -s "${natsUrl}" | |
result=$? | |
set -e | |
echo "Result ${result}" | |
if [[ ${result} -ne 1 ]] | |
then | |
echo "error code ${result} checking ${service}" | |
sendMail=0 | |
if [[ -f ./LAST_ALERT_EMAIL_${service} ]] | |
then | |
if [[ $(( (`date +%s` - `stat -L --format %Y ./LAST_ALERT_EMAIL_${service}`) > (30*60) )) -eq 1 ]] | |
then | |
rm ./LAST_ALERT_EMAIL_${service} | |
sendMail=${SEND_ERROR_MAIL} | |
else | |
echo not sending mail as less than 30 minutes since last | |
fi | |
else | |
touch ./LAST_ALERT_EMAIL_${service} | |
sendMail=${SEND_ERROR_MAIL} | |
fi | |
if [[ ${sendMail} -eq ${SEND_ERROR_MAIL} ]] | |
then | |
mailError ${service} | |
fi | |
else | |
echo "healthy response from ${service}" | |
if [[ -f ./LAST_ALERT_EMAIL_${service} ]] | |
then | |
echo "Sending service ok email" | |
mailLazerus ${service} | |
rm ./LAST_ALERT_EMAIL_${service} | |
fi | |
fi | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment