Don’t feel like shelling out $$$ for NewRelic or Blackfire.io? Got a micro instance hosting a blog that nobody reads that doesn’t have the memory to support enterprise monitoring anyway (*cough* this blog *cough*)?
Here’s a shell script that will email you when server load gets above whatever threshold you specify. Would be pretty easy to adapt to monitor memory using the ‘
free‘ command as well. Just schedule it using ‘
crontab -e‘, like ‘
*/5 * * * * /path/to/script.sh‘ for every 5 minutes, and you’re set.
Server load monitoring on a budget!
#!/bin/bash # requires bc library - yum install bc # config # alert threshold, as decimal ALERT=.7; # 70% CPU utilization # admin email EMAIL='[email protected]ever.com'; # add /usr/bin to path so cron works export PATH=$PATH:/usr/bin; # get number of processors NPROC=`nproc`; # get first utilization metric UTIL=`cat /proc/loadavg | cat -d ' ' -f 1`; # divide util by number of processors, accounting for 0.00 util RESULT=`bc <<< "scale = 2; $UTIL / $NPROC"`; # email alert if util is greater than alert threshold if [[ `bc <<< "$RESULT > $ALERT"` -eq 1 ]] then # calculate a percentage PERC=`bc <<< "scale = 2; $RESULT * 100"`; echo "CPU utilization is above threshold at $PERC %"; # add top output to email TOPOUTPUT=`top -n 1 -b`; `/usr/bin/mailx -s "Utilization high on $HOSTNAME" -r "$EMAIL" "$EMAIL" <<< "CPU on $HOSTNAME is at $PERC % $TOPOUTPUT"`; # else # echo "Utilization is only $RESULT"; fi
You can test it by generating CPU load with the
stress utility if you like.