SHARE
TWEET

loadwatcher.php

btmash Aug 18th, 2011 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. define ("LOAD_AVERAGE_THRESHOLD", 10.0);
  4. define ("APACHE_RESTART_THRESHOLD", 60 * 30);
  5. define ("DEFAULT_LOAD_AVERAGE_PATH", "/proc/loadavg");
  6. define ("APACHE_COMMAND_STOP", '/etc/init.d/apache2 stop');
  7. define ("APACHE_COMMAND_START", '/etc/init.d/apache2 start');
  8. define ("APACHE_COMMAND_RESTART", '/etc/init.d/apache2 restart');
  9. define ("APACHE_COMMAND_STATUS", '/etc/init.d/apache2 status');
  10.  
  11. function get_current_load_average() {
  12.   $load_average_file_name = DEFAULT_LOAD_AVERAGE_PATH;
  13.   $fp = @fopen($load_average_file_name, 'r');
  14.   if ($fp == null) {
  15.     die("unable to open file at $load_average_file_name\n");
  16.   }
  17.   $load_averages = explode(" ", fread($fp, 4096));
  18.   return floatval($load_averages[0]);
  19. }
  20.  
  21. function restart_apache_server() {
  22.   // Do some stuff in here!
  23.   printf ("Server might be going through problems...restart the web server now!\n");
  24.   system(APACHE_COMMAND_STOP);
  25.   printf ("Stopped web server");
  26.   sleep(10);
  27.   system(APACHE_COMMAND_START);
  28.   printf ("Started web server");
  29. }
  30.  
  31. $allowed_restart_time = time();
  32.  
  33. while (1) {
  34.   $current_load_average = get_current_load_average();
  35.   printf("Current load - %f\n", $current_load_average);
  36.   if ($current_load_average < LOAD_AVERAGE_THRESHOLD) {
  37.     printf ("Server is doing pretty well!\n");
  38.   }
  39.   else if ($current_load_average >= LOAD_AVERAGE_THRESHOLD && time() > $allowed_restart_time) {
  40.     restart_apache_server();
  41.     $allowed_restart_time = time() + APACHE_RESTART_THRESHOLD;
  42.   }
  43.   else {
  44.     printf ("Wait for some time to ensure server is getting back to normal.\n");
  45.   }
  46.   sleep(30);
  47. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top