c6f6f1521d35efec74a6ec4035faa49b927d0453
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;
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
< $this->mWaitTimeout
);
211 if ( $i !== false && $this->isOpen( $i ) ) {
212 $this->mReadIndex
= $i;
218 wfProfileOut( $fname );
223 * Get a random server to use in a query group
225 function getGroupIndex( $group ) {
226 if ( isset( $this->mGroupLoads
[$group] ) ) {
227 $i = $this->pickRandom( $this->mGroupLoads
[$group] );
231 wfDebug( "Query group $group => $i\n" );
236 * Set the master wait position
237 * If a DB_SLAVE connection has been opened already, waits
238 * Otherwise sets a variable telling it to wait if such a connection is opened
240 function waitFor( $file, $pos ) {
242 $fname = 'LoadBalancer::waitFor';
243 wfProfileIn( $fname );
245 wfDebug( "User master pos: $file $pos\n" );
246 $this->mWaitForFile = false;
247 $this->mWaitForPos = false;
249 if ( count( $this->mServers ) > 1 ) {
250 $this->mWaitForFile = $file;
251 $this->mWaitForPos = $pos;
252 $i = $this->mReadIndex;
255 if ( !$this->doWait( $i ) ) {
256 $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
257 $this->mLaggedSlaveMode = true;
261 wfProfileOut( $fname );
266 * Wait for a given slave to catch up to the master pos stored in $this
268 function doWait( $index ) {
276 if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
278 } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
282 $key = 'masterpos:' . $index;
283 $memcPos = $wgMemc->get( $key );
285 list( $file, $pos ) = explode( ' ', $memcPos );
286 # If the saved position is later than the requested position, return now
287 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
292 if ( !$retVal && $this->isOpen( $index ) ) {
293 $conn =& $this->mConnections[$index];
294 wfDebug( "Waiting for slave #$index to catch up...\n" );
295 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
297 if ( $result == -1 || is_null( $result ) ) {
298 # Timed out waiting for slave, use master instead
299 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
310 * Get a connection by index
312 function &getConnection( $i, $fail = true, $groups = array() )
314 $fname = 'LoadBalancer::getConnection';
315 wfProfileIn( $fname );
319 foreach ( $groups as $group ) {
320 $groupIndex = $this->getGroupIndex( $group );
321 if ( $groupIndex !== false ) {
327 # Operation-based index
328 if ( $i == DB_SLAVE
) {
329 $i = $this->getReaderIndex();
330 } elseif ( $i == DB_MASTER
) {
331 $i = $this->getWriterIndex();
332 } elseif ( $i == DB_LAST
) {
333 # Just use $this->mLastIndex, which should already be set
334 $i = $this->mLastIndex
;
336 # Oh dear, not set, best to use the writer for safety
337 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
338 $i = $this->getWriterIndex();
341 # Now we have an explicit index into the servers array
342 $this->openConnection( $i, $fail );
344 wfProfileOut( $fname );
345 return $this->mConnections
[$i];
349 * Open a connection to the server given by the specified index
350 * Index must be an actual index into the array
354 function openConnection( $i, $fail = false ) {
355 $fname = 'LoadBalancer::openConnection';
356 wfProfileIn( $fname );
359 if ( !$this->isOpen( $i ) ) {
360 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
362 if ( $this->isOpen( $i ) && $i != 0 && $this->mWaitForFile
) {
363 if ( !$this->doWait( $i ) ) {
364 $this->mServers
[$i]['slave pos'] = $this->mConnections
[$i]->getSlavePos();
369 if ( !$this->isOpen( $i ) ) {
370 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
372 $this->reportConnectionError( $this->mConnections
[$i] );
374 $this->mConnections
[$i] = false;
377 $this->mLastIndex
= $i;
378 wfProfileOut( $fname );
383 * Test if the specified index represents an open connection
386 function isOpen( $index ) {
387 if( !is_integer( $index ) ) {
390 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
391 $this->mConnections
[$index]->isOpen() )
400 * Really opens a connection
403 function reallyOpenConnection( &$server ) {
404 if( !is_array( $server ) ) {
405 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
409 # Get class for this database type
410 $class = 'Database' . ucfirst( $type );
411 if ( !class_exists( $class ) ) {
412 require_once( "$class.php" );
416 return new $class( $host, $user, $password, $dbname, 1, $flags );
419 function reportConnectionError( &$conn )
421 $fname = 'LoadBalancer::reportConnectionError';
422 wfProfileIn( $fname );
423 # Prevent infinite recursion
425 static $reporting = false;
428 if ( !is_object( $conn ) ) {
429 $conn = new Database
;
431 if ( $this->mFailFunction
) {
432 $conn->failFunction( $this->mFailFunction
);
434 $conn->failFunction( 'wfEmergencyAbort' );
436 $conn->reportConnectionError();
439 wfProfileOut( $fname );
442 function getWriterIndex()
452 function haveIndex( $i )
454 return array_key_exists( $i, $this->mServers
);
458 * Get the number of defined servers (not the number of open connections)
460 function getServerCount() {
461 return count( $this->mServers
);
465 * Save master pos to the session and to memcached, if the session exists
467 function saveMasterPos() {
468 global $wgSessionStarted;
469 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
470 # If this entire request was served from a slave without opening a connection to the
471 # master (however unlikely that may be), then we can fetch the position from the slave.
472 if ( empty( $this->mConnections
[0] ) ) {
473 $conn =& $this->getConnection( DB_SLAVE
);
474 list( $file, $pos ) = $conn->getSlavePos();
475 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
477 $conn =& $this->getConnection( 0 );
478 list( $file, $pos ) = $conn->getMasterPos();
479 wfDebug( "Saving master pos: $file $pos\n" );
481 if ( $file !== false ) {
482 $_SESSION['master_log_file'] = $file;
483 $_SESSION['master_pos'] = $pos;
489 * Loads the master pos from the session, waits for it if necessary
491 function loadMasterPos() {
492 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
493 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
498 * Close all open connections
500 function closeAll() {
501 foreach( $this->mConnections
as $i => $conn ) {
502 if ( $this->isOpen( $i ) ) {
503 // Need to use this syntax because $conn is a copy not a reference
504 $this->mConnections
[$i]->close();
509 function commitAll() {
510 foreach( $this->mConnections
as $i => $conn ) {
511 if ( $this->isOpen( $i ) ) {
512 // Need to use this syntax because $conn is a copy not a reference
513 $this->mConnections
[$i]->immediateCommit();
518 function waitTimeout( $value = NULL ) {
519 return wfSetVar( $this->mWaitTimeout
, $value );
522 function getLaggedSlaveMode() {
523 return $this->mLaggedSlaveMode
;
528 foreach ( $this->mConnections
as $i => $conn ) {
529 if ( $this->isOpen( $i ) ) {
530 if ( !$this->mConnections
[$i]->ping() ) {
539 * Get the hostname and lag time of the most-lagged slave
540 * This is useful for maintenance scripts that need to throttle their updates
542 function getMaxLag() {
545 foreach ( $this->mServers
as $i => $conn ) {
546 if ( $this->openConnection( $i ) ) {
547 $lag = $this->mConnections
[$i]->getLag();
548 if ( $lag > $maxLag ) {
550 $host = $this->mServers
[$i]['host'];
554 return array( $host, $maxLag );
558 * Get lag time for each DB
559 * Results are cached for a short time in memcached
561 function getLagTimes() {
566 $times = $wgMemc->get( 'lag_times' );
568 # Randomly recache with probability rising over $expiry
569 $elapsed = time() - $times['timestamp'];
570 $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
571 if ( mt_rand( 0, $chance ) != 0 ) {
572 unset( $times['timestamp'] );
577 # Cache key missing or expired
580 foreach ( $this->mServers
as $i => $conn ) {
581 if ( $this->openConnection( $i ) ) {
582 $times[$i] = $this->mConnections
[$i]->getLag();
586 # Add a timestamp key so we know when it was cached
587 $times['timestamp'] = time();
588 $wgMemc->set( 'lag_times', $times, $expiry );
590 # But don't give the timestamp to the caller
591 unset($times['timestamp']);