summaryrefslogtreecommitdiff
path: root/modules/throttle.module
blob: 18226523d9b2178f16d624d3a1a8ab9ae4742aa8 (plain)
1
2
3
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php
// $Id$

/**
 * @file
 * Allows configuration of congestion control auto-throttle mechanism.
 */

/**
 * Determine the current load on the site.
 *
 * 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).
 *
 * @return
 *   0 or 1.  0 means that the throttle is currently disabled.  1 means that
 *   the throttle is currently enabled.  When the throttle is enabled, CPU
 *   and bandwidth intensive functionality should be disabled.
 */
function throttle_status() {
  return variable_get('throttle_level', 0);
}

/**
 * Implementation of hook_exit().
 *
 * Changes the current throttle level based on page hits.
 */
function throttle_exit() {
  // The following logic determines what the current throttle level should
  //  be, and can be disabled by the admin.  If enabled, the mt_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 two additional database
  //  queries.  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 (!mt_rand(0, variable_get('throttle_probability_limiter', 9))) {

    // Count users with activity in the past n seconds, defined in user module
    $time_period = variable_get('user_block_seconds_online', 2700);

    $throttle = module_invoke('throttle', 'status');

    if ($max_guests = variable_get('throttle_anonymous', 0)) {
      $guests = db_result(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d AND uid = 0', time() - $time_period));
    }
    else {
      $guests = 0;
    }
    if ($max_users = variable_get('throttle_user', 0)) {
      $users = db_result(db_query('SELECT COUNT(DISTINCT(uid)) AS count FROM {sessions} WHERE timestamp >= %d AND uid != 0', time() - $time_period));
    }
    else {
      $users = 0;
    }

    // update the throttle status
    $message = '';
    if ($max_users && $users > $max_users) {
      if (!$throttle) {
        variable_set('throttle_level', 1);
        $message = format_plural($users,
                                 '1 user accessing site; throttle enabled.',
                                 '%count users accessing site; throttle enabled.');
      }
    }
    elseif ($max_guests && $guests > $max_guests) {
      if (!$throttle) {
        variable_set('throttle_level', 1);
        $message = format_plural($guests,
                                 '1 guest accessing site; throttle enabled.',
                                 '%count guests accessing site; throttle enabled.');
      }
    }
    else {
      if ($throttle) {
        variable_set('throttle_level', 0);
        // Note: unorthodox format_plural() usage due to Gettext plural limitations.
        $message = format_plural($users, '1 user', '%count users') .', ';
        $message .= format_plural($guests, '1 guest accessing site; throttle disabled', '%count guests accessing site; throttle disabled');
      }
    }
    if ($message) {
      cache_clear_all();
      watchdog('throttle', t('Throttle') .': '. $message);
    }
  }
}

function _throttle_validate($value, $form) {
  if ($value != NULL) {
    if (!is_numeric($value) || $value < 0) {
      form_set_error($form, t("'%value' is not a valid auto-throttle setting.  Please enter a positive numeric value.", array('%value' => theme('placeholder', $value))));
    }
  }
}

/**
 * Implementation of hook_help().
 */
function throttle_help($section) {
  switch ($section) {
    case 'admin/help#throttle':
      $output = '<p>'. t('The throttle module provides a congestion control throttling mechanism for automatically detecting a surge in incoming traffic. If the site gets linked to by a popular website, or otherwise comes under a "Denial of Service" (DoS) attack, your webserver might become overwhelmed. This mechanism is utilized by other modules to automatically optimize their performance by temporarily disabling CPU-intensive functionality.  For example, in the site theme, you might choose to disable pictures when the site is too busy (reducing bandwidth), or in modules, you might choose to disable some complicated logic (reducing CPU utilization).') .'</p>';
      $output .= '<p>'. t('The congestion control throttle can be automatically enabled when the number of anonymous or authenticated users currently visiting the site exceeds the specified threshold. ') .'</p>';
      $output .= t('<p>You can</p>
<ul>
<li>enable throttle for modules at <a href="%admin-modules">administer &gt;&gt; module</a>.</li>
<li>enable throttle for blocks at <a href="%admin-block">administer &gt;&gt; block</a>.</li>
<li>administer throttle at <a href="%admin-settings-throttle">administer &gt;&gt; settings &gt;&gt; throttle</a>.</li>
</ul>
', array('%admin-modules' => url('admin/modules'), '%admin-block' => url('admin/block'), '%admin-settings-throttle' => url('admin/settings/throttle')));
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%throttle">Throttle page</a>.', array('%throttle' => 'http://drupal.org/handbook/modules/throttle/')) .'</p>';
      return $output;
    case 'admin/modules#description':
      return t('Handles the auto-throttling mechanism, to control site congestion.');
    case 'admin/settings/throttle':
      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 congestion control throttling mechanism for automatically detecting a surge in incoming traffic.  This mechanism is utilized by other Drupal modules to automatically optimize their performance by temporarily disabling CPU-intensive functionality.');
  }
}

/**
 * Implementation of hook_settings().
 */
function throttle_settings() {
  _throttle_validate(variable_get('throttle_anonymous', ''), 'throttle_anonymous');
  _throttle_validate(variable_get('throttle_user', ''), 'throttle_user');
  $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%');

  $form['throttle_anonymous'] = array(
    '#type' => 'textfield',
    '#title' => t('Auto-throttle on anonymous users'),
    '#default_value' => variable_get('throttle_anonymous', 0),
    '#size' => 5,
    '#maxlength' => 6,
    '#description' => t('The congestion control throttle can be automatically enabled when the number of anonymous users currently visiting your site exceeds the specified threshold.  For example, to start the throttle when your site has 250 anonymous users online at once, enter \'250\' in this field. Leave this value blank or set to "0" if you do not wish to auto-throttle on anonymous users.  You can inspect the current number of anonymous users using the "Who\'s online" block.')
  );
  $form['throttle_user'] = array(
    '#type' => 'textfield',
    '#title' => t('Auto-throttle on authenticated users'),
    '#default_value' => variable_get('throttle_user', 0),
    '#size' => 5,
    '#maxlength' => 6,
    '#description' => t('The congestion control throttle can be automatically enabled when the number of authenticated users currently visiting your site exceeds the specified threshold.  For example, to start the throttle when your site has 50 registered users online at once, enter \'50\' in this field. Leave this value blank or set to "0" if you do not wish to auto-throttle on authenticated users.  You can inspect the current number of authenticated users using the "Who\'s online" block.')
  );
  $form['throttle_probability_limiter'] = array(
    '#type' => 'select',
    '#title' => t('Auto-throttle probability limiter'),
    '#default_value' => variable_get('throttle_probability_limiter', 9),
    '#options' => $probabilities,
    '#description' => t('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 queries to update the throttle status 1 out of every 10 page views.  The busier your site, the lower you should set the limiter value.')
  );

  return $form;
}