Merge "Declare visibility on class properties of RecentChange"
[mediawiki.git] / includes / db / LoadBalancer.php
blob857109db268ae04eef4a374ecd6346d6ddcdb28c
1 <?php
2 /**
3 * Database load balancing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Database
24 /**
25 * Database load balancing object
27 * @todo document
28 * @ingroup Database
30 class LoadBalancer {
31 private $mServers, $mConns, $mLoads, $mGroupLoads;
32 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
39 /**
40 * @param array $params with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
44 * @throws MWException
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__ . ': missing servers parameter' );
50 $this->mServers = $params['servers'];
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout = $params['waitTimeout'];
54 } else {
55 $this->mWaitTimeout = 10;
58 $this->mReadIndex = -1;
59 $this->mWriteIndex = -1;
60 $this->mConns = array(
61 'local' => array(),
62 'foreignUsed' => array(),
63 'foreignFree' => array() );
64 $this->mLoads = array();
65 $this->mWaitForPos = false;
66 $this->mLaggedSlaveMode = false;
67 $this->mErrorConnection = false;
68 $this->mAllowLagged = false;
70 if ( isset( $params['loadMonitor'] ) ) {
71 $this->mLoadMonitorClass = $params['loadMonitor'];
72 } else {
73 $master = reset( $params['servers'] );
74 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
75 $this->mLoadMonitorClass = 'LoadMonitor_MySQL';
76 } else {
77 $this->mLoadMonitorClass = 'LoadMonitor_Null';
81 foreach ( $params['servers'] as $i => $server ) {
82 $this->mLoads[$i] = $server['load'];
83 if ( isset( $server['groupLoads'] ) ) {
84 foreach ( $server['groupLoads'] as $group => $ratio ) {
85 if ( !isset( $this->mGroupLoads[$group] ) ) {
86 $this->mGroupLoads[$group] = array();
88 $this->mGroupLoads[$group][$i] = $ratio;
94 /**
95 * Get a LoadMonitor instance
97 * @return LoadMonitor
99 function getLoadMonitor() {
100 if ( !isset( $this->mLoadMonitor ) ) {
101 $class = $this->mLoadMonitorClass;
102 $this->mLoadMonitor = new $class( $this );
104 return $this->mLoadMonitor;
108 * Get or set arbitrary data used by the parent object, usually an LBFactory
109 * @param $x
110 * @return Mixed
112 function parentInfo( $x = null ) {
113 return wfSetVar( $this->mParentInfo, $x );
117 * Given an array of non-normalised probabilities, this function will select
118 * an element and return the appropriate key
120 * @deprecated since 1.21, use ArrayUtils::pickRandom()
122 * @param $weights array
124 * @return bool|int|string
126 function pickRandom( $weights ) {
127 return ArrayUtils::pickRandom( $weights );
131 * @param $loads array
132 * @param $wiki bool
133 * @return bool|int|string
135 function getRandomNonLagged( $loads, $wiki = false ) {
136 # Unset excessively lagged servers
137 $lags = $this->getLagTimes( $wiki );
138 foreach ( $lags as $i => $lag ) {
139 if ( $i != 0 ) {
140 if ( $lag === false ) {
141 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
142 unset( $loads[$i] );
143 } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
144 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
145 unset( $loads[$i] );
150 # Find out if all the slaves with non-zero load are lagged
151 $sum = 0;
152 foreach ( $loads as $load ) {
153 $sum += $load;
155 if ( $sum == 0 ) {
156 # No appropriate DB servers except maybe the master and some slaves with zero load
157 # Do NOT use the master
158 # Instead, this function will return false, triggering read-only mode,
159 # and a lagged slave will be used instead.
160 return false;
163 if ( count( $loads ) == 0 ) {
164 return false;
167 #wfDebugLog( 'connect', var_export( $loads, true ) );
169 # Return a random representative of the remainder
170 return ArrayUtils::pickRandom( $loads );
174 * Get the index of the reader connection, which may be a slave
175 * This takes into account load ratios and lag times. It should
176 * always return a consistent index during a given invocation
178 * Side effect: opens connections to databases
179 * @param $group bool
180 * @param $wiki bool
181 * @throws MWException
182 * @return bool|int|string
184 function getReaderIndex( $group = false, $wiki = false ) {
185 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
187 # @todo FIXME: For now, only go through all this for mysql databases
188 if ( $wgDBtype != 'mysql' ) {
189 return $this->getWriterIndex();
192 if ( count( $this->mServers ) == 1 ) {
193 # Skip the load balancing if there's only one server
194 return 0;
195 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
196 # Shortcut if generic reader exists already
197 return $this->mReadIndex;
200 wfProfileIn( __METHOD__ );
202 $totalElapsed = 0;
204 # convert from seconds to microseconds
205 $timeout = $wgDBClusterTimeout * 1e6;
207 # Find the relevant load array
208 if ( $group !== false ) {
209 if ( isset( $this->mGroupLoads[$group] ) ) {
210 $nonErrorLoads = $this->mGroupLoads[$group];
211 } else {
212 # No loads for this group, return false and the caller can use some other group
213 wfDebug( __METHOD__ . ": no loads for group $group\n" );
214 wfProfileOut( __METHOD__ );
215 return false;
217 } else {
218 $nonErrorLoads = $this->mLoads;
221 if ( !$nonErrorLoads ) {
222 wfProfileOut( __METHOD__ );
223 throw new MWException( "Empty server array given to LoadBalancer" );
226 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
227 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
229 $laggedSlaveMode = false;
231 # First try quickly looking through the available servers for a server that
232 # meets our criteria
233 do {
234 $totalThreadsConnected = 0;
235 $overloadedServers = 0;
236 $currentLoads = $nonErrorLoads;
237 while ( count( $currentLoads ) ) {
238 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
239 $i = ArrayUtils::pickRandom( $currentLoads );
240 } else {
241 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
242 if ( $i === false && count( $currentLoads ) != 0 ) {
243 # All slaves lagged. Switch to read-only mode
244 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
245 $wgReadOnly = 'The database has been automatically locked ' .
246 'while the slave database servers catch up to the master';
247 $i = ArrayUtils::pickRandom( $currentLoads );
248 $laggedSlaveMode = true;
252 if ( $i === false ) {
253 # pickRandom() returned false
254 # This is permanent and means the configuration or the load monitor
255 # wants us to return false.
256 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false\n" );
257 wfProfileOut( __METHOD__ );
258 return false;
261 wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
262 $conn = $this->openConnection( $i, $wiki );
264 if ( !$conn ) {
265 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki\n" );
266 unset( $nonErrorLoads[$i] );
267 unset( $currentLoads[$i] );
268 continue;
271 // Perform post-connection backoff
272 $threshold = isset( $this->mServers[$i]['max threads'] )
273 ? $this->mServers[$i]['max threads'] : false;
274 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
276 // Decrement reference counter, we are finished with this connection.
277 // It will be incremented for the caller later.
278 if ( $wiki !== false ) {
279 $this->reuseConnection( $conn );
282 if ( $backoff ) {
283 # Post-connection overload, don't use this server for now
284 $totalThreadsConnected += $backoff;
285 $overloadedServers++;
286 unset( $currentLoads[$i] );
287 } else {
288 # Return this server
289 break 2;
293 # No server found yet
294 $i = false;
296 # If all servers were down, quit now
297 if ( !count( $nonErrorLoads ) ) {
298 wfDebugLog( 'connect', "All servers down\n" );
299 break;
302 # Some servers must have been overloaded
303 if ( $overloadedServers == 0 ) {
304 throw new MWException( __METHOD__ . ": unexpectedly found no overloaded servers" );
306 # Back off for a while
307 # Scale the sleep time by the number of connected threads, to produce a
308 # roughly constant global poll rate
309 $avgThreads = $totalThreadsConnected / $overloadedServers;
310 $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
311 } while ( $totalElapsed < $timeout );
313 if ( $totalElapsed >= $timeout ) {
314 wfDebugLog( 'connect', "All servers busy\n" );
315 $this->mErrorConnection = false;
316 $this->mLastError = 'All servers busy';
319 if ( $i !== false ) {
320 # Slave connection successful
321 # Wait for the session master pos for a short time
322 if ( $this->mWaitForPos && $i > 0 ) {
323 if ( !$this->doWait( $i ) ) {
324 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
327 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $i !== false ) {
328 $this->mReadIndex = $i;
331 wfProfileOut( __METHOD__ );
332 return $i;
336 * Wait for a specified number of microseconds, and return the period waited
337 * @param $t int
338 * @return int
340 function sleep( $t ) {
341 wfProfileIn( __METHOD__ );
342 wfDebug( __METHOD__ . ": waiting $t us\n" );
343 usleep( $t );
344 wfProfileOut( __METHOD__ );
345 return $t;
349 * Set the master wait position
350 * If a DB_SLAVE connection has been opened already, waits
351 * Otherwise sets a variable telling it to wait if such a connection is opened
352 * @param $pos DBMasterPos
354 public function waitFor( $pos ) {
355 wfProfileIn( __METHOD__ );
356 $this->mWaitForPos = $pos;
357 $i = $this->mReadIndex;
359 if ( $i > 0 ) {
360 if ( !$this->doWait( $i ) ) {
361 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
362 $this->mLaggedSlaveMode = true;
365 wfProfileOut( __METHOD__ );
369 * Set the master wait position and wait for ALL slaves to catch up to it
370 * @param $pos DBMasterPos
372 public function waitForAll( $pos ) {
373 wfProfileIn( __METHOD__ );
374 $this->mWaitForPos = $pos;
375 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
376 $this->doWait( $i, true );
378 wfProfileOut( __METHOD__ );
382 * Get any open connection to a given server index, local or foreign
383 * Returns false if there is no connection open
385 * @param $i int
386 * @return DatabaseBase|bool False on failure
388 function getAnyOpenConnection( $i ) {
389 foreach ( $this->mConns as $conns ) {
390 if ( !empty( $conns[$i] ) ) {
391 return reset( $conns[$i] );
394 return false;
398 * Wait for a given slave to catch up to the master pos stored in $this
399 * @param $index
400 * @param $open bool
401 * @return bool
403 protected function doWait( $index, $open = false ) {
404 # Find a connection to wait on
405 $conn = $this->getAnyOpenConnection( $index );
406 if ( !$conn ) {
407 if ( !$open ) {
408 wfDebug( __METHOD__ . ": no connection open\n" );
409 return false;
410 } else {
411 $conn = $this->openConnection( $index, '' );
412 if ( !$conn ) {
413 wfDebug( __METHOD__ . ": failed to open connection\n" );
414 return false;
419 wfDebug( __METHOD__ . ": Waiting for slave #$index to catch up...\n" );
420 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
422 if ( $result == -1 || is_null( $result ) ) {
423 # Timed out waiting for slave, use master instead
424 wfDebug( __METHOD__ . ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
425 return false;
426 } else {
427 wfDebug( __METHOD__ . ": Done\n" );
428 return true;
433 * Get a connection by index
434 * This is the main entry point for this class.
436 * @param $i Integer: server index
437 * @param array $groups query groups
438 * @param bool|string $wiki Wiki ID
440 * @throws MWException
441 * @return DatabaseBase
443 public function &getConnection( $i, $groups = array(), $wiki = false ) {
444 wfProfileIn( __METHOD__ );
446 if ( $i == DB_LAST ) {
447 wfProfileOut( __METHOD__ );
448 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
449 } elseif ( $i === null || $i === false ) {
450 wfProfileOut( __METHOD__ );
451 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
454 if ( $wiki === wfWikiID() ) {
455 $wiki = false;
458 # Query groups
459 if ( $i == DB_MASTER ) {
460 $i = $this->getWriterIndex();
461 } elseif ( !is_array( $groups ) ) {
462 $groupIndex = $this->getReaderIndex( $groups, $wiki );
463 if ( $groupIndex !== false ) {
464 $serverName = $this->getServerName( $groupIndex );
465 wfDebug( __METHOD__ . ": using server $serverName for group $groups\n" );
466 $i = $groupIndex;
468 } else {
469 foreach ( $groups as $group ) {
470 $groupIndex = $this->getReaderIndex( $group, $wiki );
471 if ( $groupIndex !== false ) {
472 $serverName = $this->getServerName( $groupIndex );
473 wfDebug( __METHOD__ . ": using server $serverName for group $group\n" );
474 $i = $groupIndex;
475 break;
480 # Operation-based index
481 if ( $i == DB_SLAVE ) {
482 $this->mLastError = 'Unknown error'; // reset error string
483 $i = $this->getReaderIndex( false, $wiki );
484 # Couldn't find a working server in getReaderIndex()?
485 if ( $i === false ) {
486 $this->mLastError = 'No working slave server: ' . $this->mLastError;
487 wfProfileOut( __METHOD__ );
488 return $this->reportConnectionError();
492 # Now we have an explicit index into the servers array
493 $conn = $this->openConnection( $i, $wiki );
494 if ( !$conn ) {
495 wfProfileOut( __METHOD__ );
496 return $this->reportConnectionError();
499 wfProfileOut( __METHOD__ );
500 return $conn;
504 * Mark a foreign connection as being available for reuse under a different
505 * DB name or prefix. This mechanism is reference-counted, and must be called
506 * the same number of times as getConnection() to work.
508 * @param DatabaseBase $conn
509 * @throws MWException
511 public function reuseConnection( $conn ) {
512 $serverIndex = $conn->getLBInfo( 'serverIndex' );
513 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
514 $dbName = $conn->getDBname();
515 $prefix = $conn->tablePrefix();
516 if ( strval( $prefix ) !== '' ) {
517 $wiki = "$dbName-$prefix";
518 } else {
519 $wiki = $dbName;
521 if ( $serverIndex === null || $refCount === null ) {
522 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
524 * This can happen in code like:
525 * foreach ( $dbs as $db ) {
526 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
527 * ...
528 * $lb->reuseConnection( $conn );
530 * When a connection to the local DB is opened in this way, reuseConnection()
531 * should be ignored
533 return;
535 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
536 throw new MWException( __METHOD__ . ": connection not found, has the connection been freed already?" );
538 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
539 if ( $refCount <= 0 ) {
540 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
541 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
542 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
543 } else {
544 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
549 * Get a database connection handle reference
551 * The handle's methods wrap simply wrap those of a DatabaseBase handle
553 * @see LoadBalancer::getConnection() for parameter information
555 * @param integer $db
556 * @param mixed $groups
557 * @param string $wiki
558 * @return DBConnRef
560 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
561 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
565 * Get a database connection handle reference without connecting yet
567 * The handle's methods wrap simply wrap those of a DatabaseBase handle
569 * @see LoadBalancer::getConnection() for parameter information
571 * @param integer $db
572 * @param mixed $groups
573 * @param string $wiki
574 * @return DBConnRef
576 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
577 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
581 * Open a connection to the server given by the specified index
582 * Index must be an actual index into the array.
583 * If the server is already open, returns it.
585 * On error, returns false, and the connection which caused the
586 * error will be available via $this->mErrorConnection.
588 * @param $i Integer server index
589 * @param string $wiki wiki ID to open
590 * @return DatabaseBase
592 * @access private
594 function openConnection( $i, $wiki = false ) {
595 wfProfileIn( __METHOD__ );
596 if ( $wiki !== false ) {
597 $conn = $this->openForeignConnection( $i, $wiki );
598 wfProfileOut( __METHOD__ );
599 return $conn;
601 if ( isset( $this->mConns['local'][$i][0] ) ) {
602 $conn = $this->mConns['local'][$i][0];
603 } else {
604 $server = $this->mServers[$i];
605 $server['serverIndex'] = $i;
606 $conn = $this->reallyOpenConnection( $server, false );
607 if ( $conn->isOpen() ) {
608 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
609 $this->mConns['local'][$i][0] = $conn;
610 } else {
611 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
612 $this->mErrorConnection = $conn;
613 $conn = false;
616 wfProfileOut( __METHOD__ );
617 return $conn;
621 * Open a connection to a foreign DB, or return one if it is already open.
623 * Increments a reference count on the returned connection which locks the
624 * connection to the requested wiki. This reference count can be
625 * decremented by calling reuseConnection().
627 * If a connection is open to the appropriate server already, but with the wrong
628 * database, it will be switched to the right database and returned, as long as
629 * it has been freed first with reuseConnection().
631 * On error, returns false, and the connection which caused the
632 * error will be available via $this->mErrorConnection.
634 * @param $i Integer: server index
635 * @param string $wiki wiki ID to open
636 * @return DatabaseBase
638 function openForeignConnection( $i, $wiki ) {
639 wfProfileIn( __METHOD__ );
640 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
641 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
642 // Reuse an already-used connection
643 $conn = $this->mConns['foreignUsed'][$i][$wiki];
644 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
645 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
646 // Reuse a free connection for the same wiki
647 $conn = $this->mConns['foreignFree'][$i][$wiki];
648 unset( $this->mConns['foreignFree'][$i][$wiki] );
649 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
650 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
651 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
652 // Reuse a connection from another wiki
653 $conn = reset( $this->mConns['foreignFree'][$i] );
654 $oldWiki = key( $this->mConns['foreignFree'][$i] );
656 if ( !$conn->selectDB( $dbName ) ) {
657 $this->mLastError = "Error selecting database $dbName on server " .
658 $conn->getServer() . " from client host " . wfHostname() . "\n";
659 $this->mErrorConnection = $conn;
660 $conn = false;
661 } else {
662 $conn->tablePrefix( $prefix );
663 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
664 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
665 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
667 } else {
668 // Open a new connection
669 $server = $this->mServers[$i];
670 $server['serverIndex'] = $i;
671 $server['foreignPoolRefCount'] = 0;
672 $server['foreign'] = true;
673 $conn = $this->reallyOpenConnection( $server, $dbName );
674 if ( !$conn->isOpen() ) {
675 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
676 $this->mErrorConnection = $conn;
677 $conn = false;
678 } else {
679 $conn->tablePrefix( $prefix );
680 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
681 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
685 // Increment reference count
686 if ( $conn ) {
687 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
688 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
690 wfProfileOut( __METHOD__ );
691 return $conn;
695 * Test if the specified index represents an open connection
697 * @param $index Integer: server index
698 * @access private
699 * @return bool
701 function isOpen( $index ) {
702 if ( !is_integer( $index ) ) {
703 return false;
705 return (bool)$this->getAnyOpenConnection( $index );
709 * Really opens a connection. Uncached.
710 * Returns a Database object whether or not the connection was successful.
711 * @access private
713 * @param $server
714 * @param $dbNameOverride bool
715 * @throws MWException
716 * @return DatabaseBase
718 function reallyOpenConnection( $server, $dbNameOverride = false ) {
719 if ( !is_array( $server ) ) {
720 throw new MWException( 'You must update your load-balancing configuration. ' .
721 'See DefaultSettings.php entry for $wgDBservers.' );
724 if ( $dbNameOverride !== false ) {
725 $server['dbname'] = $dbNameOverride;
728 # Create object
729 try {
730 $db = DatabaseBase::factory( $server['type'], $server );
731 } catch ( DBConnectionError $e ) {
732 // FIXME: This is probably the ugliest thing I have ever done to
733 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
734 $db = $e->db;
737 $db->setLBInfo( $server );
738 if ( isset( $server['fakeSlaveLag'] ) ) {
739 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
741 if ( isset( $server['fakeMaster'] ) ) {
742 $db->setFakeMaster( true );
744 return $db;
748 * @throws DBConnectionError
749 * @return bool
751 private function reportConnectionError() {
752 $conn = $this->mErrorConnection; // The connection which caused the error
754 if ( !is_object( $conn ) ) {
755 // No last connection, probably due to all servers being too busy
756 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
758 // If all servers were busy, mLastError will contain something sensible
759 throw new DBConnectionError( null, $this->mLastError );
760 } else {
761 $server = $conn->getProperty( 'mServer' );
762 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
763 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
765 return false; /* not reached */
769 * @return int
771 function getWriterIndex() {
772 return 0;
776 * Returns true if the specified index is a valid server index
778 * @param $i
779 * @return bool
781 function haveIndex( $i ) {
782 return array_key_exists( $i, $this->mServers );
786 * Returns true if the specified index is valid and has non-zero load
788 * @param $i
789 * @return bool
791 function isNonZeroLoad( $i ) {
792 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
796 * Get the number of defined servers (not the number of open connections)
798 * @return int
800 function getServerCount() {
801 return count( $this->mServers );
805 * Get the host name or IP address of the server with the specified index
806 * Prefer a readable name if available.
807 * @param $i
808 * @return string
810 function getServerName( $i ) {
811 if ( isset( $this->mServers[$i]['hostName'] ) ) {
812 return $this->mServers[$i]['hostName'];
813 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
814 return $this->mServers[$i]['host'];
815 } else {
816 return '';
821 * Return the server info structure for a given index, or false if the index is invalid.
822 * @param $i
823 * @return bool
825 function getServerInfo( $i ) {
826 if ( isset( $this->mServers[$i] ) ) {
827 return $this->mServers[$i];
828 } else {
829 return false;
834 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
835 * @param $i
836 * @param $serverInfo
838 function setServerInfo( $i, $serverInfo ) {
839 $this->mServers[$i] = $serverInfo;
843 * Get the current master position for chronology control purposes
844 * @return mixed
846 function getMasterPos() {
847 # If this entire request was served from a slave without opening a connection to the
848 # master (however unlikely that may be), then we can fetch the position from the slave.
849 $masterConn = $this->getAnyOpenConnection( 0 );
850 if ( !$masterConn ) {
851 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
852 $conn = $this->getAnyOpenConnection( $i );
853 if ( $conn ) {
854 wfDebug( "Master pos fetched from slave\n" );
855 return $conn->getSlavePos();
858 } else {
859 wfDebug( "Master pos fetched from master\n" );
860 return $masterConn->getMasterPos();
862 return false;
866 * Close all open connections
868 function closeAll() {
869 foreach ( $this->mConns as $conns2 ) {
870 foreach ( $conns2 as $conns3 ) {
871 foreach ( $conns3 as $conn ) {
872 $conn->close();
876 $this->mConns = array(
877 'local' => array(),
878 'foreignFree' => array(),
879 'foreignUsed' => array(),
884 * Deprecated function, typo in function name
886 * @deprecated in 1.18
887 * @param $conn
889 function closeConnecton( $conn ) {
890 wfDeprecated( __METHOD__, '1.18' );
891 $this->closeConnection( $conn );
895 * Close a connection
896 * Using this function makes sure the LoadBalancer knows the connection is closed.
897 * If you use $conn->close() directly, the load balancer won't update its state.
898 * @param $conn DatabaseBase
900 function closeConnection( $conn ) {
901 $done = false;
902 foreach ( $this->mConns as $i1 => $conns2 ) {
903 foreach ( $conns2 as $i2 => $conns3 ) {
904 foreach ( $conns3 as $i3 => $candidateConn ) {
905 if ( $conn === $candidateConn ) {
906 $conn->close();
907 unset( $this->mConns[$i1][$i2][$i3] );
908 $done = true;
909 break;
914 if ( !$done ) {
915 $conn->close();
920 * Commit transactions on all open connections
922 function commitAll() {
923 foreach ( $this->mConns as $conns2 ) {
924 foreach ( $conns2 as $conns3 ) {
925 foreach ( $conns3 as $conn ) {
926 if ( $conn->trxLevel() ) {
927 $conn->commit( __METHOD__, 'flush' );
935 * Issue COMMIT only on master, only if queries were done on connection
937 function commitMasterChanges() {
938 // Always 0, but who knows.. :)
939 $masterIndex = $this->getWriterIndex();
940 foreach ( $this->mConns as $conns2 ) {
941 if ( empty( $conns2[$masterIndex] ) ) {
942 continue;
944 foreach ( $conns2[$masterIndex] as $conn ) {
945 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
946 $conn->commit( __METHOD__, 'flush' );
953 * @param $value null
954 * @return Mixed
956 function waitTimeout( $value = null ) {
957 return wfSetVar( $this->mWaitTimeout, $value );
961 * @return bool
963 function getLaggedSlaveMode() {
964 return $this->mLaggedSlaveMode;
968 * Disables/enables lag checks
969 * @param $mode null
970 * @return bool
972 function allowLagged( $mode = null ) {
973 if ( $mode === null ) {
974 return $this->mAllowLagged;
976 $this->mAllowLagged = $mode;
977 return $this->mAllowLagged;
981 * @return bool
983 function pingAll() {
984 $success = true;
985 foreach ( $this->mConns as $conns2 ) {
986 foreach ( $conns2 as $conns3 ) {
987 foreach ( $conns3 as $conn ) {
988 if ( !$conn->ping() ) {
989 $success = false;
994 return $success;
998 * Call a function with each open connection object
999 * @param $callback
1000 * @param array $params
1002 function forEachOpenConnection( $callback, $params = array() ) {
1003 foreach ( $this->mConns as $conns2 ) {
1004 foreach ( $conns2 as $conns3 ) {
1005 foreach ( $conns3 as $conn ) {
1006 $mergedParams = array_merge( array( $conn ), $params );
1007 call_user_func_array( $callback, $mergedParams );
1014 * Get the hostname and lag time of the most-lagged slave.
1015 * This is useful for maintenance scripts that need to throttle their updates.
1016 * May attempt to open connections to slaves on the default DB. If there is
1017 * no lag, the maximum lag will be reported as -1.
1019 * @param string $wiki Wiki ID, or false for the default database
1021 * @return array ( host, max lag, index of max lagged host )
1023 function getMaxLag( $wiki = false ) {
1024 $maxLag = -1;
1025 $host = '';
1026 $maxIndex = 0;
1027 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1028 foreach ( $this->mServers as $i => $conn ) {
1029 $conn = false;
1030 if ( $wiki === false ) {
1031 $conn = $this->getAnyOpenConnection( $i );
1033 if ( !$conn ) {
1034 $conn = $this->openConnection( $i, $wiki );
1036 if ( !$conn ) {
1037 continue;
1039 $lag = $conn->getLag();
1040 if ( $lag > $maxLag ) {
1041 $maxLag = $lag;
1042 $host = $this->mServers[$i]['host'];
1043 $maxIndex = $i;
1047 return array( $host, $maxLag, $maxIndex );
1051 * Get lag time for each server
1052 * Results are cached for a short time in memcached, and indefinitely in the process cache
1054 * @param $wiki
1056 * @return array
1058 function getLagTimes( $wiki = false ) {
1059 # Try process cache
1060 if ( isset( $this->mLagTimes ) ) {
1061 return $this->mLagTimes;
1063 if ( $this->getServerCount() == 1 ) {
1064 # No replication
1065 $this->mLagTimes = array( 0 => 0 );
1066 } else {
1067 # Send the request to the load monitor
1068 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
1069 array_keys( $this->mServers ), $wiki );
1071 return $this->mLagTimes;
1075 * Get the lag in seconds for a given connection, or zero if this load
1076 * balancer does not have replication enabled.
1078 * This should be used in preference to Database::getLag() in cases where
1079 * replication may not be in use, since there is no way to determine if
1080 * replication is in use at the connection level without running
1081 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1082 * function instead of Database::getLag() avoids a fatal error in this
1083 * case on many installations.
1085 * @param $conn DatabaseBase
1087 * @return int
1089 function safeGetLag( $conn ) {
1090 if ( $this->getServerCount() == 1 ) {
1091 return 0;
1092 } else {
1093 return $conn->getLag();
1098 * Clear the cache for getLagTimes
1100 function clearLagTimeCache() {
1101 $this->mLagTimes = null;
1106 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1107 * as well handling deferring the actual network connection until the handle is used
1109 * @ingroup Database
1110 * @since 1.22
1112 class DBConnRef implements IDatabase {
1113 /** @var LoadBalancer */
1114 protected $lb;
1115 /** @var DatabaseBase|null */
1116 protected $conn;
1117 /** @var Array|null */
1118 protected $params;
1121 * @param $lb LoadBalancer
1122 * @param $conn DatabaseBase|array Connection or (server index, group, wiki ID) array
1124 public function __construct( LoadBalancer $lb, $conn ) {
1125 $this->lb = $lb;
1126 if ( $conn instanceof DatabaseBase ) {
1127 $this->conn = $conn;
1128 } else {
1129 $this->params = $conn;
1133 public function __call( $name, $arguments ) {
1134 if ( $this->conn === null ) {
1135 list( $db, $groups, $wiki ) = $this->params;
1136 $this->conn = $this->lb->getConnection( $db, $groups, $wiki );
1138 return call_user_func_array( array( $this->conn, $name ), $arguments );
1141 function __destruct() {
1142 if ( $this->conn !== null ) {
1143 $this->lb->reuseConnection( $this->conn );