Skip to content

Instantly share code, notes, and snippets.

@asmuth
Last active December 12, 2015 03:28
Show Gist options
  • Save asmuth/4707206 to your computer and use it in GitHub Desktop.
Save asmuth/4707206 to your computer and use it in GitHub Desktop.
Linux Server Health Monitor (Fyrehose/FnordMetric)
#!/bin/bash
# This scripts sends a JSON message containing system health
# information to a fyrehose channel.
#
# Usage:
# $ ./linux_health_monitor.sh [host] [port] [channel]
# e.g.
# $ ./linux_health_monitor.sh localhost 2323 my_channel
#
# The JSON body will look like this:
# {
# "hostname": "my-hostname",
# "uptime": 1231523,
# "load_avg": [0.32, 0.16, 0.13],
# "mem": { "total": 4069, "free": 1096 },
# "swap": { "total": 0, "free": 0 },
# "disk_usage": "43%"
# }
if [[ $# -ne 3 ]]; then
echo "usage: $0 [host] [port] [channel]"
exit 1
fi
for cmd in df wc nc sed grep; do
which $cmd &> /dev/null
if [ $? != 0 ]; then
echo "error: command not found: $cmd"
exit 1
fi
done
data=$(
# hostname
echo "\"hostname\": \"$(hostname)\","
# uptime
cat /proc/uptime | \
sed -e 's/^\([0-9]\+\.[0-9]\+\).*/"uptime": \1,/'
# load_avg
cat /proc/loadavg | \
sed -e 's/^\([0-9]\+\.[0-9]\+\) \([0-9]\+\.[0-9]\+\) \([0-9]\+\.[0-9]\+\).*/"load_avg": [\1, \2, \3],/'
# mem usage
cat /proc/meminfo | \
grep -E '^(MemTotal|MemFree)' | \
sed -e 's/Mem//' -e 's/Total:[^0-9]\+\([0-9]\+\).*/"mem": { "total": \1,/' \
-e 's/Free:[^0-9]\+\([0-9]\+\).*/"free": \1 },/'
# swap_usage
cat /proc/meminfo | \
grep -E '^(SwapTotal|SwapFree)' | \
sed -e 's/Swap//' -e 's/Total:[^0-9]\+\([0-9]\+\).*/"swap": { "total": \1,/' \
-e 's/Free:[^0-9]\+\([0-9]\+\).*/"free": \1 },/'
# disk usage
df | grep -E '\/$' | \
sed -e 's/.* \([0-9]\+%\) .*/"disk_usage": "\1"/'
)
evt=$(echo "{ $data }" | sed -e ':x;N;$!bx;s/\n/ /g')
evt_len=$(echo -n $evt | wc -c)
(echo -n "#0 @$3 "'*'"$evt_len "; echo $evt) | \
nc $1 $2 > /dev/null
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment