8 * Depends on the database object
10 require_once( 'Database.php' );
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
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
23 # Scale polling time so that under overload conditions, the database server
24 # receives a SHOW STATUS query at an average interval of this many microseconds
25 define( 'AVG_STATUS_POLL', 2000 );
29 * Database load balancing object
44 $mLastError = 'Unknown error',
53 function LoadBalancer()
55 $this->mServers
= array();
56 $this->mConnections
= array();
57 $this->mFailFunction
= false;
58 $this->mReadIndex
= -1;
60 $this->mLastIndex
= -1;
61 $this->mErrorConnection
= false;
62 $this->mAllowLag
= false;
65 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
67 $lb = new LoadBalancer
;
68 $lb->initialise( $servers, $failFunction, $waitTimeout );
72 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
74 $this->mServers
= $servers;
75 $this->mFailFunction
= $failFunction;
76 $this->mReadIndex
= -1;
77 $this->mWriteIndex
= -1;
79 $this->mConnections
= array();
80 $this->mLastIndex
= 1;
81 $this->mLoads
= array();
82 $this->mWaitForFile
= false;
83 $this->mWaitForPos
= false;
84 $this->mWaitTimeout
= $waitTimeout;
85 $this->mLaggedSlaveMode
= false;
87 foreach( $servers as $i => $server ) {
88 $this->mLoads
[$i] = $server['load'];
89 if ( isset( $server['groupLoads'] ) ) {
90 foreach ( $server['groupLoads'] as $group => $ratio ) {
91 if ( !isset( $this->mGroupLoads
[$group] ) ) {
92 $this->mGroupLoads
[$group] = array();
94 $this->mGroupLoads
[$group][$i] = $ratio;
101 * Given an array of non-normalised probabilities, this function will select
102 * an element and return the appropriate key
104 function pickRandom( $weights )
106 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
110 $sum = array_sum( $weights );
112 # No loads on any of them
113 # In previous versions, this triggered an unweighted random selection,
114 # but this feature has been removed as of April 2006 to allow for strict
115 # separation of query groups.
118 $max = mt_getrandmax();
119 $rand = mt_rand(0, $max) / $max * $sum;
122 foreach ( $weights as $i => $w ) {
124 if ( $sum >= $rand ) {
131 function getRandomNonLagged( $loads ) {
132 # Unset excessively lagged servers
133 $lags = $this->getLagTimes();
134 foreach ( $lags as $i => $lag ) {
135 if ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
140 # Find out if all the slaves with non-zero load are lagged
142 foreach ( $loads as $load ) {
146 # No appropriate DB servers except maybe the master and some slaves with zero load
147 # Do NOT use the master
148 # Instead, this function will return false, triggering read-only mode,
149 # and a lagged slave will be used instead.
153 if ( count( $loads ) == 0 ) {
157 #wfDebugLog( 'connect', var_export( $loads, true ) );
159 # Return a random representative of the remainder
160 return $this->pickRandom( $loads );
164 * Get the index of the reader connection, which may be a slave
165 * This takes into account load ratios and lag times. It should
166 * always return a consistent index during a given invocation
168 * Side effect: opens connections to databases
170 function getReaderIndex() {
171 global $wgReadOnly, $wgDBClusterTimeout;
173 $fname = 'LoadBalancer::getReaderIndex';
174 wfProfileIn( $fname );
177 if ( $this->mForce
>= 0 ) {
180 if ( $this->mReadIndex
>= 0 ) {
181 $i = $this->mReadIndex
;
183 # $loads is $this->mLoads except with elements knocked out if they
185 $loads = $this->mLoads
;
189 if ( $wgReadOnly or $this->mAllowLagged
) {
190 $i = $this->pickRandom( $loads );
192 $i = $this->getRandomNonLagged( $loads );
193 if ( $i === false && count( $loads ) != 0 ) {
194 # All slaves lagged. Switch to read-only mode
195 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
196 $i = $this->pickRandom( $loads );
200 if ( $i !== false ) {
201 wfDebugLog( 'connect', "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
202 $this->openConnection( $i );
204 if ( !$this->isOpen( $i ) ) {
205 wfDebug( "Failed\n" );
209 $status = $this->mConnections
[$i]->getStatus("Thread%");
210 if ( isset( $this->mServers
[$i]['max threads'] ) &&
211 $status['Threads_running'] > $this->mServers
[$i]['max threads'] )
213 # Too much load, back off and wait for a while.
214 # The sleep time is scaled by the number of threads connected,
215 # to produce a roughly constant global poll rate.
216 $sleepTime = AVG_STATUS_POLL
* $status['Threads_connected'];
218 # If we reach the timeout and exit the loop, don't use it
229 $totalElapsed +
= $sleepTime;
230 $x = "{$this->mServers[$serverIndex]['host']} [$serverIndex]";
231 wfProfileIn( "$fname-sleep $x" );
232 usleep( $sleepTime );
233 wfProfileOut( "$fname-sleep $x" );
235 } while ( count( $loads ) && !$done && $totalElapsed / 1e6
< $wgDBClusterTimeout );
237 if ( $totalElapsed / 1e6
>= $wgDBClusterTimeout ) {
238 $this->mErrorConnection
= false;
239 $this->mLastError
= 'All servers busy';
242 if ( $i !== false && $this->isOpen( $i ) ) {
243 # Wait for the session master pos for a short time
244 if ( $this->mWaitForFile
) {
245 if ( !$this->doWait( $i ) ) {
246 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
249 if ( $i !== false ) {
250 $this->mReadIndex
= $i;
257 wfProfileOut( $fname );
262 * Get a random server to use in a query group
264 function getGroupIndex( $group ) {
265 if ( isset( $this->mGroupLoads
[$group] ) ) {
266 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
270 wfDebug( "Query group $group => $i\n" );
275 * Set the master wait position
276 * If a DB_SLAVE connection has been opened already, waits
277 * Otherwise sets a variable telling it to wait if such a connection is opened
279 function waitFor( $file, $pos ) {
280 $fname = 'LoadBalancer::waitFor';
281 wfProfileIn( $fname );
283 wfDebug( "User master pos: $file $pos\n" );
284 $this->mWaitForFile
= false;
285 $this->mWaitForPos
= false;
287 if ( count( $this->mServers
) > 1 ) {
288 $this->mWaitForFile
= $file;
289 $this->mWaitForPos
= $pos;
290 $i = $this->mReadIndex
;
293 if ( !$this->doWait( $i ) ) {
294 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
295 $this->mLaggedSlaveMode
= true;
299 wfProfileOut( $fname );
303 * Wait for a given slave to catch up to the master pos stored in $this
305 function doWait( $index ) {
311 if ( isset( $this->mServers
[$index]['lagged slave'] ) ) {
313 } elseif ( isset( $this->mServers
[$index]['fake slave'] ) ) {
317 $key = 'masterpos:' . $index;
318 $memcPos = $wgMemc->get( $key );
320 list( $file, $pos ) = explode( ' ', $memcPos );
321 # If the saved position is later than the requested position, return now
322 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
327 if ( !$retVal && $this->isOpen( $index ) ) {
328 $conn =& $this->mConnections
[$index];
329 wfDebug( "Waiting for slave #$index to catch up...\n" );
330 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, $this->mWaitTimeout
);
332 if ( $result == -1 ||
is_null( $result ) ) {
333 # Timed out waiting for slave, use master instead
334 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
345 * Get a connection by index
347 function &getConnection( $i, $fail = true, $groups = array() )
350 $fname = 'LoadBalancer::getConnection';
351 wfProfileIn( $fname );
355 if ( !is_array( $groups ) ) {
356 $groupIndex = $this->getGroupIndex( $groups, $i );
357 if ( $groupIndex !== false ) {
361 foreach ( $groups as $group ) {
362 $groupIndex = $this->getGroupIndex( $group, $i );
363 if ( $groupIndex !== false ) {
370 # For now, only go through all this for mysql databases
371 if ($wgDBtype != 'mysql') {
372 $i = $this->getWriterIndex();
374 # Operation-based index
375 elseif ( $i == DB_SLAVE
) {
376 $i = $this->getReaderIndex();
377 } elseif ( $i == DB_MASTER
) {
378 $i = $this->getWriterIndex();
379 } elseif ( $i == DB_LAST
) {
380 # Just use $this->mLastIndex, which should already be set
381 $i = $this->mLastIndex
;
383 # Oh dear, not set, best to use the writer for safety
384 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
385 $i = $this->getWriterIndex();
388 # Couldn't find a working server in getReaderIndex()?
389 if ( $i === false ) {
390 $this->reportConnectionError( $this->mErrorConnection
);
392 # Now we have an explicit index into the servers array
393 $this->openConnection( $i, $fail );
395 wfProfileOut( $fname );
396 return $this->mConnections
[$i];
400 * Open a connection to the server given by the specified index
401 * Index must be an actual index into the array
405 function openConnection( $i, $fail = false ) {
406 $fname = 'LoadBalancer::openConnection';
407 wfProfileIn( $fname );
410 if ( !$this->isOpen( $i ) ) {
411 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
414 if ( !$this->isOpen( $i ) ) {
415 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
417 $this->reportConnectionError( $this->mConnections
[$i] );
419 $this->mErrorConnection
= $this->mConnections
[$i];
420 $this->mConnections
[$i] = false;
423 $this->mLastIndex
= $i;
424 wfProfileOut( $fname );
429 * Test if the specified index represents an open connection
432 function isOpen( $index ) {
433 if( !is_integer( $index ) ) {
436 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
437 $this->mConnections
[$index]->isOpen() )
446 * Really opens a connection
449 function reallyOpenConnection( &$server ) {
450 if( !is_array( $server ) ) {
451 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
455 # Get class for this database type
456 $class = 'Database' . ucfirst( $type );
457 if ( !class_exists( $class ) ) {
458 require_once( "$class.php" );
462 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
463 $db->setLBInfo( $server );
467 function reportConnectionError( &$conn )
469 $fname = 'LoadBalancer::reportConnectionError';
470 wfProfileIn( $fname );
471 # Prevent infinite recursion
473 static $reporting = false;
476 if ( !is_object( $conn ) ) {
477 // No last connection, probably due to all servers being too busy
478 $conn = new Database
;
479 if ( $this->mFailFunction
) {
480 $conn->failFunction( $this->mFailFunction
);
481 $conn->reportConnectionError( $this->mLastError
);
483 // If all servers were busy, mLastError will contain something sensible
484 wfEmergencyAbort( $conn, $this->mLastError
);
487 if ( $this->mFailFunction
) {
488 $conn->failFunction( $this->mFailFunction
);
490 $conn->failFunction( false );
492 $conn->reportConnectionError( "{$this->mLastError} ({$conn->mServer})" );
496 wfProfileOut( $fname );
499 function getWriterIndex()
509 function haveIndex( $i )
511 return array_key_exists( $i, $this->mServers
);
515 * Get the number of defined servers (not the number of open connections)
517 function getServerCount() {
518 return count( $this->mServers
);
522 * Save master pos to the session and to memcached, if the session exists
524 function saveMasterPos() {
525 global $wgSessionStarted;
526 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
527 # If this entire request was served from a slave without opening a connection to the
528 # master (however unlikely that may be), then we can fetch the position from the slave.
529 if ( empty( $this->mConnections
[0] ) ) {
530 $conn =& $this->getConnection( DB_SLAVE
);
531 list( $file, $pos ) = $conn->getSlavePos();
532 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
534 $conn =& $this->getConnection( 0 );
535 list( $file, $pos ) = $conn->getMasterPos();
536 wfDebug( "Saving master pos: $file $pos\n" );
538 if ( $file !== false ) {
539 $_SESSION['master_log_file'] = $file;
540 $_SESSION['master_pos'] = $pos;
546 * Loads the master pos from the session, waits for it if necessary
548 function loadMasterPos() {
549 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
550 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
555 * Close all open connections
557 function closeAll() {
558 foreach( $this->mConnections
as $i => $conn ) {
559 if ( $this->isOpen( $i ) ) {
560 // Need to use this syntax because $conn is a copy not a reference
561 $this->mConnections
[$i]->close();
566 function commitAll() {
567 foreach( $this->mConnections
as $i => $conn ) {
568 if ( $this->isOpen( $i ) ) {
569 // Need to use this syntax because $conn is a copy not a reference
570 $this->mConnections
[$i]->immediateCommit();
575 function waitTimeout( $value = NULL ) {
576 return wfSetVar( $this->mWaitTimeout
, $value );
579 function getLaggedSlaveMode() {
580 return $this->mLaggedSlaveMode
;
583 /* Disables/enables lag checks */
584 function allowLagged($mode=null) {
586 return $this->mAllowLagged
;
587 $this->mAllowLagged
=$mode;
592 foreach ( $this->mConnections
as $i => $conn ) {
593 if ( $this->isOpen( $i ) ) {
594 if ( !$this->mConnections
[$i]->ping() ) {
603 * Get the hostname and lag time of the most-lagged slave
604 * This is useful for maintenance scripts that need to throttle their updates
606 function getMaxLag() {
609 foreach ( $this->mServers
as $i => $conn ) {
610 if ( $this->openConnection( $i ) ) {
611 $lag = $this->mConnections
[$i]->getLag();
612 if ( $lag > $maxLag ) {
614 $host = $this->mServers
[$i]['host'];
618 return array( $host, $maxLag );
622 * Get lag time for each DB
623 * Results are cached for a short time in memcached
625 function getLagTimes() {
632 $times = $wgMemc->get( "$wgDBname:lag_times" );
634 # Randomly recache with probability rising over $expiry
635 $elapsed = time() - $times['timestamp'];
636 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
637 if ( mt_rand( 0, $chance ) != 0 ) {
638 unset( $times['timestamp'] );
643 # Cache key missing or expired
646 foreach ( $this->mServers
as $i => $conn ) {
647 if ($i==0) { # Master
649 } elseif ( $this->openConnection( $i ) ) {
650 $times[$i] = $this->mConnections
[$i]->getLag();
654 # Add a timestamp key so we know when it was cached
655 $times['timestamp'] = time();
656 $wgMemc->set( "$wgDBname:lag_times", $times, $expiry );
658 # But don't give the timestamp to the caller
659 unset($times['timestamp']);