Using the stress command to generate CPU load

I needed a reliable way to test a script I wrote to monitor server load. Luckily I found it in bash’s stress┬ácommand.

On most versions of Linux, you can install it with

yum install stress

or

apt-get install stress

depending on your distro.

I was on Centos 7.2, which of course doesn’t have the package in a repo (including EPEL), so I downloaded it from here

ftp://fr2.rpmfind.net/linux/dag/redhat/el7/en/x86_64/dag/RPMS/stress-1.0.2-1.el7.rf.x86_64.rpm

and did

yum localinstall stress-1.0.2-1.el7.rf.x86_64.rpm

Usage is straightforward, all I needed to do was generate 90 seconds of greater than 70% CPU usage on a one CPU cloud virt, so I did

stress --cpu 2 --timeout 90

Shell script to monitor server load

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]';

# 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.

Google Analytics – take daily with a grain of salt

Haven’t messed with Google Analytics in literally years, but since I’m getting a new site up I logged in. I noticed these spikes on all of my accounts for different sites, even sites that do not exist anymore:

WtfGoogleAnalytics
Most of the traffic was from Great Britain. I’m sure there’s an explanation… that I don’t have the time or motivation to uncover.

My point is – approach your analytics data with a touch of healthy skepticism.