#!/usr/bin/perl

# Changes to PHPCOUNT by mholland on 9/28/2015

$max_top = 5;
$time_top = shift || 10; # Defaults to 10 entries unless other number included at execution. Eg phpcount 3, phpcount 100.

%users = ();
%defunct = ();
%php5 = ();
%total = ();
%fcgi = ();
%size = ();
%process_time = ();
$tot_defunct = $tot_php5 = $tot_fcgi = 0;
@targeted_users = ();

$total_php5 = $total_defunt = $total_fastcgi = 0;

unless (get_command("ps axwwo uname,rss,etime,pid,cmd | grep php5 | grep -v grep")) {
    foreach $line (@output) {
        my @tmp = split(/\s+/, $line);
        my $username = $tmp[0];
        my $size = $tmp[1] / 1024;
        my $cmd = "";
        for ($i = 4; $i <= $#tmp; $i++) { $cmd .= $tmp[$i]; }
            unless ($cmd =~ 'fcgi') {
                $seconds_taken = elapsed_seconds($tmp[2]);
                $process_time{"[$tmp[2]] $username($tmp[3]): $cmd "} = $seconds_taken; }
            $users{$username}{'count'}++;
            if ($cmd =~ 'defunct') {
                $users{$username}{'defunct'}++; $tot_defunct++; }
            elsif ($cmd =~ 'fcgi') {
                $users{$username}{'fastcgi'}++; $tot_fcgi++; }
            elsif ($cmd =~ 'bin/php') {
                $users{$username}{'php5'}++; $tot_php5++; }
            $users{$username}{$cmd}++;
            $users{$username}{'resident_size'} += $size; } }

while ( my ($user, $name) = each(%users) ) {
    $defunct{$user} = $users{$user}{'defunct'};
    $php5{$user} = $users{$user}{'bin/php'};
    $fcgi{$user} = $users{$user}{'fastcgi'};
    $total{$user} = $users{$user}{'count'};
    $size{$user} = $users{$user}{'resident_size'} }

print "\n";
print "php process summary:\n";
my $total_procs = $#output + 1;
print" [$total_procs] total from " . keys(%total) . " users ($tot_php5 traditional, $tot_fcgi fastcgi, $tot_defunct defunct)\n";

$count = 0;
print "\nTop Total PHP Processes\n";

foreach $key (sort totalhashValueDescendingNum (keys(%total))) {
    $count++;
    next if ($count > $max_top);
    printf("%s (%d) => %.2d%\n", $key, $total{$key}, ($total{$key} / $total_procs * 100)); }

$count = 0;
print "\nTop by Total Size of processes\n";

foreach $key (sort sizehashValueDescendingNum (keys(%size))) {
    $count++;
    next if ($count > $max_top);
    if ($total{$key} != 0) {
        printf("%s %dM (~%.2dM per)\n", $key, $size{$key}, ($size{$key} / $total{$key})); }
    else {
        printf("%s %dM\n", $key, $size{$key}); } }

$count = 0;
print "\nLongest Running non-fastcgi processes\n";
foreach $key (sort timehashValueDescendingNum (keys(%process_time))) {
    $count++;
    next if ($count > $time_top);
    printf("%s\n", join (' /home',split ('/home',$key)), $process_time{$key}); } # Adds space between BIN/PHP5[4] and /HOME[x] to make highlighting file for review easier.

#===========================
# Subroutines below here
#===========================

sub elapsed_seconds {
    my ($string) = @_;
    my $running_total = 0;

    if ($string =~ "-") { # this has been running more than 24 hours!!
        my ($tmp,$remainder) = split (/-/,$string);
        $running_total = 24 * 60 * 60 * $tmp;
        $string = $remainder; }
    my @tmp = split(/:/, $string);
    my $val = pop(@tmp);      # first is seconds
    $running_total += $val;
    if ($tmp[0]) { # Been running minutes
        $val = pop(@tmp);
        $running_total += ($val * 60); }
    if ($tmp[0]) { # Been running hours
        $val = pop(@tmp);
        $running_total += ($val * 60 * 60); }
    return $running_total; }

sub totalhashValueDescendingNum {
   $total{$b} <=> $total{$a}; }

sub timehashValueDescendingNum {
   $process_time{$b} <=> $process_time{$a}; }

sub sizehashValueDescendingNum {
   $size{$b} <=> $size{$a}; }

sub get_command {
    my ($cmd) = @_;
    if ($cmd eq "") {
        die "get_command called with no command"; }
    @output = ();
    $errmsg = "";
    $return = 0;
    $count = 1;
    open CMD, "($cmd | sed 's/^/STDOUT:/') 2>&1 |";
    while (<CMD>) {
        chomp $_;
        if (s/^STDOUT://)  {
            push @output, $_; }
        else {
            $errmsg = $_;
            $return = 1; }
        $count++; }
    close CMD;
    return $return; }
