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
35 /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
36 /* private */ var $mFailFunction, $mErrorConnection;
37 /* private */ var $mForce, $mReadIndex, $mLastIndex, $mAllowLagged;
38 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
39 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
41 function LoadBalancer()
43 $this->mServers
= array();
44 $this->mConnections
= array();
45 $this->mFailFunction
= false;
46 $this->mReadIndex
= -1;
48 $this->mLastIndex
= -1;
49 $this->mErrorConnection
= false;
50 $this->mAllowLag
= false;
53 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
55 $lb = new LoadBalancer
;
56 $lb->initialise( $servers, $failFunction, $waitTimeout );
60 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
62 $this->mServers
= $servers;
63 $this->mFailFunction
= $failFunction;
64 $this->mReadIndex
= -1;
65 $this->mWriteIndex
= -1;
67 $this->mConnections
= array();
68 $this->mLastIndex
= 1;
69 $this->mLoads
= array();
70 $this->mWaitForFile
= false;
71 $this->mWaitForPos
= false;
72 $this->mWaitTimeout
= $waitTimeout;
73 $this->mLaggedSlaveMode
= false;
75 foreach( $servers as $i => $server ) {
76 $this->mLoads
[$i] = $server['load'];
77 if ( isset( $server['groupLoads'] ) ) {
78 foreach ( $server['groupLoads'] as $group => $ratio ) {
79 if ( !isset( $this->mGroupLoads
[$group] ) ) {
80 $this->mGroupLoads
[$group] = array();
82 $this->mGroupLoads
[$group][$i] = $ratio;
89 * Given an array of non-normalised probabilities, this function will select
90 * an element and return the appropriate key
92 function pickRandom( $weights )
94 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
98 $sum = array_sum( $weights );
100 # No loads on any of them
101 # In previous versions, this triggered an unweighted random selection,
102 # but this feature has been removed as of April 2006 to allow for strict
103 # separation of query groups.
106 $max = mt_getrandmax();
107 $rand = mt_rand(0, $max) / $max * $sum;
110 foreach ( $weights as $i => $w ) {
112 if ( $sum >= $rand ) {
119 function getRandomNonLagged( $loads ) {
120 # Unset excessively lagged servers
121 $lags = $this->getLagTimes();
122 foreach ( $lags as $i => $lag ) {
123 if ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
128 # Find out if all the slaves with non-zero load are lagged
130 foreach ( $loads as $load ) {
134 # No appropriate DB servers except maybe the master and some slaves with zero load
135 # Do NOT use the master
136 # Instead, this function will return false, triggering read-only mode,
137 # and a lagged slave will be used instead.
141 if ( count( $loads ) == 0 ) {
145 #wfDebugLog( 'connect', var_export( $loads, true ) );
147 # Return a random representative of the remainder
148 return $this->pickRandom( $loads );
152 * Get the index of the reader connection, which may be a slave
153 * This takes into account load ratios and lag times. It should
154 * always return a consistent index during a given invocation
156 * Side effect: opens connections to databases
158 function getReaderIndex() {
159 global $wgReadOnly, $wgDBClusterTimeout;
161 $fname = 'LoadBalancer::getReaderIndex';
162 wfProfileIn( $fname );
165 if ( $this->mForce
>= 0 ) {
168 if ( $this->mReadIndex
>= 0 ) {
169 $i = $this->mReadIndex
;
171 # $loads is $this->mLoads except with elements knocked out if they
173 $loads = $this->mLoads
;
177 if ( $wgReadOnly or $this->mAllowLagged
) {
178 $i = $this->pickRandom( $loads );
180 $i = $this->getRandomNonLagged( $loads );
181 if ( $i === false && count( $loads ) != 0 ) {
182 # All slaves lagged. Switch to read-only mode
183 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
184 $i = $this->pickRandom( $loads );
188 if ( $i !== false ) {
189 wfDebugLog( 'connect', "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
190 $this->openConnection( $i );
192 if ( !$this->isOpen( $i ) ) {
193 wfDebug( "Failed\n" );
197 $status = $this->mConnections
[$i]->getStatus("Thread%");
198 if ( isset( $this->mServers
[$i]['max threads'] ) &&
199 $status['Threads_running'] > $this->mServers
[$i]['max threads'] )
201 # Too much load, back off and wait for a while.
202 # The sleep time is scaled by the number of threads connected,
203 # to produce a roughly constant global poll rate.
204 $sleepTime = AVG_STATUS_POLL
* $status['Threads_connected'];
206 # If we reach the timeout and exit the loop, don't use it
217 $totalElapsed +
= $sleepTime;
218 $x = "{$this->mServers[$serverIndex]['host']} [$serverIndex]";
219 wfProfileIn( "$fname-sleep $x" );
220 usleep( $sleepTime );
221 wfProfileOut( "$fname-sleep $x" );
223 } while ( count( $loads ) && !$done && $totalElapsed / 1e6
< $wgDBClusterTimeout );
225 if ( $totalElapsed / 1e6
>= $wgDBClusterTimeout ) {
226 $this->mErrorConnection
= false;
227 $this->mLastError
= 'All servers busy';
230 if ( $i !== false && $this->isOpen( $i ) ) {
231 # Wait for the session master pos for a short time
232 if ( $this->mWaitForFile
) {
233 if ( !$this->doWait( $i ) ) {
234 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
237 if ( $i !== false ) {
238 $this->mReadIndex
= $i;
245 wfProfileOut( $fname );
250 * Get a random server to use in a query group
252 function getGroupIndex( $group ) {
253 if ( isset( $this->mGroupLoads
[$group] ) ) {
254 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
258 wfDebug( "Query group $group => $i\n" );
263 * Set the master wait position
264 * If a DB_SLAVE connection has been opened already, waits
265 * Otherwise sets a variable telling it to wait if such a connection is opened
267 function waitFor( $file, $pos ) {
268 $fname = 'LoadBalancer::waitFor';
269 wfProfileIn( $fname );
271 wfDebug( "User master pos: $file $pos\n" );
272 $this->mWaitForFile
= false;
273 $this->mWaitForPos
= false;
275 if ( count( $this->mServers
) > 1 ) {
276 $this->mWaitForFile
= $file;
277 $this->mWaitForPos
= $pos;
278 $i = $this->mReadIndex
;
281 if ( !$this->doWait( $i ) ) {
282 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
283 $this->mLaggedSlaveMode
= true;
287 wfProfileOut( $fname );
291 * Wait for a given slave to catch up to the master pos stored in $this
293 function doWait( $index ) {
299 if ( isset( $this->mServers
[$index]['lagged slave'] ) ) {
301 } elseif ( isset( $this->mServers
[$index]['fake slave'] ) ) {
305 $key = 'masterpos:' . $index;
306 $memcPos = $wgMemc->get( $key );
308 list( $file, $pos ) = explode( ' ', $memcPos );
309 # If the saved position is later than the requested position, return now
310 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
315 if ( !$retVal && $this->isOpen( $index ) ) {
316 $conn =& $this->mConnections
[$index];
317 wfDebug( "Waiting for slave #$index to catch up...\n" );
318 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, $this->mWaitTimeout
);
320 if ( $result == -1 ||
is_null( $result ) ) {
321 # Timed out waiting for slave, use master instead
322 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
333 * Get a connection by index
335 function &getConnection( $i, $fail = true, $groups = array() )
337 $fname = 'LoadBalancer::getConnection';
338 wfProfileIn( $fname );
342 if ( !is_array( $groups ) ) {
343 $groupIndex = $this->getGroupIndex( $groups, $i );
344 if ( $groupIndex !== false ) {
348 foreach ( $groups as $group ) {
349 $groupIndex = $this->getGroupIndex( $group, $i );
350 if ( $groupIndex !== false ) {
357 # Operation-based index
358 if ( $i == DB_SLAVE
) {
359 $i = $this->getReaderIndex();
360 } elseif ( $i == DB_MASTER
) {
361 $i = $this->getWriterIndex();
362 } elseif ( $i == DB_LAST
) {
363 # Just use $this->mLastIndex, which should already be set
364 $i = $this->mLastIndex
;
366 # Oh dear, not set, best to use the writer for safety
367 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
368 $i = $this->getWriterIndex();
371 # Couldn't find a working server in getReaderIndex()?
372 if ( $i === false ) {
373 $this->reportConnectionError( $this->mErrorConnection
);
375 # Now we have an explicit index into the servers array
376 $this->openConnection( $i, $fail );
378 wfProfileOut( $fname );
379 return $this->mConnections
[$i];
383 * Open a connection to the server given by the specified index
384 * Index must be an actual index into the array
388 function openConnection( $i, $fail = false ) {
389 $fname = 'LoadBalancer::openConnection';
390 wfProfileIn( $fname );
393 if ( !$this->isOpen( $i ) ) {
394 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
397 if ( !$this->isOpen( $i ) ) {
398 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
400 $this->reportConnectionError( $this->mConnections
[$i] );
402 $this->mErrorConnection
= $this->mConnections
[$i];
403 $this->mConnections
[$i] = false;
406 $this->mLastIndex
= $i;
407 wfProfileOut( $fname );
412 * Test if the specified index represents an open connection
415 function isOpen( $index ) {
416 if( !is_integer( $index ) ) {
419 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
420 $this->mConnections
[$index]->isOpen() )
429 * Really opens a connection
432 function reallyOpenConnection( &$server ) {
433 if( !is_array( $server ) ) {
434 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
438 # Get class for this database type
439 $class = 'Database' . ucfirst( $type );
440 if ( !class_exists( $class ) ) {
441 require_once( "$class.php" );
445 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
446 $db->setLBInfo( $server );
450 function reportConnectionError( &$conn )
452 $fname = 'LoadBalancer::reportConnectionError';
453 wfProfileIn( $fname );
454 # Prevent infinite recursion
456 static $reporting = false;
459 if ( !is_object( $conn ) ) {
460 // No last connection, probably due to all servers being too busy
461 $conn = new Database
;
462 if ( $this->mFailFunction
) {
463 $conn->failFunction( $this->mFailFunction
);
464 $conn->reportConnectionError( $this->mLastError
);
466 // If all servers were busy, mLastError will contain something sensible
467 wfEmergencyAbort( $conn, $this->mLastError
);
470 if ( $this->mFailFunction
) {
471 $conn->failFunction( $this->mFailFunction
);
473 $conn->failFunction( false );
475 $conn->reportConnectionError( "{$this->mLastError} ({$conn->mServer})" );
479 wfProfileOut( $fname );
482 function getWriterIndex()
492 function haveIndex( $i )
494 return array_key_exists( $i, $this->mServers
);
498 * Get the number of defined servers (not the number of open connections)
500 function getServerCount() {
501 return count( $this->mServers
);
505 * Save master pos to the session and to memcached, if the session exists
507 function saveMasterPos() {
508 global $wgSessionStarted;
509 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
510 # If this entire request was served from a slave without opening a connection to the
511 # master (however unlikely that may be), then we can fetch the position from the slave.
512 if ( empty( $this->mConnections
[0] ) ) {
513 $conn =& $this->getConnection( DB_SLAVE
);
514 list( $file, $pos ) = $conn->getSlavePos();
515 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
517 $conn =& $this->getConnection( 0 );
518 list( $file, $pos ) = $conn->getMasterPos();
519 wfDebug( "Saving master pos: $file $pos\n" );
521 if ( $file !== false ) {
522 $_SESSION['master_log_file'] = $file;
523 $_SESSION['master_pos'] = $pos;
529 * Loads the master pos from the session, waits for it if necessary
531 function loadMasterPos() {
532 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
533 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
538 * Close all open connections
540 function closeAll() {
541 foreach( $this->mConnections
as $i => $conn ) {
542 if ( $this->isOpen( $i ) ) {
543 // Need to use this syntax because $conn is a copy not a reference
544 $this->mConnections
[$i]->close();
549 function commitAll() {
550 foreach( $this->mConnections
as $i => $conn ) {
551 if ( $this->isOpen( $i ) ) {
552 // Need to use this syntax because $conn is a copy not a reference
553 $this->mConnections
[$i]->immediateCommit();
558 function waitTimeout( $value = NULL ) {
559 return wfSetVar( $this->mWaitTimeout
, $value );
562 function getLaggedSlaveMode() {
563 return $this->mLaggedSlaveMode
;
566 /* Disables/enables lag checks */
567 function allowLagged($mode=null) {
569 return $this->mAllowLagged
;
570 $this->mAllowLagged
=$mode;
575 foreach ( $this->mConnections
as $i => $conn ) {
576 if ( $this->isOpen( $i ) ) {
577 if ( !$this->mConnections
[$i]->ping() ) {
586 * Get the hostname and lag time of the most-lagged slave
587 * This is useful for maintenance scripts that need to throttle their updates
589 function getMaxLag() {
592 foreach ( $this->mServers
as $i => $conn ) {
593 if ( $this->openConnection( $i ) ) {
594 $lag = $this->mConnections
[$i]->getLag();
595 if ( $lag > $maxLag ) {
597 $host = $this->mServers
[$i]['host'];
601 return array( $host, $maxLag );
605 * Get lag time for each DB
606 * Results are cached for a short time in memcached
608 function getLagTimes() {
615 $times = $wgMemc->get( "$wgDBname:lag_times" );
617 # Randomly recache with probability rising over $expiry
618 $elapsed = time() - $times['timestamp'];
619 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
620 if ( mt_rand( 0, $chance ) != 0 ) {
621 unset( $times['timestamp'] );
626 # Cache key missing or expired
629 foreach ( $this->mServers
as $i => $conn ) {
630 if ($i==0) { # Master
632 } elseif ( $this->openConnection( $i ) ) {
633 $times[$i] = $this->mConnections
[$i]->getLag();
637 # Add a timestamp key so we know when it was cached
638 $times['timestamp'] = time();
639 $wgMemc->set( "$wgDBname:lag_times", $times, $expiry );
641 # But don't give the timestamp to the caller
642 unset($times['timestamp']);