3 * Database load balancing manager
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
23 namespace Wikimedia\Rdbms
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
27 use Wikimedia\ScopedCallback
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var array[] Map of (server index => server config array) */
44 /** @var Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase[] */
46 /** @var float[] Map of (server index => weight) */
48 /** @var array[] Map of (group => server index => weight) */
50 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
51 private $mAllowLagged;
52 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
53 private $mWaitTimeout;
54 /** @var array The LoadMonitor configuration */
55 private $loadMonitorConfig;
56 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
57 private $tableAliases = [];
59 /** @var ILoadMonitor */
61 /** @var ChronologyProtector|null */
65 /** @var WANObjectCache */
67 /** @var object|string Class name or object With profileIn/profileOut methods */
69 /** @var TransactionProfiler */
70 protected $trxProfiler;
71 /** @var LoggerInterface */
72 protected $replLogger;
73 /** @var LoggerInterface */
74 protected $connLogger;
75 /** @var LoggerInterface */
76 protected $queryLogger;
77 /** @var LoggerInterface */
78 protected $perfLogger;
80 /** @var Database DB connection object that caused a problem */
81 private $errorConnection;
82 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
84 /** @var bool|DBMasterPos False if not set */
86 /** @var bool Whether the generic reader fell back to a lagged replica DB */
87 private $laggedReplicaMode = false;
88 /** @var bool Whether the generic reader fell back to a lagged replica DB */
89 private $allReplicasDownMode = false;
90 /** @var string The last DB selection or connection error */
91 private $mLastError = 'Unknown error';
92 /** @var string|bool Reason the LB is read-only or false if not */
93 private $readOnlyReason = false;
94 /** @var integer Total connections opened */
95 private $connsOpened = 0;
96 /** @var string|bool String if a requested DBO_TRX transaction round is active */
97 private $trxRoundId = false;
98 /** @var array[] Map of (name => callable) */
99 private $trxRecurringCallbacks = [];
100 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
101 private $localDomain;
102 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
103 private $localDomainIdAlias;
104 /** @var string Current server name */
106 /** @var bool Whether this PHP instance is for a CLI script */
108 /** @var string Agent name for query profiling */
111 /** @var callable Exception logger */
112 private $errorLogger;
115 private $disabled = false;
117 private $chronProtInitialized = false;
119 /** @var integer Warn when this many connection are held */
120 const CONN_HELD_WARN_THRESHOLD
= 10;
122 /** @var integer Default 'max lag' when unspecified */
123 const MAX_LAG_DEFAULT
= 10;
124 /** @var integer Seconds to cache master server read-only status */
125 const TTL_CACHE_READONLY
= 5;
127 const KEY_LOCAL
= 'local';
128 const KEY_FOREIGN_FREE
= 'foreignFree';
129 const KEY_FOREIGN_INUSE
= 'foreignInUse';
131 public function __construct( array $params ) {
132 if ( !isset( $params['servers'] ) ) {
133 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
135 $this->mServers
= $params['servers'];
137 $this->localDomain
= isset( $params['localDomain'] )
138 ? DatabaseDomain
::newFromId( $params['localDomain'] )
139 : DatabaseDomain
::newUnspecified();
140 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
141 // always true, gracefully handle the case when they fail to account for escaping.
142 if ( $this->localDomain
->getTablePrefix() != '' ) {
143 $this->localDomainIdAlias
=
144 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
146 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
149 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
151 $this->mReadIndex
= -1;
153 self
::KEY_LOCAL
=> [],
154 self
::KEY_FOREIGN_INUSE
=> [],
155 self
::KEY_FOREIGN_FREE
=> []
158 $this->mWaitForPos
= false;
159 $this->mAllowLagged
= false;
161 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
162 $this->readOnlyReason
= $params['readOnlyReason'];
165 if ( isset( $params['loadMonitor'] ) ) {
166 $this->loadMonitorConfig
= $params['loadMonitor'];
168 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
171 foreach ( $params['servers'] as $i => $server ) {
172 $this->mLoads
[$i] = $server['load'];
173 if ( isset( $server['groupLoads'] ) ) {
174 foreach ( $server['groupLoads'] as $group => $ratio ) {
175 if ( !isset( $this->mGroupLoads
[$group] ) ) {
176 $this->mGroupLoads
[$group] = [];
178 $this->mGroupLoads
[$group][$i] = $ratio;
183 if ( isset( $params['srvCache'] ) ) {
184 $this->srvCache
= $params['srvCache'];
186 $this->srvCache
= new EmptyBagOStuff();
188 if ( isset( $params['wanCache'] ) ) {
189 $this->wanCache
= $params['wanCache'];
191 $this->wanCache
= WANObjectCache
::newEmpty();
193 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
194 if ( isset( $params['trxProfiler'] ) ) {
195 $this->trxProfiler
= $params['trxProfiler'];
197 $this->trxProfiler
= new TransactionProfiler();
200 $this->errorLogger
= isset( $params['errorLogger'] )
201 ?
$params['errorLogger']
202 : function ( Exception
$e ) {
203 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
206 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
207 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
210 $this->host
= isset( $params['hostname'] )
211 ?
$params['hostname']
212 : ( gethostname() ?
: 'unknown' );
213 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
214 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
216 if ( isset( $params['chronologyProtector'] ) ) {
217 $this->chronProt
= $params['chronologyProtector'];
222 * Get a LoadMonitor instance
224 * @return ILoadMonitor
226 private function getLoadMonitor() {
227 if ( !isset( $this->loadMonitor
) ) {
229 'LoadMonitor' => LoadMonitor
::class,
230 'LoadMonitorNull' => LoadMonitorNull
::class,
231 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
234 $class = $this->loadMonitorConfig
['class'];
235 if ( isset( $compat[$class] ) ) {
236 $class = $compat[$class];
239 $this->loadMonitor
= new $class(
240 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
241 $this->loadMonitor
->setLogger( $this->replLogger
);
244 return $this->loadMonitor
;
248 * @param array $loads
249 * @param bool|string $domain Domain to get non-lagged for
250 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
251 * @return bool|int|string
253 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
254 $lags = $this->getLagTimes( $domain );
256 # Unset excessively lagged servers
257 foreach ( $lags as $i => $lag ) {
259 # How much lag this server nominally is allowed to have
260 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
261 ?
$this->mServers
[$i]['max lag']
262 : self
::MAX_LAG_DEFAULT
; // default
263 # Constrain that futher by $maxLag argument
264 $maxServerLag = min( $maxServerLag, $maxLag );
266 $host = $this->getServerName( $i );
267 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
268 $this->replLogger
->error(
269 "Server {host} is not replicating?", [ 'host' => $host ] );
271 } elseif ( $lag > $maxServerLag ) {
272 $this->replLogger
->warning(
273 "Server {host} has {lag} seconds of lag (>= {maxlag})",
274 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
281 # Find out if all the replica DBs with non-zero load are lagged
283 foreach ( $loads as $load ) {
287 # No appropriate DB servers except maybe the master and some replica DBs with zero load
288 # Do NOT use the master
289 # Instead, this function will return false, triggering read-only mode,
290 # and a lagged replica DB will be used instead.
294 if ( count( $loads ) == 0 ) {
298 # Return a random representative of the remainder
299 return ArrayUtils
::pickRandom( $loads );
302 public function getReaderIndex( $group = false, $domain = false ) {
303 if ( count( $this->mServers
) == 1 ) {
304 // Skip the load balancing if there's only one server
305 return $this->getWriterIndex();
306 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
307 // Shortcut if the generic reader index was already cached
308 return $this->mReadIndex
;
311 if ( $group !== false ) {
312 // Use the server weight array for this load group
313 if ( isset( $this->mGroupLoads
[$group] ) ) {
314 $loads = $this->mGroupLoads
[$group];
316 // No loads for this group, return false and the caller can use some other group
317 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
322 // Use the generic load group
323 $loads = $this->mLoads
;
326 // Scale the configured load ratios according to each server's load and state
327 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
329 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
330 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
331 if ( $i === false ) {
332 // Replica DB connection unsuccessful
336 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
337 // Before any data queries are run, wait for the server to catch up to the
338 // specified position. This is used to improve session consistency. Note that
339 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
340 // so update laggedReplicaMode as needed for consistency.
341 if ( !$this->doWait( $i ) ) {
342 $laggedReplicaMode = true;
346 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
347 // Cache the generic reader index for future ungrouped DB_REPLICA handles
348 $this->mReadIndex
= $i;
349 // Record if the generic reader index is in "lagged replica DB" mode
350 if ( $laggedReplicaMode ) {
351 $this->laggedReplicaMode
= true;
355 $serverName = $this->getServerName( $i );
356 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
362 * @param array $loads List of server weights
363 * @param string|bool $domain
364 * @return array (reader index, lagged replica mode) or false on failure
366 private function pickReaderIndex( array $loads, $domain = false ) {
367 if ( !count( $loads ) ) {
368 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
371 /** @var $i int|bool Index of selected server */
373 /** @var $laggedReplicaMode bool Whether server is considered lagged */
374 $laggedReplicaMode = false;
376 // Quickly look through the available servers for a server that meets criteria...
377 $currentLoads = $loads;
378 while ( count( $currentLoads ) ) {
379 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
380 $i = ArrayUtils
::pickRandom( $currentLoads );
383 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
384 // ChronologyProtecter sets mWaitForPos for session consistency.
385 // This triggers doWait() after connect, so it's especially good to
386 // avoid lagged servers so as to avoid excessive delay in that method.
387 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
388 // Aim for <= 1 second of waiting (being too picky can backfire)
389 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
391 if ( $i === false ) {
392 // Any server with less lag than it's 'max lag' param is preferable
393 $i = $this->getRandomNonLagged( $currentLoads, $domain );
395 if ( $i === false && count( $currentLoads ) != 0 ) {
396 // All replica DBs lagged. Switch to read-only mode
397 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
398 $i = ArrayUtils
::pickRandom( $currentLoads );
399 $laggedReplicaMode = true;
403 if ( $i === false ) {
404 // pickRandom() returned false.
405 // This is permanent and means the configuration or the load monitor
406 // wants us to return false.
407 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
409 return [ false, false ];
412 $serverName = $this->getServerName( $i );
413 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
415 $conn = $this->openConnection( $i, $domain );
417 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
418 unset( $currentLoads[$i] ); // avoid this server next iteration
423 // Decrement reference counter, we are finished with this connection.
424 // It will be incremented for the caller later.
425 if ( $domain !== false ) {
426 $this->reuseConnection( $conn );
429 // Return this server
433 // If all servers were down, quit now
434 if ( !count( $currentLoads ) ) {
435 $this->connLogger
->error( "All servers down" );
438 return [ $i, $laggedReplicaMode ];
441 public function waitFor( $pos ) {
442 $oldPos = $this->mWaitForPos
;
444 $this->mWaitForPos
= $pos;
445 // If a generic reader connection was already established, then wait now
446 $i = $this->mReadIndex
;
448 if ( !$this->doWait( $i ) ) {
449 $this->laggedReplicaMode
= true;
453 // Restore the older position if it was higher since this is used for lag-protection
454 $this->setWaitForPositionIfHigher( $oldPos );
458 public function waitForOne( $pos, $timeout = null ) {
459 $oldPos = $this->mWaitForPos
;
461 $this->mWaitForPos
= $pos;
463 $i = $this->mReadIndex
;
465 // Pick a generic replica DB if there isn't one yet
466 $readLoads = $this->mLoads
;
467 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
468 $readLoads = array_filter( $readLoads ); // with non-zero load
469 $i = ArrayUtils
::pickRandom( $readLoads );
473 $ok = $this->doWait( $i, true, $timeout );
475 $ok = true; // no applicable loads
478 # Restore the old position, as this is not used for lag-protection but for throttling
479 $this->mWaitForPos
= $oldPos;
485 public function waitForAll( $pos, $timeout = null ) {
486 $oldPos = $this->mWaitForPos
;
488 $this->mWaitForPos
= $pos;
489 $serverCount = count( $this->mServers
);
492 for ( $i = 1; $i < $serverCount; $i++
) {
493 if ( $this->mLoads
[$i] > 0 ) {
494 $ok = $this->doWait( $i, true, $timeout ) && $ok;
498 # Restore the old position, as this is not used for lag-protection but for throttling
499 $this->mWaitForPos
= $oldPos;
506 * @param DBMasterPos|bool $pos
508 private function setWaitForPositionIfHigher( $pos ) {
513 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
514 $this->mWaitForPos
= $pos;
520 * @return IDatabase|bool
522 public function getAnyOpenConnection( $i ) {
523 foreach ( $this->mConns
as $connsByServer ) {
524 if ( !empty( $connsByServer[$i] ) ) {
525 /** @var $serverConns IDatabase[] */
526 $serverConns = $connsByServer[$i];
528 return reset( $serverConns );
536 * Wait for a given replica DB to catch up to the master pos stored in $this
537 * @param int $index Server index
538 * @param bool $open Check the server even if a new connection has to be made
539 * @param int $timeout Max seconds to wait; default is mWaitTimeout
542 protected function doWait( $index, $open = false, $timeout = null ) {
543 $close = false; // close the connection afterwards
545 // Check if we already know that the DB has reached this point
546 $server = $this->getServerName( $index );
547 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
548 /** @var DBMasterPos $knownReachedPos */
549 $knownReachedPos = $this->srvCache
->get( $key );
551 $knownReachedPos instanceof DBMasterPos
&&
552 $knownReachedPos->hasReached( $this->mWaitForPos
)
554 $this->replLogger
->debug( __METHOD__
.
555 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
559 // Find a connection to wait on, creating one if needed and allowed
560 $conn = $this->getAnyOpenConnection( $index );
563 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
567 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
569 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
573 // Avoid connection spam in waitForAll() when connections
574 // are made just for the sake of doing this lag check.
579 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
580 $timeout = $timeout ?
: $this->mWaitTimeout
;
581 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
583 if ( $result == -1 ||
is_null( $result ) ) {
584 // Timed out waiting for replica DB, use master instead
585 $this->replLogger
->warning(
586 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
587 [ 'host' => $server ]
591 $this->replLogger
->info( __METHOD__
. ": Done" );
593 // Remember that the DB reached this point
594 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
598 $this->closeConnection( $conn );
605 * @see ILoadBalancer::getConnection()
608 * @param array $groups
609 * @param bool $domain
611 * @throws DBConnectionError
613 public function getConnection( $i, $groups = [], $domain = false ) {
614 if ( $i === null ||
$i === false ) {
615 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
616 ' with invalid server index' );
619 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
620 $domain = false; // local connection requested
623 $groups = ( $groups === false ||
$groups === [] )
624 ?
[ false ] // check one "group": the generic pool
627 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
628 $oldConnsOpened = $this->connsOpened
; // connections open now
630 if ( $i == self
::DB_MASTER
) {
631 $i = $this->getWriterIndex();
633 # Try to find an available server in any the query groups (in order)
634 foreach ( $groups as $group ) {
635 $groupIndex = $this->getReaderIndex( $group, $domain );
636 if ( $groupIndex !== false ) {
643 # Operation-based index
644 if ( $i == self
::DB_REPLICA
) {
645 $this->mLastError
= 'Unknown error'; // reset error string
646 # Try the general server pool if $groups are unavailable.
647 $i = ( $groups === [ false ] )
648 ?
false // don't bother with this if that is what was tried above
649 : $this->getReaderIndex( false, $domain );
650 # Couldn't find a working server in getReaderIndex()?
651 if ( $i === false ) {
652 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
653 // Throw an exception
654 $this->reportConnectionError();
655 return null; // not reached
659 # Now we have an explicit index into the servers array
660 $conn = $this->openConnection( $i, $domain );
662 // Throw an exception
663 $this->reportConnectionError();
664 return null; // not reached
667 # Profile any new connections that happen
668 if ( $this->connsOpened
> $oldConnsOpened ) {
669 $host = $conn->getServer();
670 $dbname = $conn->getDBname();
671 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
675 # Make master-requested DB handles inherit any read-only mode setting
676 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
682 public function reuseConnection( $conn ) {
683 $serverIndex = $conn->getLBInfo( 'serverIndex' );
684 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
685 if ( $serverIndex === null ||
$refCount === null ) {
687 * This can happen in code like:
688 * foreach ( $dbs as $db ) {
689 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
691 * $lb->reuseConnection( $conn );
693 * When a connection to the local DB is opened in this way, reuseConnection()
697 } elseif ( $conn instanceof DBConnRef
) {
698 // DBConnRef already handles calling reuseConnection() and only passes the live
699 // Database instance to this method. Any caller passing in a DBConnRef is broken.
700 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
701 ( new RuntimeException() )->getTraceAsString() );
706 if ( $this->disabled
) {
707 return; // DBConnRef handle probably survived longer than the LoadBalancer
710 $domain = $conn->getDomainID();
711 if ( !isset( $this->mConns
[self
::KEY_FOREIGN_INUSE
][$serverIndex][$domain] ) ) {
712 throw new InvalidArgumentException( __METHOD__
.
713 ": connection $serverIndex/$domain not found; it may have already been freed." );
714 } elseif ( $this->mConns
[self
::KEY_FOREIGN_INUSE
][$serverIndex][$domain] !== $conn ) {
715 throw new InvalidArgumentException( __METHOD__
.
716 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
718 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
719 if ( $refCount <= 0 ) {
720 $this->mConns
[self
::KEY_FOREIGN_FREE
][$serverIndex][$domain] = $conn;
721 unset( $this->mConns
[self
::KEY_FOREIGN_INUSE
][$serverIndex][$domain] );
722 if ( !$this->mConns
[self
::KEY_FOREIGN_INUSE
][$serverIndex] ) {
723 unset( $this->mConns
[ self
::KEY_FOREIGN_INUSE
][$serverIndex] ); // clean up
725 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
727 $this->connLogger
->debug( __METHOD__
.
728 ": reference count for $serverIndex/$domain reduced to $refCount" );
732 public function getConnectionRef( $db, $groups = [], $domain = false ) {
733 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
735 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
738 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
739 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
741 return new DBConnRef( $this, [ $db, $groups, $domain ] );
744 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
745 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
747 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
751 * @see ILoadBalancer::openConnection()
754 * @param bool $domain
755 * @return bool|Database
756 * @throws DBAccessError
758 public function openConnection( $i, $domain = false ) {
759 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
760 $domain = false; // local connection requested
763 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
764 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
765 // Load CP positions before connecting so that doWait() triggers later if needed
766 $this->chronProtInitialized
= true;
767 $this->chronProt
->initLB( $this );
770 if ( $domain !== false ) {
771 $conn = $this->openForeignConnection( $i, $domain );
772 } elseif ( isset( $this->mConns
[self
::KEY_LOCAL
][$i][0] ) ) {
773 $conn = $this->mConns
[self
::KEY_LOCAL
][$i][0];
775 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
776 throw new InvalidArgumentException( "No server with index '$i'." );
778 // Open a new connection
779 $server = $this->mServers
[$i];
780 $server['serverIndex'] = $i;
781 $conn = $this->reallyOpenConnection( $server, false );
782 $serverName = $this->getServerName( $i );
783 if ( $conn->isOpen() ) {
784 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
785 $this->mConns
[self
::KEY_LOCAL
][$i][0] = $conn;
787 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
788 $this->errorConnection
= $conn;
793 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
794 // Connection was made but later unrecoverably lost for some reason.
795 // Do not return a handle that will just throw exceptions on use,
796 // but let the calling code (e.g. getReaderIndex) try another server.
797 // See DatabaseMyslBase::ping() for how this can happen.
798 $this->errorConnection
= $conn;
806 * Open a connection to a foreign DB, or return one if it is already open.
808 * Increments a reference count on the returned connection which locks the
809 * connection to the requested domain. This reference count can be
810 * decremented by calling reuseConnection().
812 * If a connection is open to the appropriate server already, but with the wrong
813 * database, it will be switched to the right database and returned, as long as
814 * it has been freed first with reuseConnection().
816 * On error, returns false, and the connection which caused the
817 * error will be available via $this->errorConnection.
819 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
821 * @param int $i Server index
822 * @param string $domain Domain ID to open
825 private function openForeignConnection( $i, $domain ) {
826 $domainInstance = DatabaseDomain
::newFromId( $domain );
827 $dbName = $domainInstance->getDatabase();
828 $prefix = $domainInstance->getTablePrefix();
830 if ( isset( $this->mConns
[self
::KEY_FOREIGN_INUSE
][$i][$domain] ) ) {
831 // Reuse an in-use connection for the same domain that is not in-use
832 $conn = $this->mConns
[self
::KEY_FOREIGN_INUSE
][$i][$domain];
833 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
834 } elseif ( isset( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i][$domain] ) ) {
835 // Reuse a free connection for the same domain that is not in-use
836 $conn = $this->mConns
[self
::KEY_FOREIGN_FREE
][$i][$domain];
837 unset( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i][$domain] );
838 $this->mConns
[self
::KEY_FOREIGN_INUSE
][$i][$domain] = $conn;
839 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
840 } elseif ( !empty( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i] ) ) {
841 // Reuse a connection from another domain
842 $conn = reset( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i] );
843 $oldDomain = key( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i] );
844 // The empty string as a DB name means "don't care".
845 // DatabaseMysqlBase::open() already handle this on connection.
846 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
847 $this->mLastError
= "Error selecting database '$dbName' on server " .
848 $conn->getServer() . " from client host {$this->host}";
849 $this->errorConnection
= $conn;
852 $conn->tablePrefix( $prefix );
853 unset( $this->mConns
[self
::KEY_FOREIGN_FREE
][$i][$oldDomain] );
854 $this->mConns
[self
::KEY_FOREIGN_INUSE
][$i][$domain] = $conn;
855 $this->connLogger
->debug( __METHOD__
.
856 ": reusing free connection from $oldDomain for $domain" );
859 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
860 throw new InvalidArgumentException( "No server with index '$i'." );
862 // Open a new connection
863 $server = $this->mServers
[$i];
864 $server['serverIndex'] = $i;
865 $server['foreignPoolRefCount'] = 0;
866 $server['foreign'] = true;
867 $conn = $this->reallyOpenConnection( $server, $dbName );
868 if ( !$conn->isOpen() ) {
869 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
870 $this->errorConnection
= $conn;
873 $conn->tablePrefix( $prefix );
874 $this->mConns
[self
::KEY_FOREIGN_INUSE
][$i][$domain] = $conn;
875 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
879 // Increment reference count
880 if ( $conn instanceof IDatabase
) {
881 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
882 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
889 * Test if the specified index represents an open connection
891 * @param int $index Server index
895 private function isOpen( $index ) {
896 if ( !is_integer( $index ) ) {
900 return (bool)$this->getAnyOpenConnection( $index );
904 * Really opens a connection. Uncached.
905 * Returns a Database object whether or not the connection was successful.
908 * @param array $server
909 * @param string|bool $dbNameOverride Use "" to not select any database
911 * @throws DBAccessError
912 * @throws InvalidArgumentException
914 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
915 if ( $this->disabled
) {
916 throw new DBAccessError();
919 if ( $dbNameOverride !== false ) {
920 $server['dbname'] = $dbNameOverride;
923 // Let the handle know what the cluster master is (e.g. "db1052")
924 $masterName = $this->getServerName( $this->getWriterIndex() );
925 $server['clusterMasterHost'] = $masterName;
927 // Log when many connection are made on requests
928 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
929 $this->perfLogger
->warning( __METHOD__
. ": " .
930 "{$this->connsOpened}+ connections made (master=$masterName)" );
933 $server['srvCache'] = $this->srvCache
;
934 // Set loggers and profilers
935 $server['connLogger'] = $this->connLogger
;
936 $server['queryLogger'] = $this->queryLogger
;
937 $server['errorLogger'] = $this->errorLogger
;
938 $server['profiler'] = $this->profiler
;
939 $server['trxProfiler'] = $this->trxProfiler
;
940 // Use the same agent and PHP mode for all DB handles
941 $server['cliMode'] = $this->cliMode
;
942 $server['agent'] = $this->agent
;
943 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
944 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
945 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
947 // Create a live connection object
949 $db = Database
::factory( $server['type'], $server );
950 } catch ( DBConnectionError
$e ) {
951 // FIXME: This is probably the ugliest thing I have ever done to
952 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
956 $db->setLBInfo( $server );
957 $db->setLazyMasterHandle(
958 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
960 $db->setTableAliases( $this->tableAliases
);
962 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
963 if ( $this->trxRoundId
!== false ) {
964 $this->applyTransactionRoundFlags( $db );
966 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
967 $db->setTransactionListener( $name, $callback );
975 * @throws DBConnectionError
977 private function reportConnectionError() {
978 $conn = $this->errorConnection
; // the connection which caused the error
980 'method' => __METHOD__
,
981 'last_error' => $this->mLastError
,
984 if ( $conn instanceof IDatabase
) {
985 $context['db_server'] = $conn->getServer();
986 $this->connLogger
->warning(
987 "Connection error: {last_error} ({db_server})",
991 // throws DBConnectionError
992 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
994 // No last connection, probably due to all servers being too busy
995 $this->connLogger
->error(
996 "LB failure with no last connection. Connection error: {last_error}",
1000 // If all servers were busy, mLastError will contain something sensible
1001 throw new DBConnectionError( null, $this->mLastError
);
1005 public function getWriterIndex() {
1009 public function haveIndex( $i ) {
1010 return array_key_exists( $i, $this->mServers
);
1013 public function isNonZeroLoad( $i ) {
1014 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1017 public function getServerCount() {
1018 return count( $this->mServers
);
1021 public function getServerName( $i ) {
1022 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1023 $name = $this->mServers
[$i]['hostName'];
1024 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1025 $name = $this->mServers
[$i]['host'];
1030 return ( $name != '' ) ?
$name : 'localhost';
1034 * @deprecated Since 1.30, no alternative
1036 public function getServerInfo( $i ) {
1037 wfDeprecated( __METHOD__
, '1.30' );
1038 if ( isset( $this->mServers
[$i] ) ) {
1039 return $this->mServers
[$i];
1046 * @deprecated Since 1.30, construct new object
1048 public function setServerInfo( $i, array $serverInfo ) {
1049 wfDeprecated( __METHOD__
, '1.30' );
1050 $this->mServers
[$i] = $serverInfo;
1053 public function getMasterPos() {
1054 # If this entire request was served from a replica DB without opening a connection to the
1055 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1056 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1057 if ( !$masterConn ) {
1058 $serverCount = count( $this->mServers
);
1059 for ( $i = 1; $i < $serverCount; $i++
) {
1060 $conn = $this->getAnyOpenConnection( $i );
1062 return $conn->getReplicaPos();
1066 return $masterConn->getMasterPos();
1072 public function disable() {
1074 $this->disabled
= true;
1077 public function closeAll() {
1078 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1079 $host = $conn->getServer();
1080 $this->connLogger
->debug( "Closing connection to database '$host'." );
1085 self
::KEY_LOCAL
=> [],
1086 self
::KEY_FOREIGN_FREE
=> [],
1087 self
::KEY_FOREIGN_INUSE
=> [],
1089 $this->connsOpened
= 0;
1092 public function closeConnection( IDatabase
$conn ) {
1093 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1094 foreach ( $this->mConns
as $type => $connsByServer ) {
1095 if ( !isset( $connsByServer[$serverIndex] ) ) {
1099 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1100 if ( $conn === $trackedConn ) {
1101 $host = $this->getServerName( $i );
1102 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1103 unset( $this->mConns
[$type][$serverIndex][$i] );
1104 --$this->connsOpened
;
1113 public function commitAll( $fname = __METHOD__
) {
1116 $restore = ( $this->trxRoundId
!== false );
1117 $this->trxRoundId
= false;
1118 $this->forEachOpenConnection(
1119 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1121 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1122 } catch ( DBError
$e ) {
1123 call_user_func( $this->errorLogger
, $e );
1124 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1126 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1127 $this->undoTransactionRoundFlags( $conn );
1133 throw new DBExpectedError(
1135 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1140 public function finalizeMasterChanges() {
1141 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1142 // Any error should cause all DB transactions to be rolled back together
1143 $conn->setTrxEndCallbackSuppression( false );
1144 $conn->runOnTransactionPreCommitCallbacks();
1145 // Defer post-commit callbacks until COMMIT finishes for all DBs
1146 $conn->setTrxEndCallbackSuppression( true );
1150 public function approveMasterChanges( array $options ) {
1151 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1152 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1153 // If atomic sections or explicit transactions are still open, some caller must have
1154 // caught an exception but failed to properly rollback any changes. Detect that and
1155 // throw and error (causing rollback).
1156 if ( $conn->explicitTrxActive() ) {
1157 throw new DBTransactionError(
1159 "Explicit transaction still active. A caller may have caught an error."
1162 // Assert that the time to replicate the transaction will be sane.
1163 // If this fails, then all DB transactions will be rollback back together.
1164 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1165 if ( $limit > 0 && $time > $limit ) {
1166 throw new DBTransactionSizeError(
1168 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1172 // If a connection sits idle while slow queries execute on another, that connection
1173 // may end up dropped before the commit round is reached. Ping servers to detect this.
1174 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1175 throw new DBTransactionError(
1177 "A connection to the {$conn->getDBname()} database was lost before commit."
1183 public function beginMasterChanges( $fname = __METHOD__
) {
1184 if ( $this->trxRoundId
!== false ) {
1185 throw new DBTransactionError(
1187 "$fname: Transaction round '{$this->trxRoundId}' already started."
1190 $this->trxRoundId
= $fname;
1193 $this->forEachOpenMasterConnection(
1194 function ( Database
$conn ) use ( $fname, &$failures ) {
1195 $conn->setTrxEndCallbackSuppression( true );
1197 $conn->flushSnapshot( $fname );
1198 } catch ( DBError
$e ) {
1199 call_user_func( $this->errorLogger
, $e );
1200 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1202 $conn->setTrxEndCallbackSuppression( false );
1203 $this->applyTransactionRoundFlags( $conn );
1208 throw new DBExpectedError(
1210 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1215 public function commitMasterChanges( $fname = __METHOD__
) {
1218 /** @noinspection PhpUnusedLocalVariableInspection */
1219 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1221 $restore = ( $this->trxRoundId
!== false );
1222 $this->trxRoundId
= false;
1223 $this->forEachOpenMasterConnection(
1224 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1226 if ( $conn->writesOrCallbacksPending() ) {
1227 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1228 } elseif ( $restore ) {
1229 $conn->flushSnapshot( $fname );
1231 } catch ( DBError
$e ) {
1232 call_user_func( $this->errorLogger
, $e );
1233 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1236 $this->undoTransactionRoundFlags( $conn );
1242 throw new DBExpectedError(
1244 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1249 public function runMasterPostTrxCallbacks( $type ) {
1250 $e = null; // first exception
1251 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1252 $conn->setTrxEndCallbackSuppression( false );
1253 if ( $conn->writesOrCallbacksPending() ) {
1254 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1255 // (which finished its callbacks already). Warn and recover in this case. Let the
1256 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1257 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1259 } elseif ( $conn->trxLevel() ) {
1260 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1261 // thus leaving an implicit read-only transaction open at this point. It
1262 // also happens if onTransactionIdle() callbacks leave implicit transactions
1263 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1264 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1268 $conn->runOnTransactionIdleCallbacks( $type );
1269 } catch ( Exception
$ex ) {
1273 $conn->runTransactionListenerCallbacks( $type );
1274 } catch ( Exception
$ex ) {
1282 public function rollbackMasterChanges( $fname = __METHOD__
) {
1283 $restore = ( $this->trxRoundId
!== false );
1284 $this->trxRoundId
= false;
1285 $this->forEachOpenMasterConnection(
1286 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1287 if ( $conn->writesOrCallbacksPending() ) {
1288 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1291 $this->undoTransactionRoundFlags( $conn );
1297 public function suppressTransactionEndCallbacks() {
1298 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1299 $conn->setTrxEndCallbackSuppression( true );
1304 * @param IDatabase $conn
1306 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1307 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1308 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1309 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1310 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1311 // If config has explicitly requested DBO_TRX be either on or off by not
1312 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1313 // for things like blob stores (ExternalStore) which want auto-commit mode.
1318 * @param IDatabase $conn
1320 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1321 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1322 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1326 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1327 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1328 $conn->flushSnapshot( __METHOD__
);
1332 public function hasMasterConnection() {
1333 return $this->isOpen( $this->getWriterIndex() );
1336 public function hasMasterChanges() {
1338 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1339 $pending |
= $conn->writesOrCallbacksPending();
1342 return (bool)$pending;
1345 public function lastMasterChangeTimestamp() {
1347 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1348 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1354 public function hasOrMadeRecentMasterChanges( $age = null ) {
1355 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1357 return ( $this->hasMasterChanges()
1358 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1361 public function pendingMasterChangeCallers() {
1363 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1364 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1370 public function getLaggedReplicaMode( $domain = false ) {
1371 // No-op if there is only one DB (also avoids recursion)
1372 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1374 // See if laggedReplicaMode gets set
1375 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1376 $this->reuseConnection( $conn );
1377 } catch ( DBConnectionError
$e ) {
1378 // Avoid expensive re-connect attempts and failures
1379 $this->allReplicasDownMode
= true;
1380 $this->laggedReplicaMode
= true;
1384 return $this->laggedReplicaMode
;
1388 * @param bool $domain
1390 * @deprecated 1.28; use getLaggedReplicaMode()
1392 public function getLaggedSlaveMode( $domain = false ) {
1393 return $this->getLaggedReplicaMode( $domain );
1396 public function laggedReplicaUsed() {
1397 return $this->laggedReplicaMode
;
1403 * @deprecated Since 1.28; use laggedReplicaUsed()
1405 public function laggedSlaveUsed() {
1406 return $this->laggedReplicaUsed();
1409 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1410 if ( $this->readOnlyReason
!== false ) {
1411 return $this->readOnlyReason
;
1412 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1413 if ( $this->allReplicasDownMode
) {
1414 return 'The database has been automatically locked ' .
1415 'until the replica database servers become available';
1417 return 'The database has been automatically locked ' .
1418 'while the replica database servers catch up to the master.';
1420 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1421 return 'The database master is running in read-only mode.';
1428 * @param string $domain Domain ID, or false for the current domain
1429 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1432 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1433 $cache = $this->wanCache
;
1434 $masterServer = $this->getServerName( $this->getWriterIndex() );
1436 return (bool)$cache->getWithSetCallback(
1437 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1438 self
::TTL_CACHE_READONLY
,
1439 function () use ( $domain, $conn ) {
1440 $old = $this->trxProfiler
->setSilenced( true );
1442 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1443 $readOnly = (int)$dbw->serverIsReadOnly();
1445 $this->reuseConnection( $dbw );
1447 } catch ( DBError
$e ) {
1450 $this->trxProfiler
->setSilenced( $old );
1453 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1457 public function allowLagged( $mode = null ) {
1458 if ( $mode === null ) {
1459 return $this->mAllowLagged
;
1461 $this->mAllowLagged
= $mode;
1463 return $this->mAllowLagged
;
1466 public function pingAll() {
1468 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1469 if ( !$conn->ping() ) {
1477 public function forEachOpenConnection( $callback, array $params = [] ) {
1478 foreach ( $this->mConns
as $connsByServer ) {
1479 foreach ( $connsByServer as $serverConns ) {
1480 foreach ( $serverConns as $conn ) {
1481 $mergedParams = array_merge( [ $conn ], $params );
1482 call_user_func_array( $callback, $mergedParams );
1488 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1489 $masterIndex = $this->getWriterIndex();
1490 foreach ( $this->mConns
as $connsByServer ) {
1491 if ( isset( $connsByServer[$masterIndex] ) ) {
1492 /** @var IDatabase $conn */
1493 foreach ( $connsByServer[$masterIndex] as $conn ) {
1494 $mergedParams = array_merge( [ $conn ], $params );
1495 call_user_func_array( $callback, $mergedParams );
1501 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1502 foreach ( $this->mConns
as $connsByServer ) {
1503 foreach ( $connsByServer as $i => $serverConns ) {
1504 if ( $i === $this->getWriterIndex() ) {
1505 continue; // skip master
1507 foreach ( $serverConns as $conn ) {
1508 $mergedParams = array_merge( [ $conn ], $params );
1509 call_user_func_array( $callback, $mergedParams );
1515 public function getMaxLag( $domain = false ) {
1520 if ( $this->getServerCount() <= 1 ) {
1521 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1524 $lagTimes = $this->getLagTimes( $domain );
1525 foreach ( $lagTimes as $i => $lag ) {
1526 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1528 $host = $this->mServers
[$i]['host'];
1533 return [ $host, $maxLag, $maxIndex ];
1536 public function getLagTimes( $domain = false ) {
1537 if ( $this->getServerCount() <= 1 ) {
1538 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1541 $knownLagTimes = []; // map of (server index => 0 seconds)
1542 $indexesWithLag = [];
1543 foreach ( $this->mServers
as $i => $server ) {
1544 if ( empty( $server['is static'] ) ) {
1545 $indexesWithLag[] = $i; // DB server might have replication lag
1547 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1551 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1554 public function safeGetLag( IDatabase
$conn ) {
1555 if ( $this->getServerCount() <= 1 ) {
1558 return $conn->getLag();
1563 * @param IDatabase $conn
1564 * @param DBMasterPos|bool $pos
1565 * @param int $timeout
1568 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1569 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1570 return true; // server is not a replica DB
1574 // Get the current master position, opening a connection if needed
1575 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1576 if ( $masterConn ) {
1577 $pos = $masterConn->getMasterPos();
1579 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1580 $pos = $masterConn->getMasterPos();
1581 $this->closeConnection( $masterConn );
1585 if ( $pos instanceof DBMasterPos
) {
1586 $result = $conn->masterPosWait( $pos, $timeout );
1587 if ( $result == -1 ||
is_null( $result ) ) {
1588 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1589 $this->replLogger
->warning( "$msg" );
1592 $this->replLogger
->info( __METHOD__
. ": Done" );
1596 $ok = false; // something is misconfigured
1597 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1603 public function setTransactionListener( $name, callable
$callback = null ) {
1605 $this->trxRecurringCallbacks
[$name] = $callback;
1607 unset( $this->trxRecurringCallbacks
[$name] );
1609 $this->forEachOpenMasterConnection(
1610 function ( IDatabase
$conn ) use ( $name, $callback ) {
1611 $conn->setTransactionListener( $name, $callback );
1616 public function setTableAliases( array $aliases ) {
1617 $this->tableAliases
= $aliases;
1620 public function setDomainPrefix( $prefix ) {
1621 // Find connections to explicit foreign domains still marked as in-use...
1623 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1624 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1625 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1626 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1627 $domainsInUse[] = $conn->getDomainID();
1631 // Do not switch connections to explicit foreign domains unless marked as safe
1632 if ( $domainsInUse ) {
1633 $domains = implode( ', ', $domainsInUse );
1634 throw new DBUnexpectedError( null,
1635 "Foreign domain connections are still in use ($domains)." );
1638 $this->localDomain
= new DatabaseDomain(
1639 $this->localDomain
->getDatabase(),
1644 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1645 $db->tablePrefix( $prefix );
1650 * Make PHP ignore user aborts/disconnects until the returned
1651 * value leaves scope. This returns null and does nothing in CLI mode.
1653 * @return ScopedCallback|null
1655 final protected function getScopedPHPBehaviorForCommit() {
1656 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1657 $old = ignore_user_abort( true ); // avoid half-finished operations
1658 return new ScopedCallback( function () use ( $old ) {
1659 ignore_user_abort( $old );
1666 function __destruct() {
1667 // Avoid connection leaks for sanity
1672 class_alias( LoadBalancer
::class, 'LoadBalancer' );