#!/usr/bin/perl use strict; ################################################################## # Script downloaded from http://www.nerdgirl.dk/qa/server_load.txt # # Author: Jette Nielsen ( nerdgirl at nerdgirl dot dk) # # Created: 2004-12-12 Last update: 2005-06-28 # # Description: This script will report if the CPU load exceeds # # a certain percentage ($limit) # # ---------------------------------------------------------------- # # 1. Save this script in a file called server_load.pl owned by root # # Change the value of $max_load, to one of your choice # # 2. Make sure that the script is executable by the owner: # # 'chmod u+x server_load.pl' # # 3. Create the entry in the crontab of the root user, and make it # # run as often as you like, e.g. every 5 minutes: # # 0-59/5 * * * * /path/to/server_load.pl | mail -s "Server load" email@domain.tld # # # # Feel free to make any changes ... do not forget to mail me, if # # you think of something brilliant :-) # # ################################################################ # my $max_load = 50; # Call top and get all links beneath the headings line my $top = `/usr/bin/top -b -n`; $top =~ s/^.+?PID[^\n]+\n//s; # Then put all proccesses into an array... my @procs = split(/\n/, $top); my @procval = (); my @excee = (); my $total; # Loop through each process if (@procs > 0) { foreach my $value (@procs) { @procval = split /\s+/, $value; $procval[9] =~ /(\d+)/; $total += $1; if ($1 > 0) { push (@excee,$value); } } } my $start; my $stop; # Is the limit exceeded? if ($total > 50) { print "CPU usage limit exceeded: $total\n\n"; print join("\n",@excee)."\n\n"; # Limit is exceeded, try to restart apache $stop = `/usr/local/sbin/apachectl stop`; if ($stop =~ /httpd stopped$/) { $start = `/usr/local/sbin/apachectl start`; if ($start =~ /httpd started$/) { print "Apache was successfully restarted\n"; } else { print "Could not restart apache:\n$start\n"; } } else { print "Could not stop apache:\n$stop\n"; } }