Skip to content

Instantly share code, notes, and snippets.

@erm3nda
Last active November 27, 2015 04:52
Show Gist options
  • Save erm3nda/2219a0de87482da7337d to your computer and use it in GitHub Desktop.
Save erm3nda/2219a0de87482da7337d to your computer and use it in GitHub Desktop.
Run some processes to show cpulimit work
<?php
/**
* PHP cpulimit daemon
*
* PHP cpulimit daemon checks for http calls with REQUEST_URI and limites those processes.
* This is related to https://github.com/opsengine/cpulimit/issues/40#issuecomment-73372492
* and http://www.tronko.es/servers/cpulimit-howto/
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to [email protected] so we can mail you a copy immediately.
*
* @category process control
* @package cpulimit-daemon-test
* @author erm3nda at google's mail
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @see https://github.com/opsengine/cpulimit/issues/40
* @requisites Download and compile https://github.com/opsengine/cpulimit
* @requisites Download pre-compiled Linux 64bit binary here http://s000.tinyupload.com/?file_id=33300278775241323639
*/
set_time_limit(5); // we ensure to stop the process to 5 seconds, like the refresh.
exec("curl -L http://someurl/file.php?param=1 > /dev/null 2>$1 &"); // put a bench i.e. http://www.php-benchmark-script.com/
$process = shell_exec("ps auxwwfe | grep QUERY_STRING | grep -v grep"); // get all pids that matchs a QUERY_STRING (http request)
preg_match_all("/.*\n/", $process, $matches); // group by new lines
$matches['data'] = $matches[0]; // regroup values
unset($matches[0]); // free last array
foreach ($matches['data'] as $m) { // process all our results
if (preg_match("/.*cpulimit.*/", $m) != true) { // skip the cpulimit processes
$first_token = strtok($m, ' '); // get the 1st word on a string
$matches['pid'][] = strtok(' '); // get next word on a previous set string ($first_token)
} else {
$first_token = strtok($m, ' '); // get the 1st word on a string
$matches['skiped'][] = strtok(' ');
}
}
foreach($matches['pid'] as $pid) { // limit those scripts by cpulimit
$close = shell_exec("/sbin/cpulimit -l 10 -p" . $pid . " -v > /dev/null 2>&1 &");
$matches['closed'][] = $pid;
}
echo "<pre>";
var_dump($matches); // watch it out
echo "</pre>";
echo "<meta http-equiv='refresh' content='5'>"; // refresh the page
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment