Fix hook situation for Skin::doEditSectionLink
[mediawiki.git] / includes / db / LoadBalancer.php
blobf357880471943803343297700d48b9fa2614990d
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 integer Total connections opened */
62 private $connsOpened = 0;
63 /** @var ProcessCacheLRU */
64 private $mProcCache;
66 /** @var integer Warn when this many connection are held */
67 const CONN_HELD_WARN_THRESHOLD = 10;
69 /**
70 * @param array $params Array with keys:
71 * servers Required. Array of server info structures.
72 * loadMonitor Name of a class used to fetch server lag and load.
73 * @throws MWException
75 public function __construct( array $params ) {
76 if ( !isset( $params['servers'] ) ) {
77 throw new MWException( __CLASS__ . ': missing servers parameter' );
79 $this->mServers = $params['servers'];
80 $this->mWaitTimeout = 10;
82 $this->mReadIndex = -1;
83 $this->mWriteIndex = -1;
84 $this->mConns = array(
85 'local' => array(),
86 'foreignUsed' => array(),
87 'foreignFree' => array() );
88 $this->mLoads = array();
89 $this->mWaitForPos = false;
90 $this->mLaggedSlaveMode = false;
91 $this->mErrorConnection = false;
92 $this->mAllowLagged = false;
94 if ( isset( $params['loadMonitor'] ) ) {
95 $this->mLoadMonitorClass = $params['loadMonitor'];
96 } else {
97 $master = reset( $params['servers'] );
98 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
99 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
100 } else {
101 $this->mLoadMonitorClass = 'LoadMonitorNull';
105 foreach ( $params['servers'] as $i => $server ) {
106 $this->mLoads[$i] = $server['load'];
107 if ( isset( $server['groupLoads'] ) ) {
108 foreach ( $server['groupLoads'] as $group => $ratio ) {
109 if ( !isset( $this->mGroupLoads[$group] ) ) {
110 $this->mGroupLoads[$group] = array();
112 $this->mGroupLoads[$group][$i] = $ratio;
117 $this->mProcCache = new ProcessCacheLRU( 30 );
121 * Get a LoadMonitor instance
123 * @return LoadMonitor
125 private function getLoadMonitor() {
126 if ( !isset( $this->mLoadMonitor ) ) {
127 $class = $this->mLoadMonitorClass;
128 $this->mLoadMonitor = new $class( $this );
131 return $this->mLoadMonitor;
135 * Get or set arbitrary data used by the parent object, usually an LBFactory
136 * @param mixed $x
137 * @return mixed
139 public function parentInfo( $x = null ) {
140 return wfSetVar( $this->mParentInfo, $x );
144 * Given an array of non-normalised probabilities, this function will select
145 * an element and return the appropriate key
147 * @deprecated since 1.21, use ArrayUtils::pickRandom()
149 * @param array $weights
150 * @return bool|int|string
152 public function pickRandom( array $weights ) {
153 return ArrayUtils::pickRandom( $weights );
157 * @param array $loads
158 * @param bool|string $wiki Wiki to get non-lagged for
159 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
160 * @return bool|int|string
162 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF ) {
163 $lags = $this->getLagTimes( $wiki );
165 # Unset excessively lagged servers
166 foreach ( $lags as $i => $lag ) {
167 if ( $i != 0 ) {
168 $maxServerLag = $maxLag;
169 if ( isset( $this->mServers[$i]['max lag'] ) ) {
170 $maxServerLag = min( $maxServerLag, $this->mServers[$i]['max lag'] );
172 if ( $lag === false ) {
173 wfDebugLog( 'replication', "Server #$i is not replicating" );
174 unset( $loads[$i] );
175 } elseif ( $lag > $maxServerLag ) {
176 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
177 unset( $loads[$i] );
182 # Find out if all the slaves with non-zero load are lagged
183 $sum = 0;
184 foreach ( $loads as $load ) {
185 $sum += $load;
187 if ( $sum == 0 ) {
188 # No appropriate DB servers except maybe the master and some slaves with zero load
189 # Do NOT use the master
190 # Instead, this function will return false, triggering read-only mode,
191 # and a lagged slave will be used instead.
192 return false;
195 if ( count( $loads ) == 0 ) {
196 return false;
199 #wfDebugLog( 'connect', var_export( $loads, true ) );
201 # Return a random representative of the remainder
202 return ArrayUtils::pickRandom( $loads );
206 * Get the index of the reader connection, which may be a slave
207 * This takes into account load ratios and lag times. It should
208 * always return a consistent index during a given invocation
210 * Side effect: opens connections to databases
211 * @param string|bool $group Query group, or false for the generic reader
212 * @param string|bool $wiki Wiki ID, or false for the current wiki
213 * @throws MWException
214 * @return bool|int|string
216 public function getReaderIndex( $group = false, $wiki = false ) {
217 global $wgReadOnly, $wgDBtype;
219 # @todo FIXME: For now, only go through all this for mysql databases
220 if ( $wgDBtype != 'mysql' ) {
221 return $this->getWriterIndex();
224 if ( count( $this->mServers ) == 1 ) {
225 # Skip the load balancing if there's only one server
226 return 0;
227 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
228 # Shortcut if generic reader exists already
229 return $this->mReadIndex;
232 # Find the relevant load array
233 if ( $group !== false ) {
234 if ( isset( $this->mGroupLoads[$group] ) ) {
235 $nonErrorLoads = $this->mGroupLoads[$group];
236 } else {
237 # No loads for this group, return false and the caller can use some other group
238 wfDebug( __METHOD__ . ": no loads for group $group\n" );
240 return false;
242 } else {
243 $nonErrorLoads = $this->mLoads;
246 if ( !count( $nonErrorLoads ) ) {
247 throw new MWException( "Empty server array given to LoadBalancer" );
250 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
251 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
253 $laggedSlaveMode = false;
255 # No server found yet
256 $i = false;
257 # First try quickly looking through the available servers for a server that
258 # meets our criteria
259 $currentLoads = $nonErrorLoads;
260 while ( count( $currentLoads ) ) {
261 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
262 $i = ArrayUtils::pickRandom( $currentLoads );
263 } else {
264 $i = false;
265 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
266 # ChronologyProtecter causes mWaitForPos to be set via sessions.
267 # This triggers doWait() after connect, so it's especially good to
268 # avoid lagged servers so as to avoid just blocking in that method.
269 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
270 # Aim for <= 1 second of waiting (being too picky can backfire)
271 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
273 if ( $i === false ) {
274 # Any server with less lag than it's 'max lag' param is preferable
275 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
277 if ( $i === false && count( $currentLoads ) != 0 ) {
278 # All slaves lagged. Switch to read-only mode
279 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
280 $wgReadOnly = 'The database has been automatically locked ' .
281 'while the slave database servers catch up to the master';
282 $i = ArrayUtils::pickRandom( $currentLoads );
283 $laggedSlaveMode = true;
287 if ( $i === false ) {
288 # pickRandom() returned false
289 # This is permanent and means the configuration or the load monitor
290 # wants us to return false.
291 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
293 return false;
296 wfDebugLog( 'connect', __METHOD__ .
297 ": Using reader #$i: {$this->mServers[$i]['host']}..." );
299 $conn = $this->openConnection( $i, $wiki );
300 if ( !$conn ) {
301 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
302 unset( $nonErrorLoads[$i] );
303 unset( $currentLoads[$i] );
304 $i = false;
305 continue;
308 // Decrement reference counter, we are finished with this connection.
309 // It will be incremented for the caller later.
310 if ( $wiki !== false ) {
311 $this->reuseConnection( $conn );
314 # Return this server
315 break;
318 # If all servers were down, quit now
319 if ( !count( $nonErrorLoads ) ) {
320 wfDebugLog( 'connect', "All servers down" );
323 if ( $i !== false ) {
324 # Slave connection successful
325 # Wait for the session master pos for a short time
326 if ( $this->mWaitForPos && $i > 0 ) {
327 if ( !$this->doWait( $i ) ) {
328 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
331 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
332 $this->mReadIndex = $i;
336 return $i;
340 * Set the master wait position
341 * If a DB_SLAVE connection has been opened already, waits
342 * Otherwise sets a variable telling it to wait if such a connection is opened
343 * @param DBMasterPos $pos
345 public function waitFor( $pos ) {
346 $this->mWaitForPos = $pos;
347 $i = $this->mReadIndex;
349 if ( $i > 0 ) {
350 if ( !$this->doWait( $i ) ) {
351 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
352 $this->mLaggedSlaveMode = true;
358 * Set the master wait position and wait for ALL slaves to catch up to it
359 * @param DBMasterPos $pos
360 * @param int $timeout Max seconds to wait; default is mWaitTimeout
361 * @return bool Success (able to connect and no timeouts reached)
363 public function waitForAll( $pos, $timeout = null ) {
364 $this->mWaitForPos = $pos;
365 $serverCount = count( $this->mServers );
367 $ok = true;
368 for ( $i = 1; $i < $serverCount; $i++ ) {
369 if ( $this->mLoads[$i] > 0 ) {
370 $ok = $this->doWait( $i, true, $timeout ) && $ok;
374 return $ok;
378 * Get any open connection to a given server index, local or foreign
379 * Returns false if there is no connection open
381 * @param int $i
382 * @return DatabaseBase|bool False on failure
384 public function getAnyOpenConnection( $i ) {
385 foreach ( $this->mConns as $conns ) {
386 if ( !empty( $conns[$i] ) ) {
387 return reset( $conns[$i] );
391 return false;
395 * Wait for a given slave to catch up to the master pos stored in $this
396 * @param int $index Server index
397 * @param bool $open Check the server even if a new connection has to be made
398 * @param int $timeout Max seconds to wait; default is mWaitTimeout
399 * @return bool
401 protected function doWait( $index, $open = false, $timeout = null ) {
402 $close = false; // close the connection afterwards
404 # Find a connection to wait on, creating one if needed and allowed
405 $conn = $this->getAnyOpenConnection( $index );
406 if ( !$conn ) {
407 if ( !$open ) {
408 wfDebug( __METHOD__ . ": no connection open\n" );
410 return false;
411 } else {
412 $conn = $this->openConnection( $index, '' );
413 if ( !$conn ) {
414 wfDebug( __METHOD__ . ": failed to open connection\n" );
416 return false;
418 // Avoid connection spam in waitForAll() when connections
419 // are made just for the sake of doing this lag check.
420 $close = true;
424 wfDebug( __METHOD__ . ": Waiting for slave #$index to catch up...\n" );
425 $timeout = $timeout ?: $this->mWaitTimeout;
426 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
428 if ( $result == -1 || is_null( $result ) ) {
429 # Timed out waiting for slave, use master instead
430 $server = $this->mServers[$index]['host'];
431 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
432 wfDebug( "$msg\n" );
433 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
434 $ok = false;
435 } else {
436 wfDebug( __METHOD__ . ": Done\n" );
437 $ok = true;
440 if ( $close ) {
441 $this->closeConnection( $conn );
444 return $ok;
448 * Get a connection by index
449 * This is the main entry point for this class.
451 * @param int $i Server index
452 * @param array|string|bool $groups Query group(s), or false for the generic reader
453 * @param string|bool $wiki Wiki ID, or false for the current wiki
455 * @throws MWException
456 * @return DatabaseBase
458 public function getConnection( $i, $groups = array(), $wiki = false ) {
459 if ( $i === null || $i === false ) {
460 throw new MWException( 'Attempt to call ' . __METHOD__ .
461 ' with invalid server index' );
464 if ( $wiki === wfWikiID() ) {
465 $wiki = false;
468 $groups = ( $groups === false || $groups === array() )
469 ? array( false ) // check one "group": the generic pool
470 : (array)$groups;
472 if ( $i == DB_MASTER ) {
473 $i = $this->getWriterIndex();
474 } else {
475 # Try to find an available server in any the query groups (in order)
476 foreach ( $groups as $group ) {
477 $groupIndex = $this->getReaderIndex( $group, $wiki );
478 if ( $groupIndex !== false ) {
479 $serverName = $this->getServerName( $groupIndex );
480 wfDebug( __METHOD__ . ": using server $serverName for group '$group'\n" );
481 $i = $groupIndex;
482 break;
487 # Operation-based index
488 if ( $i == DB_SLAVE ) {
489 $this->mLastError = 'Unknown error'; // reset error string
490 # Try the general server pool if $groups are unavailable.
491 $i = in_array( false, $groups, true )
492 ? false // don't bother with this if that is what was tried above
493 : $this->getReaderIndex( false, $wiki );
494 # Couldn't find a working server in getReaderIndex()?
495 if ( $i === false ) {
496 $this->mLastError = 'No working slave server: ' . $this->mLastError;
498 return $this->reportConnectionError();
502 # Now we have an explicit index into the servers array
503 $conn = $this->openConnection( $i, $wiki );
504 if ( !$conn ) {
506 return $this->reportConnectionError();
509 return $conn;
513 * Mark a foreign connection as being available for reuse under a different
514 * DB name or prefix. This mechanism is reference-counted, and must be called
515 * the same number of times as getConnection() to work.
517 * @param DatabaseBase $conn
518 * @throws MWException
520 public function reuseConnection( $conn ) {
521 $serverIndex = $conn->getLBInfo( 'serverIndex' );
522 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
523 if ( $serverIndex === null || $refCount === null ) {
524 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
527 * This can happen in code like:
528 * foreach ( $dbs as $db ) {
529 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
530 * ...
531 * $lb->reuseConnection( $conn );
533 * When a connection to the local DB is opened in this way, reuseConnection()
534 * should be ignored
537 return;
540 $dbName = $conn->getDBname();
541 $prefix = $conn->tablePrefix();
542 if ( strval( $prefix ) !== '' ) {
543 $wiki = "$dbName-$prefix";
544 } else {
545 $wiki = $dbName;
547 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
548 throw new MWException( __METHOD__ . ": connection not found, has " .
549 "the connection been freed already?" );
551 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
552 if ( $refCount <= 0 ) {
553 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
554 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
555 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
556 } else {
557 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
562 * Get a database connection handle reference
564 * The handle's methods wrap simply wrap those of a DatabaseBase handle
566 * @see LoadBalancer::getConnection() for parameter information
568 * @param int $db
569 * @param array|string|bool $groups Query group(s), or false for the generic reader
570 * @param string|bool $wiki Wiki ID, or false for the current wiki
571 * @return DBConnRef
573 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
574 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
578 * Get a database connection handle reference without connecting yet
580 * The handle's methods wrap simply wrap those of a DatabaseBase handle
582 * @see LoadBalancer::getConnection() for parameter information
584 * @param int $db
585 * @param array|string|bool $groups Query group(s), or false for the generic reader
586 * @param string|bool $wiki Wiki ID, or false for the current wiki
587 * @return DBConnRef
589 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
590 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
594 * Open a connection to the server given by the specified index
595 * Index must be an actual index into the array.
596 * If the server is already open, returns it.
598 * On error, returns false, and the connection which caused the
599 * error will be available via $this->mErrorConnection.
601 * @param int $i Server index
602 * @param string|bool $wiki Wiki ID, or false for the current wiki
603 * @return DatabaseBase
605 * @access private
607 public function openConnection( $i, $wiki = false ) {
608 if ( $wiki !== false ) {
609 $conn = $this->openForeignConnection( $i, $wiki );
611 return $conn;
613 if ( isset( $this->mConns['local'][$i][0] ) ) {
614 $conn = $this->mConns['local'][$i][0];
615 } else {
616 $server = $this->mServers[$i];
617 $server['serverIndex'] = $i;
618 $conn = $this->reallyOpenConnection( $server, false );
619 if ( $conn->isOpen() ) {
620 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
621 $this->mConns['local'][$i][0] = $conn;
622 } else {
623 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
624 $this->mErrorConnection = $conn;
625 $conn = false;
629 return $conn;
633 * Open a connection to a foreign DB, or return one if it is already open.
635 * Increments a reference count on the returned connection which locks the
636 * connection to the requested wiki. This reference count can be
637 * decremented by calling reuseConnection().
639 * If a connection is open to the appropriate server already, but with the wrong
640 * database, it will be switched to the right database and returned, as long as
641 * it has been freed first with reuseConnection().
643 * On error, returns false, and the connection which caused the
644 * error will be available via $this->mErrorConnection.
646 * @param int $i Server index
647 * @param string $wiki Wiki ID to open
648 * @return DatabaseBase
650 private function openForeignConnection( $i, $wiki ) {
651 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
652 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
653 // Reuse an already-used connection
654 $conn = $this->mConns['foreignUsed'][$i][$wiki];
655 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
656 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
657 // Reuse a free connection for the same wiki
658 $conn = $this->mConns['foreignFree'][$i][$wiki];
659 unset( $this->mConns['foreignFree'][$i][$wiki] );
660 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
661 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
662 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
663 // Reuse a connection from another wiki
664 $conn = reset( $this->mConns['foreignFree'][$i] );
665 $oldWiki = key( $this->mConns['foreignFree'][$i] );
667 // The empty string as a DB name means "don't care".
668 // DatabaseMysqlBase::open() already handle this on connection.
669 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
670 $this->mLastError = "Error selecting database $dbName on server " .
671 $conn->getServer() . " from client host " . wfHostname() . "\n";
672 $this->mErrorConnection = $conn;
673 $conn = false;
674 } else {
675 $conn->tablePrefix( $prefix );
676 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
677 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
678 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
680 } else {
681 // Open a new connection
682 $server = $this->mServers[$i];
683 $server['serverIndex'] = $i;
684 $server['foreignPoolRefCount'] = 0;
685 $server['foreign'] = true;
686 $conn = $this->reallyOpenConnection( $server, $dbName );
687 if ( !$conn->isOpen() ) {
688 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
689 $this->mErrorConnection = $conn;
690 $conn = false;
691 } else {
692 $conn->tablePrefix( $prefix );
693 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
694 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
698 // Increment reference count
699 if ( $conn ) {
700 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
701 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
704 return $conn;
708 * Test if the specified index represents an open connection
710 * @param int $index Server index
711 * @access private
712 * @return bool
714 private function isOpen( $index ) {
715 if ( !is_integer( $index ) ) {
716 return false;
719 return (bool)$this->getAnyOpenConnection( $index );
723 * Really opens a connection. Uncached.
724 * Returns a Database object whether or not the connection was successful.
725 * @access private
727 * @param array $server
728 * @param bool $dbNameOverride
729 * @throws MWException
730 * @return DatabaseBase
732 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
733 if ( !is_array( $server ) ) {
734 throw new MWException( 'You must update your load-balancing configuration. ' .
735 'See DefaultSettings.php entry for $wgDBservers.' );
738 if ( $dbNameOverride !== false ) {
739 $server['dbname'] = $dbNameOverride;
742 // Log when many connection are made on requests
743 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
744 $masterAddr = $this->getServerName( 0 );
745 wfDebugLog( 'DBPerformance', __METHOD__ . ": " .
746 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
747 wfBacktrace( true ) );
750 # Create object
751 try {
752 $db = DatabaseBase::factory( $server['type'], $server );
753 } catch ( DBConnectionError $e ) {
754 // FIXME: This is probably the ugliest thing I have ever done to
755 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
756 $db = $e->db;
759 $db->setLBInfo( $server );
760 if ( isset( $server['fakeSlaveLag'] ) ) {
761 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
763 if ( isset( $server['fakeMaster'] ) ) {
764 $db->setFakeMaster( true );
767 return $db;
771 * @throws DBConnectionError
772 * @return bool
774 private function reportConnectionError() {
775 $conn = $this->mErrorConnection; // The connection which caused the error
776 $context = array(
777 'method' => __METHOD__,
778 'last_error' => $this->mLastError,
781 if ( !is_object( $conn ) ) {
782 // No last connection, probably due to all servers being too busy
783 wfLogDBError(
784 "LB failure with no last connection. Connection error: {last_error}",
785 $context
788 // If all servers were busy, mLastError will contain something sensible
789 throw new DBConnectionError( null, $this->mLastError );
790 } else {
791 $context['db_server'] = $conn->getProperty( 'mServer' );
792 wfLogDBError(
793 "Connection error: {last_error} ({db_server})",
794 $context
796 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
799 return false; /* not reached */
803 * @return int
805 private function getWriterIndex() {
806 return 0;
810 * Returns true if the specified index is a valid server index
812 * @param string $i
813 * @return bool
815 public function haveIndex( $i ) {
816 return array_key_exists( $i, $this->mServers );
820 * Returns true if the specified index is valid and has non-zero load
822 * @param string $i
823 * @return bool
825 public function isNonZeroLoad( $i ) {
826 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
830 * Get the number of defined servers (not the number of open connections)
832 * @return int
834 public function getServerCount() {
835 return count( $this->mServers );
839 * Get the host name or IP address of the server with the specified index
840 * Prefer a readable name if available.
841 * @param string $i
842 * @return string
844 public function getServerName( $i ) {
845 if ( isset( $this->mServers[$i]['hostName'] ) ) {
846 return $this->mServers[$i]['hostName'];
847 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
848 return $this->mServers[$i]['host'];
849 } else {
850 return '';
855 * Return the server info structure for a given index, or false if the index is invalid.
856 * @param int $i
857 * @return array|bool
859 public function getServerInfo( $i ) {
860 if ( isset( $this->mServers[$i] ) ) {
861 return $this->mServers[$i];
862 } else {
863 return false;
868 * Sets the server info structure for the given index. Entry at index $i
869 * is created if it doesn't exist
870 * @param int $i
871 * @param array $serverInfo
873 public function setServerInfo( $i, array $serverInfo ) {
874 $this->mServers[$i] = $serverInfo;
878 * Get the current master position for chronology control purposes
879 * @return mixed
881 public function getMasterPos() {
882 # If this entire request was served from a slave without opening a connection to the
883 # master (however unlikely that may be), then we can fetch the position from the slave.
884 $masterConn = $this->getAnyOpenConnection( 0 );
885 if ( !$masterConn ) {
886 $serverCount = count( $this->mServers );
887 for ( $i = 1; $i < $serverCount; $i++ ) {
888 $conn = $this->getAnyOpenConnection( $i );
889 if ( $conn ) {
890 wfDebug( "Master pos fetched from slave\n" );
892 return $conn->getSlavePos();
895 } else {
896 wfDebug( "Master pos fetched from master\n" );
898 return $masterConn->getMasterPos();
901 return false;
905 * Close all open connections
907 public function closeAll() {
908 foreach ( $this->mConns as $conns2 ) {
909 foreach ( $conns2 as $conns3 ) {
910 /** @var DatabaseBase $conn */
911 foreach ( $conns3 as $conn ) {
912 $conn->close();
916 $this->mConns = array(
917 'local' => array(),
918 'foreignFree' => array(),
919 'foreignUsed' => array(),
921 $this->connsOpened = 0;
925 * Close a connection
926 * Using this function makes sure the LoadBalancer knows the connection is closed.
927 * If you use $conn->close() directly, the load balancer won't update its state.
928 * @param DatabaseBase $conn
930 public function closeConnection( $conn ) {
931 $done = false;
932 foreach ( $this->mConns as $i1 => $conns2 ) {
933 foreach ( $conns2 as $i2 => $conns3 ) {
934 foreach ( $conns3 as $i3 => $candidateConn ) {
935 if ( $conn === $candidateConn ) {
936 $conn->close();
937 unset( $this->mConns[$i1][$i2][$i3] );
938 --$this->connsOpened;
939 $done = true;
940 break;
945 if ( !$done ) {
946 $conn->close();
951 * Commit transactions on all open connections
953 public function commitAll() {
954 foreach ( $this->mConns as $conns2 ) {
955 foreach ( $conns2 as $conns3 ) {
956 /** @var DatabaseBase[] $conns3 */
957 foreach ( $conns3 as $conn ) {
958 if ( $conn->trxLevel() ) {
959 $conn->commit( __METHOD__, 'flush' );
967 * Issue COMMIT only on master, only if queries were done on connection
969 public function commitMasterChanges() {
970 // Always 0, but who knows.. :)
971 $masterIndex = $this->getWriterIndex();
972 foreach ( $this->mConns as $conns2 ) {
973 if ( empty( $conns2[$masterIndex] ) ) {
974 continue;
976 /** @var DatabaseBase $conn */
977 foreach ( $conns2[$masterIndex] as $conn ) {
978 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
979 $conn->commit( __METHOD__, 'flush' );
986 * Issue ROLLBACK only on master, only if queries were done on connection
987 * @since 1.23
989 public function rollbackMasterChanges() {
990 // Always 0, but who knows.. :)
991 $masterIndex = $this->getWriterIndex();
992 foreach ( $this->mConns as $conns2 ) {
993 if ( empty( $conns2[$masterIndex] ) ) {
994 continue;
996 /** @var DatabaseBase $conn */
997 foreach ( $conns2[$masterIndex] as $conn ) {
998 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
999 $conn->rollback( __METHOD__, 'flush' );
1006 * @return bool Whether a master connection is already open
1007 * @since 1.24
1009 public function hasMasterConnection() {
1010 return $this->isOpen( $this->getWriterIndex() );
1014 * Determine if there are any pending changes that need to be rolled back
1015 * or committed.
1016 * @since 1.23
1017 * @return bool
1019 public function hasMasterChanges() {
1020 // Always 0, but who knows.. :)
1021 $masterIndex = $this->getWriterIndex();
1022 foreach ( $this->mConns as $conns2 ) {
1023 if ( empty( $conns2[$masterIndex] ) ) {
1024 continue;
1026 /** @var DatabaseBase $conn */
1027 foreach ( $conns2[$masterIndex] as $conn ) {
1028 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1029 return true;
1033 return false;
1037 * @param mixed $value
1038 * @return mixed
1040 public function waitTimeout( $value = null ) {
1041 return wfSetVar( $this->mWaitTimeout, $value );
1045 * @return bool
1047 public function getLaggedSlaveMode() {
1048 return $this->mLaggedSlaveMode;
1052 * Disables/enables lag checks
1053 * @param null|bool $mode
1054 * @return bool
1056 public function allowLagged( $mode = null ) {
1057 if ( $mode === null ) {
1058 return $this->mAllowLagged;
1060 $this->mAllowLagged = $mode;
1062 return $this->mAllowLagged;
1066 * @return bool
1068 public function pingAll() {
1069 $success = true;
1070 foreach ( $this->mConns as $conns2 ) {
1071 foreach ( $conns2 as $conns3 ) {
1072 /** @var DatabaseBase[] $conns3 */
1073 foreach ( $conns3 as $conn ) {
1074 if ( !$conn->ping() ) {
1075 $success = false;
1081 return $success;
1085 * Call a function with each open connection object
1086 * @param callable $callback
1087 * @param array $params
1089 public function forEachOpenConnection( $callback, array $params = array() ) {
1090 foreach ( $this->mConns as $conns2 ) {
1091 foreach ( $conns2 as $conns3 ) {
1092 foreach ( $conns3 as $conn ) {
1093 $mergedParams = array_merge( array( $conn ), $params );
1094 call_user_func_array( $callback, $mergedParams );
1101 * Get the hostname and lag time of the most-lagged slave
1103 * This is useful for maintenance scripts that need to throttle their updates.
1104 * May attempt to open connections to slaves on the default DB. If there is
1105 * no lag, the maximum lag will be reported as -1.
1107 * @param bool|string $wiki Wiki ID, or false for the default database
1108 * @return array ( host, max lag, index of max lagged host )
1110 public function getMaxLag( $wiki = false ) {
1111 $maxLag = -1;
1112 $host = '';
1113 $maxIndex = 0;
1115 if ( $this->getServerCount() <= 1 ) {
1116 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1119 $lagTimes = $this->getLagTimes( $wiki );
1120 foreach ( $lagTimes as $i => $lag ) {
1121 if ( $lag > $maxLag ) {
1122 $maxLag = $lag;
1123 $host = $this->mServers[$i]['host'];
1124 $maxIndex = $i;
1128 return array( $host, $maxLag, $maxIndex );
1132 * Get lag time for each server
1134 * Results are cached for a short time in memcached/process cache
1136 * @param string|bool $wiki
1137 * @return int[] Map of (server index => seconds)
1139 public function getLagTimes( $wiki = false ) {
1140 if ( $this->getServerCount() <= 1 ) {
1141 return array( 0 => 0 ); // no replication = no lag
1144 if ( $this->mProcCache->has( 'slave_lag', 'times', 1 ) ) {
1145 return $this->mProcCache->get( 'slave_lag', 'times' );
1148 # Send the request to the load monitor
1149 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1151 $this->mProcCache->set( 'slave_lag', 'times', $times );
1153 return $times;
1157 * Get the lag in seconds for a given connection, or zero if this load
1158 * balancer does not have replication enabled.
1160 * This should be used in preference to Database::getLag() in cases where
1161 * replication may not be in use, since there is no way to determine if
1162 * replication is in use at the connection level without running
1163 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1164 * function instead of Database::getLag() avoids a fatal error in this
1165 * case on many installations.
1167 * @param DatabaseBase $conn
1168 * @return int
1170 public function safeGetLag( $conn ) {
1171 if ( $this->getServerCount() == 1 ) {
1172 return 0;
1173 } else {
1174 return $conn->getLag();
1179 * Clear the cache for slag lag delay times
1181 public function clearLagTimeCache() {
1182 $this->mProcCache->clear( 'slave_lag' );
1187 * Helper class to handle automatically marking connections as reusable (via RAII pattern)
1188 * as well handling deferring the actual network connection until the handle is used
1190 * @ingroup Database
1191 * @since 1.22
1193 class DBConnRef implements IDatabase {
1194 /** @var LoadBalancer */
1195 private $lb;
1197 /** @var DatabaseBase|null */
1198 private $conn;
1200 /** @var array|null */
1201 private $params;
1204 * @param LoadBalancer $lb
1205 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1207 public function __construct( LoadBalancer $lb, $conn ) {
1208 $this->lb = $lb;
1209 if ( $conn instanceof DatabaseBase ) {
1210 $this->conn = $conn;
1211 } else {
1212 $this->params = $conn;
1216 public function __call( $name, $arguments ) {
1217 if ( $this->conn === null ) {
1218 list( $db, $groups, $wiki ) = $this->params;
1219 $this->conn = $this->lb->getConnection( $db, $groups, $wiki );
1222 return call_user_func_array( array( $this->conn, $name ), $arguments );
1225 public function __destruct() {
1226 if ( $this->conn !== null ) {
1227 $this->lb->reuseConnection( $this->conn );