initial import from onelab svn codebase
[plewww.git] / modules / throttle.module
1 <?php
2 // $Id: throttle.module 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Allows configuration of congestion control auto-throttle mechanism.
7  */
8
9 /**
10  * Determine the current load on the site.
11  *
12  * Call the throttle_status() function from your own modules, themes, blocks,
13  * etc. to determine the current throttle status. For example, in your theme
14  * you might choose to disable pictures when your site is too busy (reducing
15  * bandwidth), or in your modules you might choose to disable some complicated
16  * logic when your site is too busy (reducing CPU utilization).
17  *
18  * @return
19  *   0 or 1.  0 means that the throttle is currently disabled.  1 means that
20  *   the throttle is currently enabled.  When the throttle is enabled, CPU
21  *   and bandwidth intensive functionality should be disabled.
22  */
23 function throttle_status() {
24   return variable_get('throttle_level', 0);
25 }
26
27 /**
28  * Implementation of hook_exit().
29  *
30  * Changes the current throttle level based on page hits.
31  */
32 function throttle_exit() {
33   // The following logic determines what the current throttle level should
34   //  be, and can be disabled by the admin.  If enabled, the mt_rand() function
35   //  returns a number between 0 and N, N being specified by the admin. If
36   //  0 is returned, the throttle logic is run, adding two additional database
37   //  queries.  Otherwise, the following logic is skipped.  This mechanism is
38   //  referred to in the admin page as the 'probability limiter', roughly
39   //  limiting throttle related database calls to 1 in N.
40   if (!mt_rand(0, variable_get('throttle_probability_limiter', 9))) {
41
42     // Count users with activity in the past n seconds, defined in user module
43     $time_period = variable_get('user_block_seconds_online', 2700);
44
45     $throttle = module_invoke('throttle', 'status');
46
47     if ($max_guests = variable_get('throttle_anonymous', 0)) {
48       $guests = db_result(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d AND uid = 0', time() - $time_period));
49     }
50     else {
51       $guests = 0;
52     }
53     if ($max_users = variable_get('throttle_user', 0)) {
54       $users = db_result(db_query('SELECT COUNT(DISTINCT(uid)) AS count FROM {sessions} WHERE timestamp >= %d AND uid != 0', time() - $time_period));
55     }
56     else {
57       $users = 0;
58     }
59
60     // update the throttle status
61     $message = '';
62     if ($max_users && $users > $max_users) {
63       if (!$throttle) {
64         variable_set('throttle_level', 1);
65         $message = format_plural($users,
66                                  '1 user accessing site; throttle enabled.',
67                                  '%count users accessing site; throttle enabled.');
68       }
69     }
70     elseif ($max_guests && $guests > $max_guests) {
71       if (!$throttle) {
72         variable_set('throttle_level', 1);
73         $message = format_plural($guests,
74                                  '1 guest accessing site; throttle enabled.',
75                                  '%count guests accessing site; throttle enabled.');
76       }
77     }
78     else {
79       if ($throttle) {
80         variable_set('throttle_level', 0);
81         // Note: unorthodox format_plural() usage due to Gettext plural limitations.
82         $message = format_plural($users, '1 user', '%count users') .', ';
83         $message .= format_plural($guests, '1 guest accessing site; throttle disabled', '%count guests accessing site; throttle disabled');
84       }
85     }
86     if ($message) {
87       cache_clear_all();
88       watchdog('throttle', t('Throttle') .': '. $message);
89     }
90   }
91 }
92
93 function _throttle_validate($value, $form) {
94   if ($value != NULL) {
95     if (!is_numeric($value) || $value < 0) {
96       form_set_error($form, t("'%value' is not a valid auto-throttle setting.  Please enter a positive numeric value.", array('%value' => theme('placeholder', $value))));
97     }
98   }
99 }
100
101 /**
102  * Implementation of hook_help().
103  */
104 function throttle_help($section) {
105   switch ($section) {
106     case 'admin/help#throttle':
107       $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>';
108       $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>';
109       $output .= t('<p>You can</p>
110 <ul>
111 <li>enable throttle for modules at <a href="%admin-modules">administer &gt;&gt; module</a>.</li>
112 <li>enable throttle for blocks at <a href="%admin-block">administer &gt;&gt; block</a>.</li>
113 <li>administer throttle at <a href="%admin-settings-throttle">administer &gt;&gt; settings &gt;&gt; throttle</a>.</li>
114 </ul>
115 ', array('%admin-modules' => url('admin/modules'), '%admin-block' => url('admin/block'), '%admin-settings-throttle' => url('admin/settings/throttle')));
116       $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>';
117       return $output;
118     case 'admin/modules#description':
119       return t('Handles the auto-throttling mechanism, to control site congestion.');
120     case 'admin/settings/throttle':
121       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.');
122   }
123 }
124
125 /**
126  * Implementation of hook_settings().
127  */
128 function throttle_settings() {
129   _throttle_validate(variable_get('throttle_anonymous', ''), 'throttle_anonymous');
130   _throttle_validate(variable_get('throttle_user', ''), 'throttle_user');
131   $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%');
132
133   $form['throttle_anonymous'] = array(
134     '#type' => 'textfield',
135     '#title' => t('Auto-throttle on anonymous users'),
136     '#default_value' => variable_get('throttle_anonymous', 0),
137     '#size' => 5,
138     '#maxlength' => 6,
139     '#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.')
140   );
141   $form['throttle_user'] = array(
142     '#type' => 'textfield',
143     '#title' => t('Auto-throttle on authenticated users'),
144     '#default_value' => variable_get('throttle_user', 0),
145     '#size' => 5,
146     '#maxlength' => 6,
147     '#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.')
148   );
149   $form['throttle_probability_limiter'] = array(
150     '#type' => 'select',
151     '#title' => t('Auto-throttle probability limiter'),
152     '#default_value' => variable_get('throttle_probability_limiter', 9),
153     '#options' => $probabilities,
154     '#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.')
155   );
156
157   return $form;
158 }