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;
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;
52 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
54 $lb = new LoadBalancer
;
55 $lb->initialise( $servers, $failFunction, $waitTimeout );
59 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
61 $this->mServers
= $servers;
62 $this->mFailFunction
= $failFunction;
63 $this->mReadIndex
= -1;
64 $this->mWriteIndex
= -1;
66 $this->mConnections
= array();
67 $this->mLastIndex
= 1;
68 $this->mLoads
= array();
69 $this->mWaitForFile
= false;
70 $this->mWaitForPos
= false;
71 $this->mWaitTimeout
= $waitTimeout;
72 $this->mLaggedSlaveMode
= false;
74 foreach( $servers as $i => $server ) {
75 $this->mLoads
[$i] = $server['load'];
76 if ( isset( $server['groupLoads'] ) ) {
77 foreach ( $server['groupLoads'] as $group => $ratio ) {
78 if ( !isset( $this->mGroupLoads
[$group] ) ) {
79 $this->mGroupLoads
[$group] = array();
81 $this->mGroupLoads
[$group][$i] = $ratio;
88 * Given an array of non-normalised probabilities, this function will select
89 * an element and return the appropriate key
91 function pickRandom( $weights )
93 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
98 foreach ( $weights as $w ) {
103 # No loads on any of them
104 # Just pick one at random
105 foreach ( $weights as $i => $w ) {
109 $max = mt_getrandmax();
110 $rand = mt_rand(0, $max) / $max * $sum;
113 foreach ( $weights as $i => $w ) {
115 if ( $sum >= $rand ) {
122 function getRandomNonLagged( $loads ) {
123 # Unset excessively lagged servers
124 $lags = $this->getLagTimes();
125 foreach ( $lags as $i => $lag ) {
126 if ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
132 # Find out if all the slaves with non-zero load are lagged
134 foreach ( $loads as $load ) {
138 # No appropriate DB servers except maybe the master and some slaves with zero load
139 # Do NOT use the master
140 # Instead, this function will return false, triggering read-only mode,
141 # and a lagged slave will be used instead.
145 if ( count( $loads ) == 0 ) {
149 #wfDebugLog( 'connect', var_export( $loads, true ) );
151 # Return a random representative of the remainder
152 return $this->pickRandom( $loads );
156 * Get the index of the reader connection, which may be a slave
157 * This takes into account load ratios and lag times. It should
158 * always return a consistent index during a given invocation
160 * Side effect: opens connections to databases
162 function getReaderIndex() {
163 global $wgReadOnly, $wgDBClusterTimeout;
165 $fname = 'LoadBalancer::getReaderIndex';
166 wfProfileIn( $fname );
169 if ( $this->mForce
>= 0 ) {
172 if ( $this->mReadIndex
>= 0 ) {
173 $i = $this->mReadIndex
;
175 # $loads is $this->mLoads except with elements knocked out if they
177 $loads = $this->mLoads
;
182 $i = $this->pickRandom( $loads );
184 $i = $this->getRandomNonLagged( $loads );
185 if ( $i === false && count( $loads ) != 0 ) {
186 # All slaves lagged. Switch to read-only mode
187 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
188 $i = $this->pickRandom( $loads );
192 if ( $i !== false ) {
193 wfDebugLog( 'connect', "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
194 $this->openConnection( $i );
196 if ( !$this->isOpen( $i ) ) {
197 wfDebug( "Failed\n" );
201 $status = $this->mConnections
[$i]->getStatus();
202 if ( isset( $this->mServers
[$i]['max threads'] ) &&
203 $status['Threads_running'] > $this->mServers
[$i]['max threads'] )
205 # Slave is lagged, wait for a while
206 $sleepTime = AVG_STATUS_POLL
* $status['Threads_connected'];
208 # If we reach the timeout and exit the loop, don't use it
219 $totalElapsed +
= $sleepTime;
220 $x = "{$this->mServers[$serverIndex]['host']} [$serverIndex]";
221 wfProfileIn( "$fname-sleep $x" );
222 usleep( $sleepTime );
223 wfProfileOut( "$fname-sleep $x" );
225 } while ( count( $loads ) && !$done && $totalElapsed / 1e6
< $wgDBClusterTimeout );
227 if ( $totalElapsed / 1e6
>= $wgDBClusterTimeout ) {
228 $this->mErrorConnection
= false;
229 $this->mLastError
= 'All servers busy';
232 if ( $i !== false && $this->isOpen( $i ) ) {
233 # Wait for the session master pos for a short time
234 if ( $this->mWaitForFile
) {
235 if ( !$this->doWait( $i ) ) {
236 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
239 if ( $i !== false ) {
240 $this->mReadIndex
= $i;
247 wfProfileOut( $fname );
252 * Get a random server to use in a query group
254 function getGroupIndex( $group ) {
255 if ( isset( $this->mGroupLoads
[$group] ) ) {
256 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
260 wfDebug( "Query group $group => $i\n" );
265 * Set the master wait position
266 * If a DB_SLAVE connection has been opened already, waits
267 * Otherwise sets a variable telling it to wait if such a connection is opened
269 function waitFor( $file, $pos ) {
270 $fname = 'LoadBalancer::waitFor';
271 wfProfileIn( $fname );
273 wfDebug( "User master pos: $file $pos\n" );
274 $this->mWaitForFile
= false;
275 $this->mWaitForPos
= false;
277 if ( count( $this->mServers
) > 1 ) {
278 $this->mWaitForFile
= $file;
279 $this->mWaitForPos
= $pos;
280 $i = $this->mReadIndex
;
283 if ( !$this->doWait( $i ) ) {
284 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
285 $this->mLaggedSlaveMode
= true;
289 wfProfileOut( $fname );
293 * Wait for a given slave to catch up to the master pos stored in $this
295 function doWait( $index ) {
301 if ( isset( $this->mServers
[$index]['lagged slave'] ) ) {
303 } elseif ( isset( $this->mServers
[$index]['fake slave'] ) ) {
307 $key = 'masterpos:' . $index;
308 $memcPos = $wgMemc->get( $key );
310 list( $file, $pos ) = explode( ' ', $memcPos );
311 # If the saved position is later than the requested position, return now
312 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
317 if ( !$retVal && $this->isOpen( $index ) ) {
318 $conn =& $this->mConnections
[$index];
319 wfDebug( "Waiting for slave #$index to catch up...\n" );
320 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, $this->mWaitTimeout
);
322 if ( $result == -1 ||
is_null( $result ) ) {
323 # Timed out waiting for slave, use master instead
324 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
335 * Get a connection by index
337 function &getConnection( $i, $fail = true, $groups = array() )
339 $fname = 'LoadBalancer::getConnection';
340 wfProfileIn( $fname );
344 foreach ( $groups as $group ) {
345 $groupIndex = $this->getGroupIndex( $group );
346 if ( $groupIndex !== false ) {
352 # Operation-based index
353 if ( $i == DB_SLAVE
) {
354 $i = $this->getReaderIndex();
355 } elseif ( $i == DB_MASTER
) {
356 $i = $this->getWriterIndex();
357 } elseif ( $i == DB_LAST
) {
358 # Just use $this->mLastIndex, which should already be set
359 $i = $this->mLastIndex
;
361 # Oh dear, not set, best to use the writer for safety
362 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
363 $i = $this->getWriterIndex();
366 # Couldn't find a working server in getReaderIndex()?
367 if ( $i === false ) {
368 $this->reportConnectionError( $this->mErrorConnection
);
370 # Now we have an explicit index into the servers array
371 $this->openConnection( $i, $fail );
373 wfProfileOut( $fname );
374 return $this->mConnections
[$i];
378 * Open a connection to the server given by the specified index
379 * Index must be an actual index into the array
383 function openConnection( $i, $fail = false ) {
384 $fname = 'LoadBalancer::openConnection';
385 wfProfileIn( $fname );
388 if ( !$this->isOpen( $i ) ) {
389 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
392 if ( !$this->isOpen( $i ) ) {
393 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
395 $this->reportConnectionError( $this->mConnections
[$i] );
397 $this->mErrorConnection
= $this->mConnections
[$i];
398 $this->mConnections
[$i] = false;
401 $this->mLastIndex
= $i;
402 wfProfileOut( $fname );
407 * Test if the specified index represents an open connection
410 function isOpen( $index ) {
411 if( !is_integer( $index ) ) {
414 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
415 $this->mConnections
[$index]->isOpen() )
424 * Really opens a connection
427 function reallyOpenConnection( &$server ) {
428 if( !is_array( $server ) ) {
429 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
433 # Get class for this database type
434 $class = 'Database' . ucfirst( $type );
435 if ( !class_exists( $class ) ) {
436 require_once( "$class.php" );
440 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
441 $db->setLBInfo( $server );
445 function reportConnectionError( &$conn )
447 $fname = 'LoadBalancer::reportConnectionError';
448 wfProfileIn( $fname );
449 # Prevent infinite recursion
451 static $reporting = false;
454 if ( !is_object( $conn ) ) {
455 // No last connection, probably due to all servers being too busy
456 $conn = new Database
;
457 if ( $this->mFailFunction
) {
458 $conn->failFunction( $this->mFailFunction
);
459 $conn->reportConnectionError( $this->mLastError
);
461 // If all servers were busy, mLastError will contain something sensible
462 wfEmergencyAbort( $conn, $this->mLastError
);
465 if ( $this->mFailFunction
) {
466 $conn->failFunction( $this->mFailFunction
);
468 $conn->failFunction( false );
470 $conn->reportConnectionError( "{$this->mLastError} ({$conn->mServer})" );
474 wfProfileOut( $fname );
477 function getWriterIndex()
487 function haveIndex( $i )
489 return array_key_exists( $i, $this->mServers
);
493 * Get the number of defined servers (not the number of open connections)
495 function getServerCount() {
496 return count( $this->mServers
);
500 * Save master pos to the session and to memcached, if the session exists
502 function saveMasterPos() {
503 global $wgSessionStarted;
504 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
505 # If this entire request was served from a slave without opening a connection to the
506 # master (however unlikely that may be), then we can fetch the position from the slave.
507 if ( empty( $this->mConnections
[0] ) ) {
508 $conn =& $this->getConnection( DB_SLAVE
);
509 list( $file, $pos ) = $conn->getSlavePos();
510 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
512 $conn =& $this->getConnection( 0 );
513 list( $file, $pos ) = $conn->getMasterPos();
514 wfDebug( "Saving master pos: $file $pos\n" );
516 if ( $file !== false ) {
517 $_SESSION['master_log_file'] = $file;
518 $_SESSION['master_pos'] = $pos;
524 * Loads the master pos from the session, waits for it if necessary
526 function loadMasterPos() {
527 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
528 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
533 * Close all open connections
535 function closeAll() {
536 foreach( $this->mConnections
as $i => $conn ) {
537 if ( $this->isOpen( $i ) ) {
538 // Need to use this syntax because $conn is a copy not a reference
539 $this->mConnections
[$i]->close();
544 function commitAll() {
545 foreach( $this->mConnections
as $i => $conn ) {
546 if ( $this->isOpen( $i ) ) {
547 // Need to use this syntax because $conn is a copy not a reference
548 $this->mConnections
[$i]->immediateCommit();
553 function waitTimeout( $value = NULL ) {
554 return wfSetVar( $this->mWaitTimeout
, $value );
557 function getLaggedSlaveMode() {
558 return $this->mLaggedSlaveMode
;
563 foreach ( $this->mConnections
as $i => $conn ) {
564 if ( $this->isOpen( $i ) ) {
565 if ( !$this->mConnections
[$i]->ping() ) {
574 * Get the hostname and lag time of the most-lagged slave
575 * This is useful for maintenance scripts that need to throttle their updates
577 function getMaxLag() {
580 foreach ( $this->mServers
as $i => $conn ) {
581 if ( $this->openConnection( $i ) ) {
582 $lag = $this->mConnections
[$i]->getLag();
583 if ( $lag > $maxLag ) {
585 $host = $this->mServers
[$i]['host'];
589 return array( $host, $maxLag );
593 * Get lag time for each DB
594 * Results are cached for a short time in memcached
596 function getLagTimes() {
603 $times = $wgMemc->get( "$wgDBname:lag_times" );
605 # Randomly recache with probability rising over $expiry
606 $elapsed = time() - $times['timestamp'];
607 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
608 if ( mt_rand( 0, $chance ) != 0 ) {
609 unset( $times['timestamp'] );
614 # Cache key missing or expired
617 foreach ( $this->mServers
as $i => $conn ) {
618 if ( $this->openConnection( $i ) ) {
619 $times[$i] = $this->mConnections
[$i]->getLag();
623 # Add a timestamp key so we know when it was cached
624 $times['timestamp'] = time();
625 $wgMemc->set( "$wgDBname:lag_times", $times, $expiry );
627 # But don't give the timestamp to the caller
628 unset($times['timestamp']);