Update message initialiser to use Revision functions for backend-independence. No...
[lhc/web/wiklou.git] / includes / LoadBalancer.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 */
6
7 /**
8 * Depends on the database object
9 */
10 require_once( 'Database.php' );
11
12 # Valid database indexes
13 # Operation-based indexes
14 define( 'DB_SLAVE', -1 ); # Read from the slave (or only server)
15 define( 'DB_MASTER', -2 ); # Write to master (or only server)
16 define( 'DB_LAST', -3 ); # Whatever database was used last
17
18 # Obsolete aliases
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
21
22 # Task-based indexes
23 # ***NOT USED YET, EXPERIMENTAL***
24 # These may be defined in $wgDBservers. If they aren't, the default reader or writer will be used
25 # Even numbers are always readers, odd numbers are writers
26 define( 'DB_TASK_FIRST', 1000 ); # First in list
27 define( 'DB_SEARCH_R', 1000 ); # Search read
28 define( 'DB_SEARCH_W', 1001 ); # Search write
29 define( 'DB_ASKSQL_R', 1002 ); # Special:Asksql read
30 define( 'DB_WATCHLIST_R', 1004 ); # Watchlist read
31 define( 'DB_TASK_LAST', 1004) ; # Last in list
32
33 /**
34 * Database load balancing object
35 *
36 * @todo document
37 * @package MediaWiki
38 */
39 class LoadBalancer {
40 /* private */ var $mServers, $mConnections, $mLoads;
41 /* private */ var $mFailFunction;
42 /* private */ var $mForce, $mReadIndex, $mLastIndex;
43 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
44 /* private */ var $mLaggedSlaveMode;
45
46 function LoadBalancer()
47 {
48 $this->mServers = array();
49 $this->mConnections = array();
50 $this->mFailFunction = false;
51 $this->mReadIndex = -1;
52 $this->mForce = -1;
53 $this->mLastIndex = -1;
54 }
55
56 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
57 {
58 $lb = new LoadBalancer;
59 $lb->initialise( $servers, $failFunction = false );
60 return $lb;
61 }
62
63 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
64 {
65 $this->mServers = $servers;
66 $this->mFailFunction = $failFunction;
67 $this->mReadIndex = -1;
68 $this->mWriteIndex = -1;
69 $this->mForce = -1;
70 $this->mConnections = array();
71 $this->mLastIndex = 1;
72 $this->mLoads = array();
73 $this->mWaitForFile = false;
74 $this->mWaitForPos = false;
75 $this->mWaitTimeout = $waitTimeout;
76 $this->mLaggedSlaveMode = false;
77
78 foreach( $servers as $i => $server ) {
79 $this->mLoads[$i] = $server['load'];
80 }
81 }
82
83 /**
84 * Given an array of non-normalised probabilities, this function will select
85 * an element and return the appropriate key
86 */
87 function pickRandom( $weights )
88 {
89 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
90 return false;
91 }
92
93 $sum = 0;
94 foreach ( $weights as $w ) {
95 $sum += $w;
96 }
97 $max = mt_getrandmax();
98 $rand = mt_rand(0, $max) / $max * $sum;
99
100 $sum = 0;
101 foreach ( $weights as $i => $w ) {
102 $sum += $w;
103 if ( $sum >= $rand ) {
104 break;
105 }
106 }
107 return $i;
108 }
109
110 function getReaderIndex()
111 {
112 $fname = 'LoadBalancer::getReaderIndex';
113 wfProfileIn( $fname );
114
115 $i = false;
116 if ( $this->mForce >= 0 ) {
117 $i = $this->mForce;
118 } else {
119 if ( $this->mReadIndex >= 0 ) {
120 $i = $this->mReadIndex;
121 } else {
122 # $loads is $this->mLoads except with elements knocked out if they
123 # don't work
124 $loads = $this->mLoads;
125 do {
126 $i = $this->pickRandom( $loads );
127 if ( $i !== false ) {
128 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
129
130 $this->openConnection( $i );
131
132 if ( !$this->isOpen( $i ) ) {
133 unset( $loads[$i] );
134 }
135 }
136 } while ( $i !== false && !$this->isOpen( $i ) );
137
138 if ( $this->isOpen( $i ) ) {
139 $this->mReadIndex = $i;
140 } else {
141 $i = false;
142 }
143 }
144 }
145 wfProfileOut( $fname );
146 return $i;
147 }
148
149 /**
150 * Set the master wait position
151 * If a DB_SLAVE connection has been opened already, waits
152 * Otherwise sets a variable telling it to wait if such a connection is opened
153 */
154 function waitFor( $file, $pos ) {
155 $fname = 'LoadBalancer::waitFor';
156 wfProfileIn( $fname );
157
158 wfDebug( "User master pos: $file $pos\n" );
159 $this->mWaitForFile = false;
160 $this->mWaitForPos = false;
161
162 if ( count( $this->mServers ) > 1 ) {
163 $this->mWaitForFile = $file;
164 $this->mWaitForPos = $pos;
165
166 if ( $this->mReadIndex > 0 ) {
167 if ( !$this->doWait( $this->mReadIndex ) ) {
168 $this->mLaggedSlaveMode = true;
169 }
170 }
171 }
172 wfProfileOut( $fname );
173 }
174
175 /**
176 * Wait for a given slave to catch up to the master pos stored in $this
177 */
178 function doWait( $index ) {
179 global $wgMemc;
180
181 $retVal = false;
182
183 $key = 'masterpos:' . $index;
184 $memcPos = $wgMemc->get( $key );
185 if ( $memcPos ) {
186 list( $file, $pos ) = explode( ' ', $memcPos );
187 # If the saved position is later than the requested position, return now
188 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
189 $retVal = true;
190 }
191 }
192
193 if ( !$retVal && $this->isOpen( $index ) ) {
194 $conn =& $this->mConnections[$index];
195 wfDebug( "Waiting for slave #$index to catch up...\n" );
196 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
197
198 if ( $result == -1 || is_null( $result ) ) {
199 # Timed out waiting for slave, use master instead
200 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
201 $retVal = false;
202 } else {
203 $retVal = true;
204 wfDebug( "Done\n" );
205 }
206 }
207 return $retVal;
208 }
209
210 /**
211 * Get a connection by index
212 */
213 function &getConnection( $i, $fail = true )
214 {
215 $fname = 'LoadBalancer::getConnection';
216 wfProfileIn( $fname );
217 /*
218 # Task-based index
219 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
220 if ( $i % 2 ) {
221 # Odd index use writer
222 $i = DB_MASTER;
223 } else {
224 # Even index use reader
225 $i = DB_SLAVE;
226 }
227 }*/
228
229 # Operation-based index
230 if ( $i == DB_SLAVE ) {
231 $i = $this->getReaderIndex();
232 } elseif ( $i == DB_MASTER ) {
233 $i = $this->getWriterIndex();
234 } elseif ( $i == DB_LAST ) {
235 # Just use $this->mLastIndex, which should already be set
236 $i = $this->mLastIndex;
237 if ( $i === -1 ) {
238 # Oh dear, not set, best to use the writer for safety
239 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
240 $i = $this->getWriterIndex();
241 }
242 }
243 # Now we have an explicit index into the servers array
244 $this->openConnection( $i, $fail );
245 wfProfileOut( $fname );
246 return $this->mConnections[$i];
247 }
248
249 /**
250 * Open a connection to the server given by the specified index
251 * Index must be an actual index into the array
252 * @private
253 */
254 function openConnection( $i, $fail = false ) {
255 $fname = 'LoadBalancer::openConnection';
256 wfProfileIn( $fname );
257
258 if ( !$this->isOpen( $i ) ) {
259 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
260
261 if ( $i != 0 && $this->mWaitForFile ) {
262 if ( !$this->doWait( $i ) ) {
263 # Error waiting for this slave, use master instead
264 $this->mReadIndex = 0;
265 $i = 0;
266 if ( !$this->isOpen( 0 ) ) {
267 $this->mConnections[0] = $this->reallyOpenConnection( $this->mServers[0] );
268 }
269 wfDebug( "Failed over to {$this->mConnections[0]->mServer}\n" );
270 }
271 }
272 }
273 if ( !$this->isOpen( $i ) ) {
274 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
275 if ( $fail ) {
276 $this->reportConnectionError( $this->mConnections[$i] );
277 }
278 $this->mConnections[$i] = false;
279 }
280 $this->mLastIndex = $i;
281 wfProfileOut( $fname );
282 }
283
284 /**
285 * Test if the specified index represents an open connection
286 * @private
287 */
288 function isOpen( $index ) {
289 if( !is_integer( $index ) ) {
290 return false;
291 }
292 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
293 $this->mConnections[$index]->isOpen() )
294 {
295 return true;
296 } else {
297 return false;
298 }
299 }
300
301 /**
302 * Really opens a connection
303 * @private
304 */
305 function reallyOpenConnection( &$server ) {
306 if( !is_array( $server ) ) {
307 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
308 }
309
310 extract( $server );
311 # Get class for this database type
312 $class = 'Database' . ucfirst( $type );
313 if ( !class_exists( $class ) ) {
314 require_once( "$class.php" );
315 }
316
317 # Create object
318 return new $class( $host, $user, $password, $dbname, 1, $flags );
319 }
320
321 function reportConnectionError( &$conn )
322 {
323 $fname = 'LoadBalancer::reportConnectionError';
324 wfProfileIn( $fname );
325 # Prevent infinite recursion
326
327 static $reporting = false;
328 if ( !$reporting ) {
329 $reporting = true;
330 if ( !is_object( $conn ) ) {
331 $conn = new Database;
332 }
333 if ( $this->mFailFunction ) {
334 $conn->failFunction( $this->mFailFunction );
335 } else {
336 $conn->failFunction( 'wfEmergencyAbort' );
337 }
338 $conn->reportConnectionError();
339 $reporting = false;
340 }
341 wfProfileOut( $fname );
342 }
343
344 function getWriterIndex()
345 {
346 return 0;
347 }
348
349 function force( $i )
350 {
351 $this->mForce = $i;
352 }
353
354 function haveIndex( $i )
355 {
356 return array_key_exists( $i, $this->mServers );
357 }
358
359 /**
360 * Get the number of defined servers (not the number of open connections)
361 */
362 function getServerCount() {
363 return count( $this->mServers );
364 }
365
366 /**
367 * Save master pos to the session and to memcached, if the session exists
368 */
369 function saveMasterPos() {
370 global $wgSessionStarted;
371 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
372 # If this entire request was served from a slave without opening a connection to the
373 # master (however unlikely that may be), then we can fetch the position from the slave.
374 if ( empty( $this->mConnections[0] ) ) {
375 $conn =& $this->getConnection( DB_SLAVE );
376 list( $file, $pos ) = $conn->getSlavePos();
377 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
378 } else {
379 $conn =& $this->getConnection( 0 );
380 list( $file, $pos ) = $conn->getMasterPos();
381 wfDebug( "Saving master pos: $file $pos\n" );
382 }
383 if ( $file !== false ) {
384 $_SESSION['master_log_file'] = $file;
385 $_SESSION['master_pos'] = $pos;
386 }
387 }
388 }
389
390 /**
391 * Loads the master pos from the session, waits for it if necessary
392 */
393 function loadMasterPos() {
394 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
395 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
396 }
397 }
398
399 /**
400 * Close all open connections
401 */
402 function closeAll() {
403 foreach( $this->mConnections as $i => $conn ) {
404 if ( $this->isOpen( $i ) ) {
405 $conn->close();
406 }
407 }
408 }
409
410 function commitAll() {
411 foreach( $this->mConnections as $i => $conn ) {
412 if ( $this->isOpen( $i ) ) {
413 $conn->immediateCommit();
414 }
415 }
416 }
417
418 function waitTimeout( $value = NULL ) {
419 return wfSetVar( $this->mWaitTimeout, $value );
420 }
421
422 function getLaggedSlaveMode() {
423 return $this->mLaggedSlaveMode;
424 }
425 }