#!/usr/bin/perl

# run as www-data (same as /run/hilis4/*.pid owner)
# perl script/kidreaper.pl `cat /run/hilis4/<service>.pid` <MB>
# adapted from http://www.catalystframework.org/calendar/2007/18 (changed kB to MB)

use strict;
use lib '/home/raj/perl5/lib/perl5';
use Data::Printer;

my ($ppid, $MB) = @ARGV;

die "Usage: kidreaper PPID ram_limit_in_MB\n" unless $ppid && $MB;

my $kids;

if ( open ($kids, "/bin/ps -o pid=,vsz= --ppid $ppid|") ) {
    my @goners;

    while (<$kids>) {
        chomp;
        my ($pid, $mem) = split; # p $mem;

        # ps shows KB.  we want MBytes.
        $mem /= 1024;

        if ($mem >= $MB) {
            warn sprintf "process %s mem [%s MB] > permitted [%s MB]",
                $pid, $mem, $MB;
            push @goners, $pid;
        }
    }

    close($kids);

    if (@goners) {
        # kill them slowly, so that all connection serving
        # children don't suddenly die at once.

        foreach my $victim (@goners) { # p $victim;
           # kill 'HUP', $victim;
           sleep 2;
        }
    }
}
else {
    die "Can't get process list: $!\n";
}
