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 * Database load balancing object
29 /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
30 /* private */ var $mFailFunction;
31 /* private */ var $mForce, $mReadIndex, $mLastIndex;
32 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
33 /* private */ var $mLaggedSlaveMode;
35 function LoadBalancer()
37 $this->mServers
= array();
38 $this->mConnections
= array();
39 $this->mFailFunction
= false;
40 $this->mReadIndex
= -1;
42 $this->mLastIndex
= -1;
45 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
47 $lb = new LoadBalancer
;
48 $lb->initialise( $servers, $failFunction, $waitTimeout );
52 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
54 $this->mServers
= $servers;
55 $this->mFailFunction
= $failFunction;
56 $this->mReadIndex
= -1;
57 $this->mWriteIndex
= -1;
59 $this->mConnections
= array();
60 $this->mLastIndex
= 1;
61 $this->mLoads
= array();
62 $this->mWaitForFile
= false;
63 $this->mWaitForPos
= false;
64 $this->mWaitTimeout
= $waitTimeout;
65 $this->mLaggedSlaveMode
= false;
67 foreach( $servers as $i => $server ) {
68 $this->mLoads
[$i] = $server['load'];
69 if ( isset( $server['groupLoads'] ) ) {
70 foreach ( $server['groupLoads'] as $group => $ratio ) {
71 if ( !isset( $this->mGroupLoads
[$group] ) ) {
72 $this->mGroupLoads
[$group] = array();
74 $this->mGroupLoads
[$group][$i] = $ratio;
81 * Given an array of non-normalised probabilities, this function will select
82 * an element and return the appropriate key
84 function pickRandom( $weights )
86 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
91 foreach ( $weights as $w ) {
96 # No loads on any of them
97 # Just pick one at random
98 foreach ( $weights as $i => $w ) {
102 $max = mt_getrandmax();
103 $rand = mt_rand(0, $max) / $max * $sum;
106 foreach ( $weights as $i => $w ) {
108 if ( $sum >= $rand ) {
115 function getRandomNonLagged( $loads ) {
116 # Unset excessively lagged servers
117 $lags = $this->getLagTimes();
118 foreach ( $lags as $i => $lag ) {
119 if ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
125 # Find out if all the slaves with non-zero load are lagged
127 foreach ( $loads as $load ) {
131 # No appropriate DB servers except maybe the master and some slaves with zero load
132 # Do NOT use the master
133 # Instead, this function will return false, triggering read-only mode,
134 # and a lagged slave will be used instead.
138 if ( count( $loads ) == 0 ) {
142 #wfDebug( var_export( $loads, true ) );
144 # Return a random representative of the remainder
145 return $this->pickRandom( $loads );
149 function getReaderIndex()
151 global $wgMaxLag, $wgReadOnly, $wgDBClusterTimeout;
153 $fname = 'LoadBalancer::getReaderIndex';
154 wfProfileIn( $fname );
157 if ( $this->mForce
>= 0 ) {
160 if ( $this->mReadIndex
>= 0 ) {
161 $i = $this->mReadIndex
;
163 # $loads is $this->mLoads except with elements knocked out if they
165 $loads = $this->mLoads
;
170 $i = $this->pickRandom( $loads );
172 $i = $this->getRandomNonLagged( $loads );
173 if ( $i === false && count( $loads ) != 0 ) {
174 # All slaves lagged. Switch to read-only mode
175 $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
176 $i = $this->pickRandom( $loads );
179 if ( $i !== false ) {
180 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}...\n" );
181 $this->openConnection( $i );
183 if ( !$this->isOpen( $i ) ) {
184 wfDebug( "Failed\n" );
188 $status = $this->mConnections
[$i]->getStatus();
189 if ( isset( $this->mServers
[$i]['max threads'] ) &&
190 $status['Threads_running'] > $this->mServers
[$i]['max threads'] )
192 # Slave is lagged, wait for a while
193 $sleepTime = 5000 * $status['Threads_connected'];
195 # If we reach the timeout and exit the loop, don't use it
206 $totalElapsed +
= $sleepTime;
207 usleep( $sleepTime );
209 } while ( count( $loads ) && !$done && $totalElapsed / 1e6
< $wgDBClusterTimeout );
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();
219 $this->mReadIndex
= $i;
226 wfProfileOut( $fname );
231 * Get a random server to use in a query group
233 function getGroupIndex( $group ) {
234 if ( isset( $this->mGroupLoads
[$group] ) ) {
235 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
239 wfDebug( "Query group $group => $i\n" );
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
248 function waitFor( $file, $pos ) {
249 $fname = 'LoadBalancer::waitFor';
250 wfProfileIn( $fname );
252 wfDebug( "User master pos: $file $pos\n" );
253 $this->mWaitForFile
= false;
254 $this->mWaitForPos
= false;
256 if ( count( $this->mServers
) > 1 ) {
257 $this->mWaitForFile
= $file;
258 $this->mWaitForPos
= $pos;
259 $i = $this->mReadIndex
;
262 if ( !$this->doWait( $i ) ) {
263 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
264 $this->mLaggedSlaveMode
= true;
268 wfProfileOut( $fname );
272 * Wait for a given slave to catch up to the master pos stored in $this
274 function doWait( $index ) {
280 if ( isset( $this->mServers
[$index]['lagged slave'] ) ) {
282 } elseif ( isset( $this->mServers
[$index]['fake slave'] ) ) {
286 $key = 'masterpos:' . $index;
287 $memcPos = $wgMemc->get( $key );
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 ) {
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
);
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" );
314 * Get a connection by index
316 function &getConnection( $i, $fail = true, $groups = array() )
318 $fname = 'LoadBalancer::getConnection';
319 wfProfileIn( $fname );
323 foreach ( $groups as $group ) {
324 $groupIndex = $this->getGroupIndex( $group );
325 if ( $groupIndex !== false ) {
331 # Operation-based index
332 if ( $i == DB_SLAVE
) {
333 $i = $this->getReaderIndex();
334 } elseif ( $i == DB_MASTER
) {
335 $i = $this->getWriterIndex();
336 } elseif ( $i == DB_LAST
) {
337 # Just use $this->mLastIndex, which should already be set
338 $i = $this->mLastIndex
;
340 # Oh dear, not set, best to use the writer for safety
341 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
342 $i = $this->getWriterIndex();
345 # Now we have an explicit index into the servers array
346 $this->openConnection( $i, $fail );
348 wfProfileOut( $fname );
349 return $this->mConnections
[$i];
353 * Open a connection to the server given by the specified index
354 * Index must be an actual index into the array
358 function openConnection( $i, $fail = false ) {
359 $fname = 'LoadBalancer::openConnection';
360 wfProfileIn( $fname );
363 if ( !$this->isOpen( $i ) ) {
364 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
366 if ( !$this->isOpen( $i ) ) {
367 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
369 $this->reportConnectionError( $this->mConnections
[$i] );
371 $this->mConnections
[$i] = false;
374 $this->mLastIndex
= $i;
375 wfProfileOut( $fname );
380 * Test if the specified index represents an open connection
383 function isOpen( $index ) {
384 if( !is_integer( $index ) ) {
387 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
388 $this->mConnections
[$index]->isOpen() )
397 * Really opens a connection
400 function reallyOpenConnection( &$server ) {
401 if( !is_array( $server ) ) {
402 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
406 # Get class for this database type
407 $class = 'Database' . ucfirst( $type );
408 if ( !class_exists( $class ) ) {
409 require_once( "$class.php" );
413 return new $class( $host, $user, $password, $dbname, 1, $flags );
416 function reportConnectionError( &$conn )
418 $fname = 'LoadBalancer::reportConnectionError';
419 wfProfileIn( $fname );
420 # Prevent infinite recursion
422 static $reporting = false;
425 if ( !is_object( $conn ) ) {
426 $conn = new Database
;
428 if ( $this->mFailFunction
) {
429 $conn->failFunction( $this->mFailFunction
);
431 $conn->failFunction( 'wfEmergencyAbort' );
433 $conn->reportConnectionError();
436 wfProfileOut( $fname );
439 function getWriterIndex()
449 function haveIndex( $i )
451 return array_key_exists( $i, $this->mServers
);
455 * Get the number of defined servers (not the number of open connections)
457 function getServerCount() {
458 return count( $this->mServers
);
462 * Save master pos to the session and to memcached, if the session exists
464 function saveMasterPos() {
465 global $wgSessionStarted;
466 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
467 # If this entire request was served from a slave without opening a connection to the
468 # master (however unlikely that may be), then we can fetch the position from the slave.
469 if ( empty( $this->mConnections
[0] ) ) {
470 $conn =& $this->getConnection( DB_SLAVE
);
471 list( $file, $pos ) = $conn->getSlavePos();
472 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
474 $conn =& $this->getConnection( 0 );
475 list( $file, $pos ) = $conn->getMasterPos();
476 wfDebug( "Saving master pos: $file $pos\n" );
478 if ( $file !== false ) {
479 $_SESSION['master_log_file'] = $file;
480 $_SESSION['master_pos'] = $pos;
486 * Loads the master pos from the session, waits for it if necessary
488 function loadMasterPos() {
489 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
490 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
495 * Close all open connections
497 function closeAll() {
498 foreach( $this->mConnections
as $i => $conn ) {
499 if ( $this->isOpen( $i ) ) {
500 // Need to use this syntax because $conn is a copy not a reference
501 $this->mConnections
[$i]->close();
506 function commitAll() {
507 foreach( $this->mConnections
as $i => $conn ) {
508 if ( $this->isOpen( $i ) ) {
509 // Need to use this syntax because $conn is a copy not a reference
510 $this->mConnections
[$i]->immediateCommit();
515 function waitTimeout( $value = NULL ) {
516 return wfSetVar( $this->mWaitTimeout
, $value );
519 function getLaggedSlaveMode() {
520 return $this->mLaggedSlaveMode
;
525 foreach ( $this->mConnections
as $i => $conn ) {
526 if ( $this->isOpen( $i ) ) {
527 if ( !$this->mConnections
[$i]->ping() ) {
536 * Get the hostname and lag time of the most-lagged slave
537 * This is useful for maintenance scripts that need to throttle their updates
539 function getMaxLag() {
542 foreach ( $this->mServers
as $i => $conn ) {
543 if ( $this->openConnection( $i ) ) {
544 $lag = $this->mConnections
[$i]->getLag();
545 if ( $lag > $maxLag ) {
547 $host = $this->mServers
[$i]['host'];
551 return array( $host, $maxLag );
555 * Get lag time for each DB
556 * Results are cached for a short time in memcached
558 function getLagTimes() {
563 $times = $wgMemc->get( 'lag_times' );
565 # Randomly recache with probability rising over $expiry
566 $elapsed = time() - $times['timestamp'];
567 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
568 if ( mt_rand( 0, $chance ) != 0 ) {
569 unset( $times['timestamp'] );
574 # Cache key missing or expired
577 foreach ( $this->mServers
as $i => $conn ) {
578 if ( $this->openConnection( $i ) ) {
579 $times[$i] = $this->mConnections
[$i]->getLag();
583 # Add a timestamp key so we know when it was cached
584 $times['timestamp'] = time();
585 $wgMemc->set( 'lag_times', $times, $expiry );
587 # But don't give the timestamp to the caller
588 unset($times['timestamp']);