Use Doxygen @addtogroup instead of phpdoc @package && @subpackage
[lhc/web/wiklou.git] / includes / LoadBalancer.php
1 <?php
2 /**
3 *
4 */
5
6
7 /**
8 * Database load balancing object
9 *
10 * @todo document
11 */
12 class LoadBalancer {
13 /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
14 /* private */ var $mFailFunction, $mErrorConnection;
15 /* private */ var $mForce, $mReadIndex, $mLastIndex, $mAllowLagged;
16 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
17 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
18
19 /**
20 * Scale polling time so that under overload conditions, the database server
21 * receives a SHOW STATUS query at an average interval of this many microseconds
22 */
23 const AVG_STATUS_POLL = 2000;
24
25 function __construct( $servers, $failFunction = false, $waitTimeout = 10, $waitForMasterNow = false )
26 {
27 $this->mServers = $servers;
28 $this->mFailFunction = $failFunction;
29 $this->mReadIndex = -1;
30 $this->mWriteIndex = -1;
31 $this->mForce = -1;
32 $this->mConnections = array();
33 $this->mLastIndex = 1;
34 $this->mLoads = array();
35 $this->mWaitForFile = false;
36 $this->mWaitForPos = false;
37 $this->mWaitTimeout = $waitTimeout;
38 $this->mLaggedSlaveMode = false;
39 $this->mErrorConnection = false;
40 $this->mAllowLag = false;
41
42 foreach( $servers as $i => $server ) {
43 $this->mLoads[$i] = $server['load'];
44 if ( isset( $server['groupLoads'] ) ) {
45 foreach ( $server['groupLoads'] as $group => $ratio ) {
46 if ( !isset( $this->mGroupLoads[$group] ) ) {
47 $this->mGroupLoads[$group] = array();
48 }
49 $this->mGroupLoads[$group][$i] = $ratio;
50 }
51 }
52 }
53 if ( $waitForMasterNow ) {
54 $this->loadMasterPos();
55 }
56 }
57
58 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
59 {
60 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
61 }
62
63 /**
64 * Given an array of non-normalised probabilities, this function will select
65 * an element and return the appropriate key
66 */
67 function pickRandom( $weights )
68 {
69 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
70 return false;
71 }
72
73 $sum = array_sum( $weights );
74 if ( $sum == 0 ) {
75 # No loads on any of them
76 # In previous versions, this triggered an unweighted random selection,
77 # but this feature has been removed as of April 2006 to allow for strict
78 # separation of query groups.
79 return false;
80 }
81 $max = mt_getrandmax();
82 $rand = mt_rand(0, $max) / $max * $sum;
83
84 $sum = 0;
85 foreach ( $weights as $i => $w ) {
86 $sum += $w;
87 if ( $sum >= $rand ) {
88 break;
89 }
90 }
91 return $i;
92 }
93
94 function getRandomNonLagged( $loads ) {
95 # Unset excessively lagged servers
96 $lags = $this->getLagTimes();
97 foreach ( $lags as $i => $lag ) {
98 if ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
99 unset( $loads[$i] );
100 }
101 }
102
103 # Find out if all the slaves with non-zero load are lagged
104 $sum = 0;
105 foreach ( $loads as $load ) {
106 $sum += $load;
107 }
108 if ( $sum == 0 ) {
109 # No appropriate DB servers except maybe the master and some slaves with zero load
110 # Do NOT use the master
111 # Instead, this function will return false, triggering read-only mode,
112 # and a lagged slave will be used instead.
113 return false;
114 }
115
116 if ( count( $loads ) == 0 ) {
117 return false;
118 }
119
120 #wfDebugLog( 'connect', var_export( $loads, true ) );
121
122 # Return a random representative of the remainder
123 return $this->pickRandom( $loads );
124 }
125
126 /**
127 * Get the index of the reader connection, which may be a slave
128 * This takes into account load ratios and lag times. It should
129 * always return a consistent index during a given invocation
130 *
131 * Side effect: opens connections to databases
132 */
133 function getReaderIndex() {
134 global $wgReadOnly, $wgDBClusterTimeout;
135
136 $fname = 'LoadBalancer::getReaderIndex';
137 wfProfileIn( $fname );
138
139 $i = false;
140 if ( $this->mForce >= 0 ) {
141 $i = $this->mForce;
142 } elseif ( count( $this->mServers ) == 1 ) {
143 # Skip the load balancing if there's only one server
144 $i = 0;
145 } else {
146 if ( $this->mReadIndex >= 0 ) {
147 $i = $this->mReadIndex;
148 } else {
149 # $loads is $this->mLoads except with elements knocked out if they
150 # don't work
151 $loads = $this->mLoads;
152 $done = false;
153 $totalElapsed = 0;
154 do {
155 if ( $wgReadOnly or $this->mAllowLagged ) {
156 $i = $this->pickRandom( $loads );
157 } else {
158 $i = $this->getRandomNonLagged( $loads );
159 if ( $i === false && count( $loads ) != 0 ) {
160 # All slaves lagged. Switch to read-only mode
161 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
162 $i = $this->pickRandom( $loads );
163 }
164 }
165 $serverIndex = $i;
166 if ( $i !== false ) {
167 wfDebugLog( 'connect', "$fname: Using reader #$i: {$this->mServers[$i]['host']}...\n" );
168 $this->openConnection( $i );
169
170 if ( !$this->isOpen( $i ) ) {
171 wfDebug( "$fname: Failed\n" );
172 unset( $loads[$i] );
173 $sleepTime = 0;
174 } else {
175 if ( isset( $this->mServers[$i]['max threads'] ) ) {
176 $status = $this->mConnections[$i]->getStatus("Thread%");
177 if ( $status['Threads_running'] > $this->mServers[$i]['max threads'] ) {
178 # Too much load, back off and wait for a while.
179 # The sleep time is scaled by the number of threads connected,
180 # to produce a roughly constant global poll rate.
181 $sleepTime = self::AVG_STATUS_POLL * $status['Threads_connected'];
182
183 # If we reach the timeout and exit the loop, don't use it
184 $i = false;
185 } else {
186 $done = true;
187 $sleepTime = 0;
188 }
189 } else {
190 $done = true;
191 $sleepTime = 0;
192 }
193 }
194 } else {
195 $sleepTime = 500000;
196 }
197 if ( $sleepTime ) {
198 $totalElapsed += $sleepTime;
199 $x = "{$this->mServers[$serverIndex]['host']} [$serverIndex]";
200 wfProfileIn( "$fname-sleep $x" );
201 usleep( $sleepTime );
202 wfProfileOut( "$fname-sleep $x" );
203 }
204 } while ( count( $loads ) && !$done && $totalElapsed / 1e6 < $wgDBClusterTimeout );
205
206 if ( $totalElapsed / 1e6 >= $wgDBClusterTimeout ) {
207 $this->mErrorConnection = false;
208 $this->mLastError = 'All servers busy';
209 }
210
211 if ( $i !== false && $this->isOpen( $i ) ) {
212 # Wait for the session master pos for a short time
213 if ( $this->mWaitForFile ) {
214 if ( !$this->doWait( $i ) ) {
215 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
216 }
217 }
218 if ( $i !== false ) {
219 $this->mReadIndex = $i;
220 }
221 } else {
222 $i = false;
223 }
224 }
225 }
226 wfProfileOut( $fname );
227 return $i;
228 }
229
230 /**
231 * Get a random server to use in a query group
232 */
233 function getGroupIndex( $group ) {
234 if ( isset( $this->mGroupLoads[$group] ) ) {
235 $i = $this->pickRandom( $this->mGroupLoads[$group] );
236 } else {
237 $i = false;
238 }
239 wfDebug( "Query group $group => $i\n" );
240 return $i;
241 }
242
243 /**
244 * Set the master wait position
245 * If a DB_SLAVE connection has been opened already, waits
246 * Otherwise sets a variable telling it to wait if such a connection is opened
247 */
248 function waitFor( $file, $pos ) {
249 $fname = 'LoadBalancer::waitFor';
250 wfProfileIn( $fname );
251
252 wfDebug( "User master pos: $file $pos\n" );
253 $this->mWaitForFile = false;
254 $this->mWaitForPos = false;
255
256 if ( count( $this->mServers ) > 1 ) {
257 $this->mWaitForFile = $file;
258 $this->mWaitForPos = $pos;
259 $i = $this->mReadIndex;
260
261 if ( $i > 0 ) {
262 if ( !$this->doWait( $i ) ) {
263 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
264 $this->mLaggedSlaveMode = true;
265 }
266 }
267 }
268 wfProfileOut( $fname );
269 }
270
271 /**
272 * Wait for a given slave to catch up to the master pos stored in $this
273 */
274 function doWait( $index ) {
275 global $wgMemc;
276
277 $retVal = false;
278
279 # Debugging hacks
280 if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
281 return false;
282 } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
283 return true;
284 }
285
286 $key = 'masterpos:' . $index;
287 $memcPos = $wgMemc->get( $key );
288 if ( $memcPos ) {
289 list( $file, $pos ) = explode( ' ', $memcPos );
290 # If the saved position is later than the requested position, return now
291 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
292 $retVal = true;
293 }
294 }
295
296 if ( !$retVal && $this->isOpen( $index ) ) {
297 $conn =& $this->mConnections[$index];
298 wfDebug( "Waiting for slave #$index to catch up...\n" );
299 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
300
301 if ( $result == -1 || is_null( $result ) ) {
302 # Timed out waiting for slave, use master instead
303 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
304 $retVal = false;
305 } else {
306 $retVal = true;
307 wfDebug( "Done\n" );
308 }
309 }
310 return $retVal;
311 }
312
313 /**
314 * Get a connection by index
315 */
316 function &getConnection( $i, $fail = true, $groups = array() )
317 {
318 global $wgDBtype;
319 $fname = 'LoadBalancer::getConnection';
320 wfProfileIn( $fname );
321
322
323 # Query groups
324 if ( !is_array( $groups ) ) {
325 $groupIndex = $this->getGroupIndex( $groups, $i );
326 if ( $groupIndex !== false ) {
327 $i = $groupIndex;
328 }
329 } else {
330 foreach ( $groups as $group ) {
331 $groupIndex = $this->getGroupIndex( $group, $i );
332 if ( $groupIndex !== false ) {
333 $i = $groupIndex;
334 break;
335 }
336 }
337 }
338
339 # For now, only go through all this for mysql databases
340 if ($wgDBtype != 'mysql') {
341 $i = $this->getWriterIndex();
342 }
343 # Operation-based index
344 elseif ( $i == DB_SLAVE ) {
345 $i = $this->getReaderIndex();
346 } elseif ( $i == DB_MASTER ) {
347 $i = $this->getWriterIndex();
348 } elseif ( $i == DB_LAST ) {
349 # Just use $this->mLastIndex, which should already be set
350 $i = $this->mLastIndex;
351 if ( $i === -1 ) {
352 # Oh dear, not set, best to use the writer for safety
353 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
354 $i = $this->getWriterIndex();
355 }
356 }
357 # Couldn't find a working server in getReaderIndex()?
358 if ( $i === false ) {
359 $this->reportConnectionError( $this->mErrorConnection );
360 }
361 # Now we have an explicit index into the servers array
362 $this->openConnection( $i, $fail );
363
364 wfProfileOut( $fname );
365 return $this->mConnections[$i];
366 }
367
368 /**
369 * Open a connection to the server given by the specified index
370 * Index must be an actual index into the array
371 * Returns success
372 * @access private
373 */
374 function openConnection( $i, $fail = false ) {
375 $fname = 'LoadBalancer::openConnection';
376 wfProfileIn( $fname );
377 $success = true;
378
379 if ( !$this->isOpen( $i ) ) {
380 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
381 }
382
383 if ( !$this->isOpen( $i ) ) {
384 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
385 if ( $fail ) {
386 $this->reportConnectionError( $this->mConnections[$i] );
387 }
388 $this->mErrorConnection = $this->mConnections[$i];
389 $this->mConnections[$i] = false;
390 $success = false;
391 }
392 $this->mLastIndex = $i;
393 wfProfileOut( $fname );
394 return $success;
395 }
396
397 /**
398 * Test if the specified index represents an open connection
399 * @access private
400 */
401 function isOpen( $index ) {
402 if( !is_integer( $index ) ) {
403 return false;
404 }
405 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
406 $this->mConnections[$index]->isOpen() )
407 {
408 return true;
409 } else {
410 return false;
411 }
412 }
413
414 /**
415 * Really opens a connection
416 * @access private
417 */
418 function reallyOpenConnection( &$server ) {
419 if( !is_array( $server ) ) {
420 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
421 }
422
423 extract( $server );
424 # Get class for this database type
425 $class = 'Database' . ucfirst( $type );
426
427 # Create object
428 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
429 $db->setLBInfo( $server );
430 return $db;
431 }
432
433 function reportConnectionError( &$conn )
434 {
435 $fname = 'LoadBalancer::reportConnectionError';
436 wfProfileIn( $fname );
437 # Prevent infinite recursion
438
439 static $reporting = false;
440 if ( !$reporting ) {
441 $reporting = true;
442 if ( !is_object( $conn ) ) {
443 // No last connection, probably due to all servers being too busy
444 $conn = new Database;
445 if ( $this->mFailFunction ) {
446 $conn->failFunction( $this->mFailFunction );
447 $conn->reportConnectionError( $this->mLastError );
448 } else {
449 // If all servers were busy, mLastError will contain something sensible
450 throw new DBConnectionError( $conn, $this->mLastError );
451 }
452 } else {
453 if ( $this->mFailFunction ) {
454 $conn->failFunction( $this->mFailFunction );
455 } else {
456 $conn->failFunction( false );
457 }
458 $server = $conn->getProperty( 'mServer' );
459 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
460 }
461 $reporting = false;
462 }
463 wfProfileOut( $fname );
464 }
465
466 function getWriterIndex() {
467 return 0;
468 }
469
470 /**
471 * Force subsequent calls to getConnection(DB_SLAVE) to return the
472 * given index. Set to -1 to restore the original load balancing
473 * behaviour. I thought this was a good idea when I originally
474 * wrote this class, but it has never been used.
475 */
476 function force( $i ) {
477 $this->mForce = $i;
478 }
479
480 /**
481 * Returns true if the specified index is a valid server index
482 */
483 function haveIndex( $i ) {
484 return array_key_exists( $i, $this->mServers );
485 }
486
487 /**
488 * Returns true if the specified index is valid and has non-zero load
489 */
490 function isNonZeroLoad( $i ) {
491 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
492 }
493
494 /**
495 * Get the number of defined servers (not the number of open connections)
496 */
497 function getServerCount() {
498 return count( $this->mServers );
499 }
500
501 /**
502 * Save master pos to the session and to memcached, if the session exists
503 */
504 function saveMasterPos() {
505 global $wgSessionStarted;
506 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
507 # If this entire request was served from a slave without opening a connection to the
508 # master (however unlikely that may be), then we can fetch the position from the slave.
509 if ( empty( $this->mConnections[0] ) ) {
510 $conn =& $this->getConnection( DB_SLAVE );
511 list( $file, $pos ) = $conn->getSlavePos();
512 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
513 } else {
514 $conn =& $this->getConnection( 0 );
515 list( $file, $pos ) = $conn->getMasterPos();
516 wfDebug( "Saving master pos: $file $pos\n" );
517 }
518 if ( $file !== false ) {
519 $_SESSION['master_log_file'] = $file;
520 $_SESSION['master_pos'] = $pos;
521 }
522 }
523 }
524
525 /**
526 * Loads the master pos from the session, waits for it if necessary
527 */
528 function loadMasterPos() {
529 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
530 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
531 }
532 }
533
534 /**
535 * Close all open connections
536 */
537 function closeAll() {
538 foreach( $this->mConnections as $i => $conn ) {
539 if ( $this->isOpen( $i ) ) {
540 // Need to use this syntax because $conn is a copy not a reference
541 $this->mConnections[$i]->close();
542 }
543 }
544 }
545
546 function commitAll() {
547 foreach( $this->mConnections as $i => $conn ) {
548 if ( $this->isOpen( $i ) ) {
549 // Need to use this syntax because $conn is a copy not a reference
550 $this->mConnections[$i]->immediateCommit();
551 }
552 }
553 }
554
555 function waitTimeout( $value = NULL ) {
556 return wfSetVar( $this->mWaitTimeout, $value );
557 }
558
559 function getLaggedSlaveMode() {
560 return $this->mLaggedSlaveMode;
561 }
562
563 /* Disables/enables lag checks */
564 function allowLagged($mode=null) {
565 if ($mode===null)
566 return $this->mAllowLagged;
567 $this->mAllowLagged=$mode;
568 }
569
570 function pingAll() {
571 $success = true;
572 foreach ( $this->mConnections as $i => $conn ) {
573 if ( $this->isOpen( $i ) ) {
574 if ( !$this->mConnections[$i]->ping() ) {
575 $success = false;
576 }
577 }
578 }
579 return $success;
580 }
581
582 /**
583 * Get the hostname and lag time of the most-lagged slave
584 * This is useful for maintenance scripts that need to throttle their updates
585 */
586 function getMaxLag() {
587 $maxLag = -1;
588 $host = '';
589 foreach ( $this->mServers as $i => $conn ) {
590 if ( $this->openConnection( $i ) ) {
591 $lag = $this->mConnections[$i]->getLag();
592 if ( $lag > $maxLag ) {
593 $maxLag = $lag;
594 $host = $this->mServers[$i]['host'];
595 }
596 }
597 }
598 return array( $host, $maxLag );
599 }
600
601 /**
602 * Get lag time for each DB
603 * Results are cached for a short time in memcached
604 */
605 function getLagTimes() {
606 wfProfileIn( __METHOD__ );
607 $expiry = 5;
608 $requestRate = 10;
609
610 global $wgMemc;
611 $times = $wgMemc->get( wfMemcKey( 'lag_times' ) );
612 if ( $times ) {
613 # Randomly recache with probability rising over $expiry
614 $elapsed = time() - $times['timestamp'];
615 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
616 if ( mt_rand( 0, $chance ) != 0 ) {
617 unset( $times['timestamp'] );
618 wfProfileOut( __METHOD__ );
619 return $times;
620 }
621 wfIncrStats( 'lag_cache_miss_expired' );
622 } else {
623 wfIncrStats( 'lag_cache_miss_absent' );
624 }
625
626 # Cache key missing or expired
627
628 $times = array();
629 foreach ( $this->mServers as $i => $conn ) {
630 if ($i==0) { # Master
631 $times[$i] = 0;
632 } elseif ( $this->openConnection( $i ) ) {
633 $times[$i] = $this->mConnections[$i]->getLag();
634 }
635 }
636
637 # Add a timestamp key so we know when it was cached
638 $times['timestamp'] = time();
639 $wgMemc->set( wfMemcKey( 'lag_times' ), $times, $expiry );
640
641 # But don't give the timestamp to the caller
642 unset($times['timestamp']);
643 wfProfileOut( __METHOD__ );
644 return $times;
645 }
646 }
647
648 ?>