user mode OOM for LAMP

#!/usr/bin/perl

use strict;
use warnings;
use Proc::ProcessTable;

my $table = Proc::ProcessTable->new;
my $doeskill=0;
for my $process (@{$table->table}) {
# skip root processes
#next if $process->uid == 0 or $process->gid == 0;

# skip anything other than Passenger application processes
next unless $process->fname =~/apache2|php|mysql/;

# skip any using less than 0.5 GiB
next if $process->rss < 1024*1024*512; # document the slaughter (my $cmd = $process->cmndline) =~ s/\s+\z//;
print “Killing process: pid=”, $process->pid, ” uid=”, $process->uid, ” rss=”, $process->rss, ” fname=”, $process->fname, ” cmndline=”, $cmd, “\n”;

# try first to terminate process politely
kill 15, $process->pid;

# wait a little, then kill ruthlessly if it’s still around
sleep 5;
kill 9, $process->pid;
$doeskill=1;
}

if($doeskill)
{
print “restarting apache and mysql\n”;
`/usr/sbin/service apache2 restart`;
`/usr/sbin/service mysql restart`;
}
else
{
print “clean, no need restart web\n”;
}