Skip to content

Instantly share code, notes, and snippets.

@abiusx
Created April 9, 2020 16:28
Show Gist options
  • Save abiusx/c7299d6ef1353b115f52dcba4fabf9fb to your computer and use it in GitHub Desktop.
Save abiusx/c7299d6ef1353b115f52dcba4fabf9fb to your computer and use it in GitHub Desktop.
Shows usage by user for php-fpm process pool. Useful for shared hosting monitoring of hacked or abusive users.
#!/usr/bin/env php
<?php
$sample_count=$argv[1]??1;
$sleep=$argv[2]??100;
$sleep*=1000;
$users=[];
for ($i=0;$i<$sample_count;++$i)
{
$res=sample();
foreach ($res as $data)
{
@$users[$data->user]->cpu+=$data->cpu;
@$users[$data->user]->ram+=$data->ram;
@$users[$data->user]->count++;
}
usleep($sleep);
}
uasort($users, function($x,$y) { return $x->cpu<$y->cpu;});
$format="%-20s%-10s\t%-10s\t%-10s\n";
printf($format, "USER","CPU","RAM","PROCESSES");
echo str_repeat("-",80), PHP_EOL;
foreach ($users as $username=>$u)
{
printf($format,
$username, sprintf("%.1f%%",$u->cpu/$sample_count),
sprintf("%.1f%%",$u->ram/$sample_count), $u->count/$sample_count
);
}
function sample()
{
$res=shell_exec("ps aux | grep 'php-fp[m]: pool'");
$res=explode("\n",$res);
$out=[];
foreach ($res as $r)
{
$t=explode(" ", $r);
$t=array_values(array_filter($t));
if (count($t)<10) continue;
$cpu=$t[2];
$ram=$t[3];
$user=$t[12];
$out[]=(object)compact('cpu','ram','user');
}
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment