Skip to content

Instantly share code, notes, and snippets.

@buttjer
Last active September 20, 2016 10:33
Show Gist options
  • Save buttjer/4710cdb8057749b616ddd78098e3825a to your computer and use it in GitHub Desktop.
Save buttjer/4710cdb8057749b616ddd78098e3825a to your computer and use it in GitHub Desktop.
/*
This script uses the sys_getloadavg() function
to lock out some visitors in cases of extreme load.
$threads defines the maximum avaialable count of php threads
to aproximate a representation of the stresslevel.
A good value is the number of cpu threads available to php.
by malte buttjer
buttjer.net
*/
<?
class Loadcheck {
static private $threads;
static public function start( $threads = 12 ) {
self::$threads = $threads;
if( self::test() ) return;
http_response_code( 503 );
die();
}
static private function test() {
if ( self::isVIRoute() ) return TRUE;
if ( self::isDenied() ) return FALSE;
if ( self::isStressed() ) return FALSE;
return TRUE;
}
static private function isDenied() {
return isset( $_COOKIE['denied'] );
}
static private function isVIRoute() {
$routes = ['cart/placeorder']; //Very important payment routes
return in_array( $_SERVER['REQUEST_URI'], $routes );
}
static private function isStressed() {
$stressLevel = self::getStressLevel( self::$threads );
// $_COOKIE['cartSessionCookie'] is the session cookie of the cart.
// Customers with an active cart arent locked out in the first place
if ( $stressLevel === 1 && !isset( $_COOKIE['cartSessionCookie'] ) ) {
setcookie('denied', 'denied', time()+3*60); //lock for 3min
return TRUE;
}
if ( $stressLevel === 2 && !isset( $_COOKIE['cartSessionCookie'] ) ) {
setcookie('denied', 'denied', time()+5*60); //lock for 5min
return TRUE;
}
if ( $stressLevel === 2 ) {
setcookie('denied', 'denied', time()+60); //lock for 1min
return TRUE;
}
return FALSE;
}
static private function getStressLevel( $threads ) {
$load = sys_getloadavg();
if ( $load[0] > $threads * 0.95 ) return 2; //EXTREME
if ( $load[0] > $threads * 0.8 ) return 1; //VERY
return 0; //CHILLED
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment