throttle.module 15 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
Dries's avatar
 
Dries committed
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/*  Call the throttle_status() function from your own modules, themes, blocks,
 * etc, to determine the current throttle status.  For example, in your theme
 * you might choose to disable pictures when your site is too busy (reducing
 * bandwidth), or in your modules you might choose to disable some complicated
 * logic when your site is too busy (reducing CPU utilization).
 *  To determine the current throttle level from your own php code, you can add
 * the following line:
 *    $throttle_level = module_invoke("throttle", "status");
 *  This will return a number from 0 to 5.  0 meaning that the current load is
 * very small, 5 meaning that the current load is as heavy as it gets.  You
 * should consider disabling logic when the throttle_level gets to 4 or 5.
 */
function throttle_status() {
  if (variable_get("throttle_enable", 0)) {
    return variable_get("throttle_level", 0);
  }
  else {
    return 0;
  }
}


function throttle_exit() {
  /*
  ** The following logic determines what the current throttle level should
  **  be, and can be disabled by the admin.  If enabled, the rand() function
  **  returns a number between 0 and N, N being specified by the admin. If
  **  0 is returned, the throttle logic is run, adding on additional database
  **  query.  Otherwise, the following logic is skipped.  This mechanism is
  **  referred to in the admin page as the 'probability limiter', roughly
  **  limiting throttle related database calls to 1 in N.
  */
  if ((variable_get("throttle_enable", 0)) && (!rand(0, variable_get("throttle_probability_limiter", 9)))) {
    /*
    ** Note:  The rand() function is supported by PHP 3+.  However, prior to
    ** PHP 4.2.0 it needs to be seeded with a call to srand().  It is important
    ** that this only happens once, so this should be managed by the Drupal
    ** engine, not this module.  The Drupal engine should use phpversion() to
    ** detect and automatically seed pre-4.2.0 systems.
    */

    $throttle = throttle_status();
Dries's avatar
 
Dries committed
46 47 48 49
    $multiplier = variable_get("throttle_multiplier", 60);
    // count all hits in past sixty seconds
    $recent_activity = db_fetch_object(db_query("SELECT COUNT(timestamp) AS hits FROM {accesslog} WHERE timestamp >= %d", (time() - 60)));
    _throttle_update($recent_activity->hits);
Dries's avatar
 
Dries committed
50 51 52
  }
}

Dries's avatar
 
Dries committed
53 54 55
function throttle_perm() {
  /*
  ** throttle module defines the following permissions:
Dries's avatar
 
Dries committed
56
  **   access throttle block - see throttle statistics
Dries's avatar
 
Dries committed
57
  */
Dries's avatar
 
Dries committed
58
  return array("access throttle block");
Dries's avatar
 
Dries committed
59 60
}

Dries's avatar
 
Dries committed
61
function throttle_help($section = "admin/help#throttle") {
Dries's avatar
 
Dries committed
62

Dries's avatar
 
Dries committed
63
  switch ($section) {
Dries's avatar
 
Dries committed
64
    case "admin/system/modules#description":
Dries's avatar
 
Dries committed
65
      $output = t("Allows configuration of congestion control auto-throttle mechanism.");
Dries's avatar
 
Dries committed
66 67
      break;
    case "admin/system/modules/throttle":
68
      return t("If your site gets linked to by a popular website, or otherwise comes under a \"Denial of Service\" (DoS) attack, your webserver might become overwhelmed.  This module provides a mechanism for automatically detecting a surge in incoming traffic.  This mechanism is utilized by other Drupal models to automatically optimize their performance by temporarily disabling CPU-intensive functionality.  To use the auto-throttle, the access log must be enabled.  It is advised that you carefully read the explainations below and then properly tune this module based on your site's requirements and your webserver's capabilities.", array("%access" => url("admin/system/modules/statistics")));
Dries's avatar
 
Dries committed
69
    case "admin/help#throttle":
70 71
      $output .= "<h3>Introduction</h3><p>This Drupal module allows you to enable and configure the auto-throttle congestion control mechanism offered by the <a href=\"%statistics-module\">statistics module</a>.  The auto-throttle mechanism allows your site to automatically adapt to different server levels.</p>";
      $output .= "<p>This module also adds a block that displays the current status of the throttle.  You must have \"<a href=\"%throttle-block\">access throttle block</a>\" privileges to view the block.  As a general rule of thumb, only site administrators should be granted access to this block.</p>";
Dries's avatar
 
Dries committed
72
      $output .= "<p>The auto-throttle mechanism performs an extra database query in order to determine what the current throttle level should be.  Fortunately the throttle can be tuned so these database queries only occur on a fraction of all pages generated by your site, reducing the overhead to an insignificant amount.  Additionally, when the top-most throttle level is reached, all throttle queries are suspended for a configurable period of time.  More detail follows.</p>";
73 74 75
      $output .= "<p>As with any module, the throttle module needs to be <a href=\"%modules-enable\">enabled</a> before you can use it.  Also refer to the permissions section below if you wish to access the throttle statistics block.</p>";
      $output .= "<h3>Configuring the throttle module</h3><p>The <a href=\"%throttle-config\">configuration section</a> for the throttle allows you to turn it on and off, as well as to fine-tune how sensitive it is.</p>";
      $output .= "<h4>enable auto-throttle:</h4><blockquote>This first option on the throttle module configuration screen allows you to enable or disable the auto-throttling mechanism.  Note that the access-log must also be enabled via the <a href=\"%statistics-config\">statistics module</a> for the auto-throttling mechanism to have any effect.</blockquote>";
Dries's avatar
 
Dries committed
76
      $output .= "<h4>auto-throttle multiplier:</h4><blockquote><p>This second option allows you to tune the auto-throttle mechanism.  The auto-throttle mechanism supports six throttle levels, from 0 (off) to 5 (maximum).  The current throttle level is based upon how many pages have been accessed on your site in the past 60 seconds - the more pages being displayed, the higher the throttle level.  This multiplier defines how many hits are required to switch from one throttle level to the next.</p>";
Dries's avatar
 
Dries committed
77
      $output .= "<p>For example, with a throttle multiplier of 20:  Once 20 pages have been accessed on your site within a period of 60 seconds, the throttle level will be incremented to a level of 1.  Once 40 pages have been accessed on your site within a period of 60 seconds, the throttle level will be incremented to a level of 2.  And so on, until 100 pages are accessed on your site within a period of 60 seconds, at which time the throttle level will be set to a maximum level of 5.</p></blockquote>";
Dries's avatar
 
Dries committed
78 79
      $output .= "<h4>auto-throttle probability limiter:</h4><blockquote><p>This option allows you to minimize the performance impact of the auto-throttle.  If we refer to the probability limiter as P, then P% of all pages generated by your site will perform an extra database query to verify that the current throttle level is appropriate to the current server load.</p>";
      $output .= "<p>As a rule of thumb, the higher your multiplier, the lower your probability limiter should be.  For example, if you have a multiplier of 100, then you logically don't need to check the throttle level more than once out of every 100 page views, so the probability limiter should be set to 1%.  As database queries are \"expensive\", it's recommended that you keep the probability limiter to the smallest percentage possible, while still high enough to react quickly to a change in server load.</p></blockquote>";
80 81 82
      $output .= "<h3>Throttle block</h3><p>This block displays some statistics regarding the current throttle and its configuration.  It is recommended that only site administrators receive the \"<a href=\"%throttle-access\">access throttle block</a>\" permission bit required to view this block.  It does not display information that would interest a normal site end-user.</p>";
      $output .= "<p>Don't forget to <a href=\"%throttle-block-enable\">enable the block</a>.</p>";
      $output .= "<h3>Permissions</h3><p>This module has one permission that needs to be configured in <a href=\"%permissions\">user permissions</a>.</p>";
Dries's avatar
 
Dries committed
83 84 85
      $output .= "<ul><li><i>access throttle block</i> - enable for user roles that get to view the throttle block.</li></ul>";
      $output .= "<h3>For programmers: throttle_status()</h3><p>The function <code>throttle_status()</code> will return a number from 0 to 5.  0 means that there is no throttle enabled at this time.  Each number above that is a progressively more throttled system...  To disable a feature when a site first begins to get busy, disable it at a throttle of 2 or 3.  To hold on to the bitter end, wait until 4 or 5.</p>";
      $output .= "<p>To implement the throttle, you should do something like this:";
86 87 88
      $output .= "<pre>
       if (module_invoke(\"throttle\", \"status\") >= \$my_throttle_value) {
          // my throttle limit was reached, disable stuff
Dries's avatar
 
Dries committed
89 90 91 92
        }
        else {
          // throttle limit not reached, execute normally
       }</pre></p>";
93
    $output = t($output, array("%statistics-module" => url("admin/statistics"), "%throttle-block" => url("admin/user/permission"), "%modules-enable" => url("admin/system/modules"), "%throttle-config" => url("admin/system/modules/throttle"), "%statistics-config" => url("admin/system/modules/statistics"), "%throttle-access" => url("admin/user/permission"), "%throttle-block-enable" => url("admin/block"), "%permissions" => url("admin/user/permission")));
Dries's avatar
 
Dries committed
94 95
    break;
  }
Dries's avatar
 
Dries committed
96

Dries's avatar
 
Dries committed
97
  return $output;
Dries's avatar
 
Dries committed
98 99 100
}


Dries's avatar
 
Dries committed
101
// throttle module configuration options
102
function throttle_settings() {
Dries's avatar
 
Dries committed
103
  // enable/disable auto-throttle
104
  $group = form_radios(t("Enable auto-throttle"), "throttle_enable", variable_get("throttle_enable", 0), array("1" => t("enabled"), "0" => t("disabled")), t("Enable auto-throttling congestion control mechanism.  Allows your site to adapt under extreme user loads, such as being linked by Slashdot.  To use the auto-throttle you must also enable the '<a href=\"%access_log\">access log</a>' from the statistics module.", array("%access_log" => url("admin/system/modules/statistics"))));
105
  $output = form_group(t("Auto-throttle status"), $group);
Dries's avatar
 
Dries committed
106 107

  // tune auto-throttle
Dries's avatar
 
Dries committed
108
  $throttles = array(1 => "1 (0,1,2,3,4,5)", 5 => "5 (0,5,10,15,20,25)", 10 => "10 (0,10,20,30,40,50)", 12 => "12 (0,12,24,36,48,60)", 15 => "15 (0,15,30,45,60,75)", 20 => "20 (0,20,40,60,80,100)", 30 => "30 (0,30,60,90,120,150)", 50 => "50 (0,50,100,150,200,250)", 60 => "60 (0,60,120,180,240,300)", 100 => "100 (0,100,200,300,400,500", 500 => "500 (0,500,1000,1500,2000,2500", 1000 => "1000 (0,1000,2000,3000,4000,5000)");
109
  $group = form_select(t("Auto-throttle multiplier"), "throttle_multiplier", variable_get("throttle_multiplier", 60), $throttles, "The 'auto-throttle multiplier' is the number of hits in the past 60 seconds required to trigger a higher throttle level.  For example, if you set the multiplier to 60, and your site is getting less than 60 hits a minute, then the throttle will be at a level of 0.  Only once you start getting more than 60 hits a minute will the throttle level go to 1.  If you start getting more than 120 hits a minute, the throttle becomes 2.  This continues until your site is sustaining more than 300 hits per minute, at which time the throttle reaches a maximum level of 5.  In the pop down menu, the first number is the multiplier, and the numbers in parenthesis are how many hits are required to switch to each throttle level.  The more powerful your server, the higher you should set the multiplier value.");
Dries's avatar
 
Dries committed
110
  $probabilities = array(0 => "100%", 1 => "50%", 2 => "33.3%", 3 => "25%", 4 => "20%", 5 => "16.6%", 7 => "12.5%", 9 => "10%", 19 => "5%", 99 => "1%", 199 => ".5%", 399 => ".25%", 989 => ".1%");
111
  $group .= form_select(t("Auto-throttle probability limiter"), "throttle_probability_limiter", variable_get("throttle_probability_limiter", 9), $probabilities, "The auto-throttle probability limiter is an efficiency mechanism to statistically reduce the overhead of the auto-throttle.  The limiter is expressed as a percentage of page views, so for example if set to the default of 10% we only perform the extra database query to update the current level 1 out of every 10 page views.  The busier your site, the lower you should set the limiter value.");
Dries's avatar
 
Dries committed
112
  $period = array(1800 => format_interval(1800), 3600 => format_interval(3600), 7200 => format_interval(7200), 10800 => format_interval(10800), 14400 => format_interval(14400), 18000 => format_interval(18000), 21600 => format_interval(21600), 43200 => format_interval(43200), 64800 => format_interval(64800), 86400 => format_interval(86400), 172800 => format_interval(172800), 259200 => format_interval(259200), 604800 => format_interval(604800));
Dries's avatar
 
Dries committed
113 114
  $output .= form_group(t("Auto-throttle tuning"), $group);

Dries's avatar
 
Dries committed
115 116 117
  return $output;
}

Dries's avatar
 
Dries committed
118
// displays admin oriented "Throttle status" block
Dries's avatar
 
Dries committed
119 120
function throttle_display_throttle_block() {
  if (user_access("access throttle block")) {
121
    if (variable_get("throttle_enable", 0)) {
Dries's avatar
 
Dries committed
122
      /* the throttle is enabled:  display the status of all throttle config */
123 124
      $throttle = module_invoke("throttle", "status");
      $multiplier = variable_get("throttle_multiplier", 60);
Dries's avatar
 
Dries committed
125
      $minimum = $throttle * $multiplier;
126
      $limiter = variable_get("throttle_probability_limiter", 9);
Dries's avatar
 
Dries committed
127 128 129 130 131
      /* calculate probability limiter's odds of updating throttle */
      $probability = substr((($limiter / ($limiter + 1) * 100) - 100) * -1, 0, 4);

      if ($throttle < 5) {
        $maximum = (($throttle + 1) * $multiplier) - 1;
Dries's avatar
 
Dries committed
132
        $output .= t("Current level: %level (%min - %max)", array("%level" => $throttle, "%min" => $minimum, "%max" => $maximum)) ."<br />\n";
Dries's avatar
 
Dries committed
133 134
      }
      else {
Dries's avatar
 
Dries committed
135
        $output .= t("Current level: %level (%min+)", array("%level" => $throttle, "%min" => $minimum)) ."<br />\n";
Dries's avatar
 
Dries committed
136
      }
Dries's avatar
 
Dries committed
137
      $output .= t("Probability: %probability%", array("%probability" => $probability)) ."<br />\n";
Dries's avatar
 
Dries committed
138 139 140 141 142
      if ($throttle < 5) {
        $recent_activity = db_fetch_object(db_query("SELECT COUNT(timestamp) AS hits FROM {accesslog} WHERE timestamp >= %d", (time() - 60)));
        $output .= "<br />". t("This site has served %pages in the past minute.", array("%pages" => format_plural($recent_activity->hits , "1 page", "%count pages")));
        _throttle_update($recent_activity->hits);
      }
Dries's avatar
 
Dries committed
143 144
    }
    else {
145
      $output .= t("Throttle: <a href=\"%status\">disabled</a>", array("%status" => url("admin/system/modules/throttle"))) ."<br />\n";
Dries's avatar
 
Dries committed
146 147 148 149 150
    }
  }
  return $output;
}

Dries's avatar
 
Dries committed
151
// block hook
Dries's avatar
 
Dries committed
152 153 154 155 156 157 158 159 160 161
function throttle_block($op = "list", $delta = 0) {
  if ($op == "list") {
    $blocks[0]["info"] = t("Throttle status");
    return $blocks;
  }
  else {
    $block["subject"] = t("Throttle status");
    $block["content"] = throttle_display_throttle_block();
    return $block;
  }
Dries's avatar
 
Dries committed
162 163
}

Dries's avatar
 
Dries committed
164 165 166 167 168
function _throttle_update($hits) {
  $throttle = throttle_status();
  $multiplier = variable_get("throttle_multiplier", 60);

  for ($i = 0; $i <= 5; $i++) {
Dries's avatar
 
Dries committed
169
    if ($i * $multiplier <= $hits) {
Dries's avatar
 
Dries committed
170 171 172 173
      $throttle_new = $i;
    }
  }

Dries's avatar
 
Dries committed
174 175 176 177 178 179 180 181
  // log the change
  if ($throttle_new < $throttle) {
    variable_set("throttle_level", $throttle - 1);
    watchdog("regular", "message: '". $hits ."' hits in past minute; throttle decreased to level ". $throttle_new);
  }
  if ($throttle_new > $throttle) {
    variable_set("throttle_level", $throttle + 1);
    watchdog("warning", "warning: '". $hits ."' hits in past minute; throttle increased to level ". $throttle_new);
Dries's avatar
 
Dries committed
182 183 184
  }
}

Dries's avatar
 
Dries committed
185
?>