Implement extension registration from an extension.json file
[mediawiki.git] / includes / db / LoadBalancer.php
blobf789d56ac1ee24691505e038c56899266111e6f2
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 /** @var array[] Map of (server index => server config array) */
32 private $mServers;
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
34 private $mConns;
35 /** @var array Map of (server index => weight) */
36 private $mLoads;
37 /** @var array[] Map of (group => server index => weight) */
38 private $mGroupLoads;
39 /** @var bool Whether to disregard slave lag as a factor in slave selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on slave lag to resolve */
42 private $mWaitTimeout;
44 /** @var array LBFactory information */
45 private $mParentInfo;
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
51 /** @var bool|DatabaseBase Database connection that caused a problem */
52 private $mErrorConnection;
53 /** @var integer The generic (not query grouped) slave index (of $mServers) */
54 private $mReadIndex;
55 /** @var bool|DBMasterPos False if not set */
56 private $mWaitForPos;
57 /** @var bool Whether the generic reader fell back to a lagged slave */
58 private $mLaggedSlaveMode;
59 /** @var string The last DB selection or connection error */
60 private $mLastError = 'Unknown error';
61 /** @var ProcessCacheLRU */
62 private $mProcCache;
64 /**
65 * @param array $params Array with keys:
66 * servers Required. Array of server info structures.
67 * loadMonitor Name of a class used to fetch server lag and load.
68 * @throws MWException
70 public function __construct( array $params ) {
71 if ( !isset( $params['servers'] ) ) {
72 throw new MWException( __CLASS__ . ': missing servers parameter' );
74 $this->mServers = $params['servers'];
75 $this->mWaitTimeout = 10;
77 $this->mReadIndex = -1;
78 $this->mWriteIndex = -1;
79 $this->mConns = array(
80 'local' => array(),
81 'foreignUsed' => array(),
82 'foreignFree' => array() );
83 $this->mLoads = array();
84 $this->mWaitForPos = false;
85 $this->mLaggedSlaveMode = false;
86 $this->mErrorConnection = false;
87 $this->mAllowLagged = false;
89 if ( isset( $params['loadMonitor'] ) ) {
90 $this->mLoadMonitorClass = $params['loadMonitor'];
91 } else {
92 $master = reset( $params['servers'] );
93 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
94 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
95 } else {
96 $this->mLoadMonitorClass = 'LoadMonitorNull';
100 foreach ( $params['servers'] as $i => $server ) {
101 $this->mLoads[$i] = $server['load'];
102 if ( isset( $server['groupLoads'] ) ) {
103 foreach ( $server['groupLoads'] as $group => $ratio ) {
104 if ( !isset( $this->mGroupLoads[$group] ) ) {
105 $this->mGroupLoads[$group] = array();
107 $this->mGroupLoads[$group][$i] = $ratio;
112 $this->mProcCache = new ProcessCacheLRU( 30 );
116 * Get a LoadMonitor instance
118 * @return LoadMonitor
120 private function getLoadMonitor() {
121 if ( !isset( $this->mLoadMonitor ) ) {
122 $class = $this->mLoadMonitorClass;
123 $this->mLoadMonitor = new $class( $this );
126 return $this->mLoadMonitor;
130 * Get or set arbitrary data used by the parent object, usually an LBFactory
131 * @param mixed $x
132 * @return mixed
134 public function parentInfo( $x = null ) {
135 return wfSetVar( $this->mParentInfo, $x );
139 * Given an array of non-normalised probabilities, this function will select
140 * an element and return the appropriate key
142 * @deprecated since 1.21, use ArrayUtils::pickRandom()
144 * @param array $weights
145 * @return bool|int|string
147 public function pickRandom( array $weights ) {
148 return ArrayUtils::pickRandom( $weights );
152 * @param array $loads
153 * @param bool|string $wiki Wiki to get non-lagged for
154 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
155 * @return bool|int|string
157 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF ) {
158 $lags = $this->getLagTimes( $wiki );
160 # Unset excessively lagged servers
161 foreach ( $lags as $i => $lag ) {
162 if ( $i != 0 ) {
163 $maxServerLag = $maxLag;
164 if ( isset( $this->mServers[$i]['max lag'] ) ) {
165 $maxServerLag = min( $maxServerLag, $this->mServers[$i]['max lag'] );
167 if ( $lag === false ) {
168 wfDebugLog( 'replication', "Server #$i is not replicating" );
169 unset( $loads[$i] );
170 } elseif ( $lag > $maxServerLag ) {
171 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
172 unset( $loads[$i] );
177 # Find out if all the slaves with non-zero load are lagged
178 $sum = 0;
179 foreach ( $loads as $load ) {
180 $sum += $load;
182 if ( $sum == 0 ) {
183 # No appropriate DB servers except maybe the master and some slaves with zero load
184 # Do NOT use the master
185 # Instead, this function will return false, triggering read-only mode,
186 # and a lagged slave will be used instead.
187 return false;
190 if ( count( $loads ) == 0 ) {
191 return false;
194 #wfDebugLog( 'connect', var_export( $loads, true ) );
196 # Return a random representative of the remainder
197 return ArrayUtils::pickRandom( $loads );
201 * Get the index of the reader connection, which may be a slave
202 * This takes into account load ratios and lag times. It should
203 * always return a consistent index during a given invocation
205 * Side effect: opens connections to databases
206 * @param string|bool $group Query group, or false for the generic reader
207 * @param string|bool $wiki Wiki ID, or false for the current wiki
208 * @throws MWException
209 * @return bool|int|string
211 public function getReaderIndex( $group = false, $wiki = false ) {
212 global $wgReadOnly, $wgDBtype;
214 # @todo FIXME: For now, only go through all this for mysql databases
215 if ( $wgDBtype != 'mysql' ) {
216 return $this->getWriterIndex();
219 if ( count( $this->mServers ) == 1 ) {
220 # Skip the load balancing if there's only one server
221 return 0;
222 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
223 # Shortcut if generic reader exists already
224 return $this->mReadIndex;
227 # Find the relevant load array
228 if ( $group !== false ) {
229 if ( isset( $this->mGroupLoads[$group] ) ) {
230 $nonErrorLoads = $this->mGroupLoads[$group];
231 } else {
232 # No loads for this group, return false and the caller can use some other group
233 wfDebug( __METHOD__ . ": no loads for group $group\n" );
235 return false;
237 } else {
238 $nonErrorLoads = $this->mLoads;
241 if ( !count( $nonErrorLoads ) ) {
242 throw new MWException( "Empty server array given to LoadBalancer" );
245 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
246 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
248 $laggedSlaveMode = false;
250 # No server found yet
251 $i = false;
252 # First try quickly looking through the available servers for a server that
253 # meets our criteria
254 $currentLoads = $nonErrorLoads;
255 while ( count( $currentLoads ) ) {
256 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
257 $i = ArrayUtils::pickRandom( $currentLoads );
258 } else {
259 $i = false;
260 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
261 # ChronologyProtecter causes mWaitForPos to be set via sessions.
262 # This triggers doWait() after connect, so it's especially good to
263 # avoid lagged servers so as to avoid just blocking in that method.
264 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
265 # Aim for <= 1 second of waiting (being too picky can backfire)
266 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
268 if ( $i === false ) {
269 # Any server with less lag than it's 'max lag' param is preferable
270 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
272 if ( $i === false && count( $currentLoads ) != 0 ) {
273 # All slaves lagged. Switch to read-only mode
274 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
275 $wgReadOnly = 'The database has been automatically locked ' .
276 'while the slave database servers catch up to the master';
277 $i = ArrayUtils::pickRandom( $currentLoads );
278 $laggedSlaveMode = true;
282 if ( $i === false ) {
283 # pickRandom() returned false
284 # This is permanent and means the configuration or the load monitor
285 # wants us to return false.
286 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
288 return false;
291 wfDebugLog( 'connect', __METHOD__ .
292 ": Using reader #$i: {$this->mServers[$i]['host']}..." );
294 $conn = $this->openConnection( $i, $wiki );
295 if ( !$conn ) {
296 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
297 unset( $nonErrorLoads[$i] );
298 unset( $currentLoads[$i] );
299 $i = false;
300 continue;
303 // Decrement reference counter, we are finished with this connection.
304 // It will be incremented for the caller later.
305 if ( $wiki !== false ) {
306 $this->reuseConnection( $conn );
309 # Return this server
310 break;
313 # If all servers were down, quit now
314 if ( !count( $nonErrorLoads ) ) {
315 wfDebugLog( 'connect', "All servers down" );
318 if ( $i !== false ) {
319 # Slave connection successful
320 # Wait for the session master pos for a short time
321 if ( $this->mWaitForPos && $i > 0 ) {
322 if ( !$this->doWait( $i ) ) {
323 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
326 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group !== false ) {
327 $this->mReadIndex = $i;
331 return $i;
335 * Set the master wait position
336 * If a DB_SLAVE connection has been opened already, waits
337 * Otherwise sets a variable telling it to wait if such a connection is opened
338 * @param DBMasterPos $pos
340 public function waitFor( $pos ) {
341 $this->mWaitForPos = $pos;
342 $i = $this->mReadIndex;
344 if ( $i > 0 ) {
345 if ( !$this->doWait( $i ) ) {
346 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
347 $this->mLaggedSlaveMode = true;
353 * Set the master wait position and wait for ALL slaves to catch up to it
354 * @param DBMasterPos $pos
355 * @param int $timeout Max seconds to wait; default is mWaitTimeout
356 * @return bool Success (able to connect and no timeouts reached)
358 public function waitForAll( $pos, $timeout = null ) {
359 $this->mWaitForPos = $pos;
360 $serverCount = count( $this->mServers );
362 $ok = true;
363 for ( $i = 1; $i < $serverCount; $i++ ) {
364 if ( $this->mLoads[$i] > 0 ) {
365 $ok = $this->doWait( $i, true, $timeout ) && $ok;
369 return $ok;
373 * Get any open connection to a given server index, local or foreign
374 * Returns false if there is no connection open
376 * @param int $i
377 * @return DatabaseBase|bool False on failure
379 public function getAnyOpenConnection( $i ) {
380 foreach ( $this->mConns as $conns ) {
381 if ( !empty( $conns[$i] ) ) {
382 return reset( $conns[$i] );
386 return false;
390 * Wait for a given slave to catch up to the master pos stored in $this
391 * @param int $index Server index
392 * @param bool $open Check the server even if a new connection has to be made
393 * @param int $timeout Max seconds to wait; default is mWaitTimeout
394 * @return bool
396 protected function doWait( $index, $open = false, $timeout = null ) {
397 $close = false; // close the connection afterwards
399 # Find a connection to wait on, creating one if needed and allowed
400 $conn = $this->getAnyOpenConnection( $index );
401 if ( !$conn ) {
402 if ( !$open ) {
403 wfDebug( __METHOD__ . ": no connection open\n" );
405 return false;
406 } else {
407 $conn = $this->openConnection( $index, '' );
408 if ( !$conn ) {
409 wfDebug( __METHOD__ . ": failed to open connection\n" );
411 return false;
413 // Avoid connection spam in waitForAll() when connections
414 // are made just for the sake of doing this lag check.
415 $close = true;
419 wfDebug( __METHOD__ . ": Waiting for slave #$index to catch up...\n" );
420 $timeout = $timeout ?: $this->mWaitTimeout;
421 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
423 if ( $result == -1 || is_null( $result ) ) {
424 # Timed out waiting for slave, use master instead
425 $server = $this->mServers[$index]['host'];
426 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
427 wfDebug( "$msg\n" );
428 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
429 $ok = false;
430 } else {
431 wfDebug( __METHOD__ . ": Done\n" );
432 $ok = true;
435 if ( $close ) {
436 $this->closeConnection( $conn );
439 return $ok;
443 * Get a connection by index
444 * This is the main entry point for this class.
446 * @param int $i Server index
447 * @param array|string|bool $groups Query group(s), or false for the generic reader
448 * @param string|bool $wiki Wiki ID, or false for the current wiki
450 * @throws MWException
451 * @return DatabaseBase
453 public function getConnection( $i, $groups = array(), $wiki = false ) {
454 if ( $i === null || $i === false ) {
455 throw new MWException( 'Attempt to call ' . __METHOD__ .
456 ' with invalid server index' );
459 if ( $wiki === wfWikiID() ) {
460 $wiki = false;
463 $groups = ( $groups === false || $groups === array() )
464 ? array( false ) // check one "group": the generic pool
465 : (array)$groups;
467 if ( $i == DB_MASTER ) {
468 $i = $this->getWriterIndex();
469 } else {
470 # Try to find an available server in any the query groups (in order)
471 foreach ( $groups as $group ) {
472 $groupIndex = $this->getReaderIndex( $group, $wiki );
473 if ( $groupIndex !== false ) {
474 $serverName = $this->getServerName( $groupIndex );
475 wfDebug( __METHOD__ . ": using server $serverName for group $group\n" );
476 $i = $groupIndex;
477 break;
482 # Operation-based index
483 if ( $i == DB_SLAVE ) {
484 $this->mLastError = 'Unknown error'; // reset error string
485 # Try the general server pool if $groups are unavailable.
486 $i = in_array( false, $groups, true )
487 ? false // don't bother with this if that is what was tried above
488 : $this->getReaderIndex( false, $wiki );
489 # Couldn't find a working server in getReaderIndex()?
490 if ( $i === false ) {
491 $this->mLastError = 'No working slave server: ' . $this->mLastError;
493 return $this->reportConnectionError();
497 # Now we have an explicit index into the servers array
498 $conn = $this->openConnection( $i, $wiki );
499 if ( !$conn ) {
501 return $this->reportConnectionError();
505 return $conn;
509 * Mark a foreign connection as being available for reuse under a different
510 * DB name or prefix. This mechanism is reference-counted, and must be called
511 * the same number of times as getConnection() to work.
513 * @param DatabaseBase $conn
514 * @throws MWException
516 public function reuseConnection( $conn ) {
517 $serverIndex = $conn->getLBInfo( 'serverIndex' );
518 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
519 if ( $serverIndex === null || $refCount === null ) {
520 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
523 * This can happen in code like:
524 * foreach ( $dbs as $db ) {
525 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
526 * ...
527 * $lb->reuseConnection( $conn );
529 * When a connection to the local DB is opened in this way, reuseConnection()
530 * should be ignored
533 return;
536 $dbName = $conn->getDBname();
537 $prefix = $conn->tablePrefix();
538 if ( strval( $prefix ) !== '' ) {
539 $wiki = "$dbName-$prefix";
540 } else {
541 $wiki = $dbName;
543 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
544 throw new MWException( __METHOD__ . ": connection not found, has " .
545 "the connection been freed already?" );
547 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
548 if ( $refCount <= 0 ) {
549 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
550 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
551 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
552 } else {
553 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
558 * Get a database connection handle reference
560 * The handle's methods wrap simply wrap those of a DatabaseBase handle
562 * @see LoadBalancer::getConnection() for parameter information
564 * @param int $db
565 * @param array|string|bool $groups Query group(s), or false for the generic reader
566 * @param string|bool $wiki Wiki ID, or false for the current wiki
567 * @return DBConnRef
569 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
570 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
574 * Get a database connection handle reference without connecting yet
576 * The handle's methods wrap simply wrap those of a DatabaseBase handle
578 * @see LoadBalancer::getConnection() for parameter information
580 * @param int $db
581 * @param array|string|bool $groups Query group(s), or false for the generic reader
582 * @param string|bool $wiki Wiki ID, or false for the current wiki
583 * @return DBConnRef
585 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
586 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
590 * Open a connection to the server given by the specified index
591 * Index must be an actual index into the array.
592 * If the server is already open, returns it.
594 * On error, returns false, and the connection which caused the
595 * error will be available via $this->mErrorConnection.
597 * @param int $i Server index
598 * @param string|bool $wiki Wiki ID, or false for the current wiki
599 * @return DatabaseBase
601 * @access private
603 public function openConnection( $i, $wiki = false ) {
604 if ( $wiki !== false ) {
605 $conn = $this->openForeignConnection( $i, $wiki );
607 return $conn;
609 if ( isset( $this->mConns['local'][$i][0] ) ) {
610 $conn = $this->mConns['local'][$i][0];
611 } else {
612 $server = $this->mServers[$i];
613 $server['serverIndex'] = $i;
614 $conn = $this->reallyOpenConnection( $server, false );
615 if ( $conn->isOpen() ) {
616 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
617 $this->mConns['local'][$i][0] = $conn;
618 } else {
619 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
620 $this->mErrorConnection = $conn;
621 $conn = false;
625 return $conn;
629 * Open a connection to a foreign DB, or return one if it is already open.
631 * Increments a reference count on the returned connection which locks the
632 * connection to the requested wiki. This reference count can be
633 * decremented by calling reuseConnection().
635 * If a connection is open to the appropriate server already, but with the wrong
636 * database, it will be switched to the right database and returned, as long as
637 * it has been freed first with reuseConnection().
639 * On error, returns false, and the connection which caused the
640 * error will be available via $this->mErrorConnection.
642 * @param int $i Server index
643 * @param string $wiki Wiki ID to open
644 * @return DatabaseBase
646 private function openForeignConnection( $i, $wiki ) {
647 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
648 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
649 // Reuse an already-used connection
650 $conn = $this->mConns['foreignUsed'][$i][$wiki];
651 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
652 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
653 // Reuse a free connection for the same wiki
654 $conn = $this->mConns['foreignFree'][$i][$wiki];
655 unset( $this->mConns['foreignFree'][$i][$wiki] );
656 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
657 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
658 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
659 // Reuse a connection from another wiki
660 $conn = reset( $this->mConns['foreignFree'][$i] );
661 $oldWiki = key( $this->mConns['foreignFree'][$i] );
663 // The empty string as a DB name means "don't care".
664 // DatabaseMysqlBase::open() already handle this on connection.
665 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
666 $this->mLastError = "Error selecting database $dbName on server " .
667 $conn->getServer() . " from client host " . wfHostname() . "\n";
668 $this->mErrorConnection = $conn;
669 $conn = false;
670 } else {
671 $conn->tablePrefix( $prefix );
672 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
673 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
674 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
676 } else {
677 // Open a new connection
678 $server = $this->mServers[$i];
679 $server['serverIndex'] = $i;
680 $server['foreignPoolRefCount'] = 0;
681 $server['foreign'] = true;
682 $conn = $this->reallyOpenConnection( $server, $dbName );
683 if ( !$conn->isOpen() ) {
684 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
685 $this->mErrorConnection = $conn;
686 $conn = false;
687 } else {
688 $conn->tablePrefix( $prefix );
689 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
690 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
694 // Increment reference count
695 if ( $conn ) {
696 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
697 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
700 return $conn;
704 * Test if the specified index represents an open connection
706 * @param int $index Server index
707 * @access private
708 * @return bool
710 private function isOpen( $index ) {
711 if ( !is_integer( $index ) ) {
712 return false;
715 return (bool)$this->getAnyOpenConnection( $index );
719 * Really opens a connection. Uncached.
720 * Returns a Database object whether or not the connection was successful.
721 * @access private
723 * @param array $server
724 * @param bool $dbNameOverride
725 * @throws MWException
726 * @return DatabaseBase
728 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
729 if ( !is_array( $server ) ) {
730 throw new MWException( 'You must update your load-balancing configuration. ' .
731 'See DefaultSettings.php entry for $wgDBservers.' );
734 if ( $dbNameOverride !== false ) {
735 $server['dbname'] = $dbNameOverride;
738 # Create object
739 try {
740 $db = DatabaseBase::factory( $server['type'], $server );
741 } catch ( DBConnectionError $e ) {
742 // FIXME: This is probably the ugliest thing I have ever done to
743 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
744 $db = $e->db;
747 $db->setLBInfo( $server );
748 if ( isset( $server['fakeSlaveLag'] ) ) {
749 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
751 if ( isset( $server['fakeMaster'] ) ) {
752 $db->setFakeMaster( true );
755 return $db;
759 * @throws DBConnectionError
760 * @return bool
762 private function reportConnectionError() {
763 $conn = $this->mErrorConnection; // The connection which caused the error
764 $context = array(
765 'method' => __METHOD__,
766 'last_error' => $this->mLastError,
769 if ( !is_object( $conn ) ) {
770 // No last connection, probably due to all servers being too busy
771 wfLogDBError(
772 "LB failure with no last connection. Connection error: {last_error}",
773 $context
776 // If all servers were busy, mLastError will contain something sensible
777 throw new DBConnectionError( null, $this->mLastError );
778 } else {
779 $context['db_server'] = $conn->getProperty( 'mServer' );
780 wfLogDBError(
781 "Connection error: {last_error} ({db_server})",
782 $context
784 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
787 return false; /* not reached */
791 * @return int
793 private function getWriterIndex() {
794 return 0;
798 * Returns true if the specified index is a valid server index
800 * @param string $i
801 * @return bool
803 public function haveIndex( $i ) {
804 return array_key_exists( $i, $this->mServers );
808 * Returns true if the specified index is valid and has non-zero load
810 * @param string $i
811 * @return bool
813 public function isNonZeroLoad( $i ) {
814 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
818 * Get the number of defined servers (not the number of open connections)
820 * @return int
822 public function getServerCount() {
823 return count( $this->mServers );
827 * Get the host name or IP address of the server with the specified index
828 * Prefer a readable name if available.
829 * @param string $i
830 * @return string
832 public function getServerName( $i ) {
833 if ( isset( $this->mServers[$i]['hostName'] ) ) {
834 return $this->mServers[$i]['hostName'];
835 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
836 return $this->mServers[$i]['host'];
837 } else {
838 return '';
843 * Return the server info structure for a given index, or false if the index is invalid.
844 * @param int $i
845 * @return array|bool
847 public function getServerInfo( $i ) {
848 if ( isset( $this->mServers[$i] ) ) {
849 return $this->mServers[$i];
850 } else {
851 return false;
856 * Sets the server info structure for the given index. Entry at index $i
857 * is created if it doesn't exist
858 * @param int $i
859 * @param array $serverInfo
861 public function setServerInfo( $i, array $serverInfo ) {
862 $this->mServers[$i] = $serverInfo;
866 * Get the current master position for chronology control purposes
867 * @return mixed
869 public function getMasterPos() {
870 # If this entire request was served from a slave without opening a connection to the
871 # master (however unlikely that may be), then we can fetch the position from the slave.
872 $masterConn = $this->getAnyOpenConnection( 0 );
873 if ( !$masterConn ) {
874 $serverCount = count( $this->mServers );
875 for ( $i = 1; $i < $serverCount; $i++ ) {
876 $conn = $this->getAnyOpenConnection( $i );
877 if ( $conn ) {
878 wfDebug( "Master pos fetched from slave\n" );
880 return $conn->getSlavePos();
883 } else {
884 wfDebug( "Master pos fetched from master\n" );
886 return $masterConn->getMasterPos();
889 return false;
893 * Close all open connections
895 public function closeAll() {
896 foreach ( $this->mConns as $conns2 ) {
897 foreach ( $conns2 as $conns3 ) {
898 /** @var DatabaseBase $conn */
899 foreach ( $conns3 as $conn ) {
900 $conn->close();
904 $this->mConns = array(
905 'local' => array(),
906 'foreignFree' => array(),
907 'foreignUsed' => array(),
912 * Close a connection
913 * Using this function makes sure the LoadBalancer knows the connection is closed.
914 * If you use $conn->close() directly, the load balancer won't update its state.
915 * @param DatabaseBase $conn
917 public function closeConnection( $conn ) {
918 $done = false;
919 foreach ( $this->mConns as $i1 => $conns2 ) {
920 foreach ( $conns2 as $i2 => $conns3 ) {
921 foreach ( $conns3 as $i3 => $candidateConn ) {
922 if ( $conn === $candidateConn ) {
923 $conn->close();
924 unset( $this->mConns[$i1][$i2][$i3] );
925 $done = true;
926 break;
931 if ( !$done ) {
932 $conn->close();
937 * Commit transactions on all open connections
939 public function commitAll() {
940 foreach ( $this->mConns as $conns2 ) {
941 foreach ( $conns2 as $conns3 ) {
942 /** @var DatabaseBase[] $conns3 */
943 foreach ( $conns3 as $conn ) {
944 if ( $conn->trxLevel() ) {
945 $conn->commit( __METHOD__, 'flush' );
953 * Issue COMMIT only on master, only if queries were done on connection
955 public function commitMasterChanges() {
956 // Always 0, but who knows.. :)
957 $masterIndex = $this->getWriterIndex();
958 foreach ( $this->mConns as $conns2 ) {
959 if ( empty( $conns2[$masterIndex] ) ) {
960 continue;
962 /** @var DatabaseBase $conn */
963 foreach ( $conns2[$masterIndex] as $conn ) {
964 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
965 $conn->commit( __METHOD__, 'flush' );
972 * Issue ROLLBACK only on master, only if queries were done on connection
973 * @since 1.23
975 public function rollbackMasterChanges() {
976 // Always 0, but who knows.. :)
977 $masterIndex = $this->getWriterIndex();
978 foreach ( $this->mConns as $conns2 ) {
979 if ( empty( $conns2[$masterIndex] ) ) {
980 continue;
982 /** @var DatabaseBase $conn */
983 foreach ( $conns2[$masterIndex] as $conn ) {
984 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
985 $conn->rollback( __METHOD__, 'flush' );
992 * @return bool Whether a master connection is already open
993 * @since 1.24
995 public function hasMasterConnection() {
996 return $this->isOpen( $this->getWriterIndex() );
1000 * Determine if there are any pending changes that need to be rolled back
1001 * or committed.
1002 * @since 1.23
1003 * @return bool
1005 public function hasMasterChanges() {
1006 // Always 0, but who knows.. :)
1007 $masterIndex = $this->getWriterIndex();
1008 foreach ( $this->mConns as $conns2 ) {
1009 if ( empty( $conns2[$masterIndex] ) ) {
1010 continue;
1012 /** @var DatabaseBase $conn */
1013 foreach ( $conns2[$masterIndex] as $conn ) {
1014 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1015 return true;
1019 return false;
1023 * @param mixed $value
1024 * @return mixed
1026 public function waitTimeout( $value = null ) {
1027 return wfSetVar( $this->mWaitTimeout, $value );
1031 * @return bool
1033 public function getLaggedSlaveMode() {
1034 return $this->mLaggedSlaveMode;
1038 * Disables/enables lag checks
1039 * @param null|bool $mode
1040 * @return bool
1042 public function allowLagged( $mode = null ) {
1043 if ( $mode === null ) {
1044 return $this->mAllowLagged;
1046 $this->mAllowLagged = $mode;
1048 return $this->mAllowLagged;
1052 * @return bool
1054 public function pingAll() {
1055 $success = true;
1056 foreach ( $this->mConns as $conns2 ) {
1057 foreach ( $conns2 as $conns3 ) {
1058 /** @var DatabaseBase[] $conns3 */
1059 foreach ( $conns3 as $conn ) {
1060 if ( !$conn->ping() ) {
1061 $success = false;
1067 return $success;
1071 * Call a function with each open connection object
1072 * @param callable $callback
1073 * @param array $params
1075 public function forEachOpenConnection( $callback, array $params = array() ) {
1076 foreach ( $this->mConns as $conns2 ) {
1077 foreach ( $conns2 as $conns3 ) {
1078 foreach ( $conns3 as $conn ) {
1079 $mergedParams = array_merge( array( $conn ), $params );
1080 call_user_func_array( $callback, $mergedParams );
1087 * Get the hostname and lag time of the most-lagged slave
1089 * This is useful for maintenance scripts that need to throttle their updates.
1090 * May attempt to open connections to slaves on the default DB. If there is
1091 * no lag, the maximum lag will be reported as -1.
1093 * @param bool|string $wiki Wiki ID, or false for the default database
1094 * @return array ( host, max lag, index of max lagged host )
1096 public function getMaxLag( $wiki = false ) {
1097 $maxLag = -1;
1098 $host = '';
1099 $maxIndex = 0;
1101 if ( $this->getServerCount() <= 1 ) {
1102 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1105 $lagTimes = $this->getLagTimes( $wiki );
1106 foreach ( $lagTimes as $i => $lag ) {
1107 if ( $lag > $maxLag ) {
1108 $maxLag = $lag;
1109 $host = $this->mServers[$i]['host'];
1110 $maxIndex = $i;
1114 return array( $host, $maxLag, $maxIndex );
1118 * Get lag time for each server
1120 * Results are cached for a short time in memcached/process cache
1122 * @param string|bool $wiki
1123 * @return int[] Map of (server index => seconds)
1125 public function getLagTimes( $wiki = false ) {
1126 if ( $this->getServerCount() <= 1 ) {
1127 return array( 0 => 0 ); // no replication = no lag
1130 if ( $this->mProcCache->has( 'slave_lag', 'times', 1 ) ) {
1131 return $this->mProcCache->get( 'slave_lag', 'times' );
1134 # Send the request to the load monitor
1135 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1137 $this->mProcCache->set( 'slave_lag', 'times', $times );
1139 return $times;
1143 * Get the lag in seconds for a given connection, or zero if this load
1144 * balancer does not have replication enabled.
1146 * This should be used in preference to Database::getLag() in cases where
1147 * replication may not be in use, since there is no way to determine if
1148 * replication is in use at the connection level without running
1149 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1150 * function instead of Database::getLag() avoids a fatal error in this
1151 * case on many installations.
1153 * @param DatabaseBase $conn
1154 * @return int
1156 public function safeGetLag( $conn ) {
1157 if ( $this->getServerCount() == 1 ) {
1158 return 0;
1159 } else {
1160 return $conn->getLag();
1165 * Clear the cache for slag lag delay times
1167 public function clearLagTimeCache() {
1168 $this->mProcCache->clear( 'slave_lag' );
1173 * Helper class to handle automatically marking connections as reusable (via RAII pattern)
1174 * as well handling deferring the actual network connection until the handle is used
1176 * @ingroup Database
1177 * @since 1.22
1179 class DBConnRef implements IDatabase {
1180 /** @var LoadBalancer */
1181 private $lb;
1183 /** @var DatabaseBase|null */
1184 private $conn;
1186 /** @var array|null */
1187 private $params;
1190 * @param LoadBalancer $lb
1191 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1193 public function __construct( LoadBalancer $lb, $conn ) {
1194 $this->lb = $lb;
1195 if ( $conn instanceof DatabaseBase ) {
1196 $this->conn = $conn;
1197 } else {
1198 $this->params = $conn;
1202 public function __call( $name, $arguments ) {
1203 if ( $this->conn === null ) {
1204 list( $db, $groups, $wiki ) = $this->params;
1205 $this->conn = $this->lb->getConnection( $db, $groups, $wiki );
1208 return call_user_func_array( array( $this->conn, $name ), $arguments );
1211 public function __destruct() {
1212 if ( $this->conn !== null ) {
1213 $this->lb->reuseConnection( $this->conn );