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 (connection category => 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 int 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 int 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 int 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 private $maxLag = self
::MAX_LAG_DEFAULT
;
121 /** @var int Warn when this many connection are held */
122 const CONN_HELD_WARN_THRESHOLD
= 10;
124 /** @var int Default 'maxLag' when unspecified */
125 const MAX_LAG_DEFAULT
= 10;
126 /** @var int Seconds to cache master server read-only status */
127 const TTL_CACHE_READONLY
= 5;
129 const KEY_LOCAL
= 'local';
130 const KEY_FOREIGN_FREE
= 'foreignFree';
131 const KEY_FOREIGN_INUSE
= 'foreignInUse';
133 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
134 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
135 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
137 public function __construct( array $params ) {
138 if ( !isset( $params['servers'] ) ) {
139 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
141 $this->mServers
= $params['servers'];
142 foreach ( $this->mServers
as $i => $server ) {
144 $this->mServers
[$i]['master'] = true;
146 $this->mServers
[$i]['replica'] = true;
150 $this->localDomain
= isset( $params['localDomain'] )
151 ? DatabaseDomain
::newFromId( $params['localDomain'] )
152 : DatabaseDomain
::newUnspecified();
153 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
154 // always true, gracefully handle the case when they fail to account for escaping.
155 if ( $this->localDomain
->getTablePrefix() != '' ) {
156 $this->localDomainIdAlias
=
157 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
159 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
162 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
164 $this->mReadIndex
= -1;
166 // Connection were transaction rounds may be applied
167 self
::KEY_LOCAL
=> [],
168 self
::KEY_FOREIGN_INUSE
=> [],
169 self
::KEY_FOREIGN_FREE
=> [],
170 // Auto-committing counterpart connections that ignore transaction rounds
171 self
::KEY_LOCAL_NOROUND
=> [],
172 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
173 self
::KEY_FOREIGN_FREE_NOROUND
=> []
176 $this->mWaitForPos
= false;
177 $this->mAllowLagged
= false;
179 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
180 $this->readOnlyReason
= $params['readOnlyReason'];
183 if ( isset( $params['maxLag'] ) ) {
184 $this->maxLag
= $params['maxLag'];
187 if ( isset( $params['loadMonitor'] ) ) {
188 $this->loadMonitorConfig
= $params['loadMonitor'];
190 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
192 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
194 foreach ( $params['servers'] as $i => $server ) {
195 $this->mLoads
[$i] = $server['load'];
196 if ( isset( $server['groupLoads'] ) ) {
197 foreach ( $server['groupLoads'] as $group => $ratio ) {
198 if ( !isset( $this->mGroupLoads
[$group] ) ) {
199 $this->mGroupLoads
[$group] = [];
201 $this->mGroupLoads
[$group][$i] = $ratio;
206 if ( isset( $params['srvCache'] ) ) {
207 $this->srvCache
= $params['srvCache'];
209 $this->srvCache
= new EmptyBagOStuff();
211 if ( isset( $params['wanCache'] ) ) {
212 $this->wanCache
= $params['wanCache'];
214 $this->wanCache
= WANObjectCache
::newEmpty();
216 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
217 if ( isset( $params['trxProfiler'] ) ) {
218 $this->trxProfiler
= $params['trxProfiler'];
220 $this->trxProfiler
= new TransactionProfiler();
223 $this->errorLogger
= isset( $params['errorLogger'] )
224 ?
$params['errorLogger']
225 : function ( Exception
$e ) {
226 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
229 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
230 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
233 $this->host
= isset( $params['hostname'] )
234 ?
$params['hostname']
235 : ( gethostname() ?
: 'unknown' );
236 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
237 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
239 if ( isset( $params['chronologyProtector'] ) ) {
240 $this->chronProt
= $params['chronologyProtector'];
245 * Get a LoadMonitor instance
247 * @return ILoadMonitor
249 private function getLoadMonitor() {
250 if ( !isset( $this->loadMonitor
) ) {
252 'LoadMonitor' => LoadMonitor
::class,
253 'LoadMonitorNull' => LoadMonitorNull
::class,
254 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
257 $class = $this->loadMonitorConfig
['class'];
258 if ( isset( $compat[$class] ) ) {
259 $class = $compat[$class];
262 $this->loadMonitor
= new $class(
263 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
264 $this->loadMonitor
->setLogger( $this->replLogger
);
267 return $this->loadMonitor
;
271 * @param array $loads
272 * @param bool|string $domain Domain to get non-lagged for
273 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
274 * @return bool|int|string
276 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
277 $lags = $this->getLagTimes( $domain );
279 # Unset excessively lagged servers
280 foreach ( $lags as $i => $lag ) {
282 # How much lag this server nominally is allowed to have
283 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
284 ?
$this->mServers
[$i]['max lag']
285 : $this->maxLag
; // default
286 # Constrain that futher by $maxLag argument
287 $maxServerLag = min( $maxServerLag, $maxLag );
289 $host = $this->getServerName( $i );
290 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
291 $this->replLogger
->error(
292 "Server {host} is not replicating?", [ 'host' => $host ] );
294 } elseif ( $lag > $maxServerLag ) {
295 $this->replLogger
->info(
296 "Server {host} has {lag} seconds of lag (>= {maxlag})",
297 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
304 # Find out if all the replica DBs with non-zero load are lagged
306 foreach ( $loads as $load ) {
310 # No appropriate DB servers except maybe the master and some replica DBs with zero load
311 # Do NOT use the master
312 # Instead, this function will return false, triggering read-only mode,
313 # and a lagged replica DB will be used instead.
317 if ( count( $loads ) == 0 ) {
321 # Return a random representative of the remainder
322 return ArrayUtils
::pickRandom( $loads );
325 public function getReaderIndex( $group = false, $domain = false ) {
326 if ( count( $this->mServers
) == 1 ) {
327 // Skip the load balancing if there's only one server
328 return $this->getWriterIndex();
329 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
330 // Shortcut if the generic reader index was already cached
331 return $this->mReadIndex
;
334 if ( $group !== false ) {
335 // Use the server weight array for this load group
336 if ( isset( $this->mGroupLoads
[$group] ) ) {
337 $loads = $this->mGroupLoads
[$group];
339 // No loads for this group, return false and the caller can use some other group
340 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
345 // Use the generic load group
346 $loads = $this->mLoads
;
349 // Scale the configured load ratios according to each server's load and state
350 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
352 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
353 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
354 if ( $i === false ) {
355 // Replica DB connection unsuccessful
359 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
360 // Before any data queries are run, wait for the server to catch up to the
361 // specified position. This is used to improve session consistency. Note that
362 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
363 // so update laggedReplicaMode as needed for consistency.
364 if ( !$this->doWait( $i ) ) {
365 $laggedReplicaMode = true;
369 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
370 // Cache the generic reader index for future ungrouped DB_REPLICA handles
371 $this->mReadIndex
= $i;
372 // Record if the generic reader index is in "lagged replica DB" mode
373 if ( $laggedReplicaMode ) {
374 $this->laggedReplicaMode
= true;
378 $serverName = $this->getServerName( $i );
379 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
385 * @param array $loads List of server weights
386 * @param string|bool $domain
387 * @return array (reader index, lagged replica mode) or false on failure
389 private function pickReaderIndex( array $loads, $domain = false ) {
390 if ( !count( $loads ) ) {
391 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
394 /** @var int|bool $i Index of selected server */
396 /** @var bool $laggedReplicaMode Whether server is considered lagged */
397 $laggedReplicaMode = false;
399 // Quickly look through the available servers for a server that meets criteria...
400 $currentLoads = $loads;
401 while ( count( $currentLoads ) ) {
402 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
403 $i = ArrayUtils
::pickRandom( $currentLoads );
406 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
407 // ChronologyProtecter sets mWaitForPos for session consistency.
408 // This triggers doWait() after connect, so it's especially good to
409 // avoid lagged servers so as to avoid excessive delay in that method.
410 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
411 // Aim for <= 1 second of waiting (being too picky can backfire)
412 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
414 if ( $i === false ) {
415 // Any server with less lag than it's 'max lag' param is preferable
416 $i = $this->getRandomNonLagged( $currentLoads, $domain );
418 if ( $i === false && count( $currentLoads ) != 0 ) {
419 // All replica DBs lagged. Switch to read-only mode
420 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
421 $i = ArrayUtils
::pickRandom( $currentLoads );
422 $laggedReplicaMode = true;
426 if ( $i === false ) {
427 // pickRandom() returned false.
428 // This is permanent and means the configuration or the load monitor
429 // wants us to return false.
430 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
432 return [ false, false ];
435 $serverName = $this->getServerName( $i );
436 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
438 $conn = $this->openConnection( $i, $domain );
440 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
441 unset( $currentLoads[$i] ); // avoid this server next iteration
446 // Decrement reference counter, we are finished with this connection.
447 // It will be incremented for the caller later.
448 if ( $domain !== false ) {
449 $this->reuseConnection( $conn );
452 // Return this server
456 // If all servers were down, quit now
457 if ( !count( $currentLoads ) ) {
458 $this->connLogger
->error( "All servers down" );
461 return [ $i, $laggedReplicaMode ];
464 public function waitFor( $pos ) {
465 $oldPos = $this->mWaitForPos
;
467 $this->mWaitForPos
= $pos;
468 // If a generic reader connection was already established, then wait now
469 $i = $this->mReadIndex
;
471 if ( !$this->doWait( $i ) ) {
472 $this->laggedReplicaMode
= true;
476 // Restore the older position if it was higher since this is used for lag-protection
477 $this->setWaitForPositionIfHigher( $oldPos );
481 public function waitForOne( $pos, $timeout = null ) {
482 $oldPos = $this->mWaitForPos
;
484 $this->mWaitForPos
= $pos;
486 $i = $this->mReadIndex
;
488 // Pick a generic replica DB if there isn't one yet
489 $readLoads = $this->mLoads
;
490 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
491 $readLoads = array_filter( $readLoads ); // with non-zero load
492 $i = ArrayUtils
::pickRandom( $readLoads );
496 $ok = $this->doWait( $i, true, $timeout );
498 $ok = true; // no applicable loads
501 # Restore the old position, as this is not used for lag-protection but for throttling
502 $this->mWaitForPos
= $oldPos;
508 public function waitForAll( $pos, $timeout = null ) {
509 $oldPos = $this->mWaitForPos
;
511 $this->mWaitForPos
= $pos;
512 $serverCount = count( $this->mServers
);
515 for ( $i = 1; $i < $serverCount; $i++
) {
516 if ( $this->mLoads
[$i] > 0 ) {
517 $ok = $this->doWait( $i, true, $timeout ) && $ok;
521 # Restore the old position, as this is not used for lag-protection but for throttling
522 $this->mWaitForPos
= $oldPos;
529 * @param DBMasterPos|bool $pos
531 private function setWaitForPositionIfHigher( $pos ) {
536 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
537 $this->mWaitForPos
= $pos;
543 * @return IDatabase|bool
545 public function getAnyOpenConnection( $i ) {
546 foreach ( $this->mConns
as $connsByServer ) {
547 if ( !empty( $connsByServer[$i] ) ) {
548 /** @var IDatabase[] $serverConns */
549 $serverConns = $connsByServer[$i];
551 return reset( $serverConns );
559 * Wait for a given replica DB to catch up to the master pos stored in $this
560 * @param int $index Server index
561 * @param bool $open Check the server even if a new connection has to be made
562 * @param int $timeout Max seconds to wait; default is mWaitTimeout
565 protected function doWait( $index, $open = false, $timeout = null ) {
566 $close = false; // close the connection afterwards
568 // Check if we already know that the DB has reached this point
569 $server = $this->getServerName( $index );
570 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
571 /** @var DBMasterPos $knownReachedPos */
572 $knownReachedPos = $this->srvCache
->get( $key );
574 $knownReachedPos instanceof DBMasterPos
&&
575 $knownReachedPos->hasReached( $this->mWaitForPos
)
577 $this->replLogger
->debug( __METHOD__
.
578 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
579 [ 'dbserver' => $server ] );
583 // Find a connection to wait on, creating one if needed and allowed
584 $conn = $this->getAnyOpenConnection( $index );
587 $this->replLogger
->debug( __METHOD__
. ': no connection open for {dbserver}',
588 [ 'dbserver' => $server ] );
592 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
594 $this->replLogger
->warning( __METHOD__
. ': failed to connect to {dbserver}',
595 [ 'dbserver' => $server ] );
599 // Avoid connection spam in waitForAll() when connections
600 // are made just for the sake of doing this lag check.
605 $this->replLogger
->info( __METHOD__
. ': Waiting for replica DB {dbserver} to catch up...',
606 [ 'dbserver' => $server ] );
607 $timeout = $timeout ?
: $this->mWaitTimeout
;
608 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
610 if ( $result == -1 ||
is_null( $result ) ) {
611 // Timed out waiting for replica DB, use master instead
612 $this->replLogger
->warning(
613 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
614 [ 'host' => $server, 'pos' => $this->mWaitForPos
]
618 $this->replLogger
->info( __METHOD__
. ": Done" );
620 // Remember that the DB reached this point
621 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
625 $this->closeConnection( $conn );
631 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
632 if ( $i === null ||
$i === false ) {
633 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
634 ' with invalid server index' );
637 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
638 $domain = false; // local connection requested
641 $groups = ( $groups === false ||
$groups === [] )
642 ?
[ false ] // check one "group": the generic pool
645 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
646 $oldConnsOpened = $this->connsOpened
; // connections open now
648 if ( $i == self
::DB_MASTER
) {
649 $i = $this->getWriterIndex();
651 # Try to find an available server in any the query groups (in order)
652 foreach ( $groups as $group ) {
653 $groupIndex = $this->getReaderIndex( $group, $domain );
654 if ( $groupIndex !== false ) {
661 # Operation-based index
662 if ( $i == self
::DB_REPLICA
) {
663 $this->mLastError
= 'Unknown error'; // reset error string
664 # Try the general server pool if $groups are unavailable.
665 $i = ( $groups === [ false ] )
666 ?
false // don't bother with this if that is what was tried above
667 : $this->getReaderIndex( false, $domain );
668 # Couldn't find a working server in getReaderIndex()?
669 if ( $i === false ) {
670 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
671 // Throw an exception
672 $this->reportConnectionError();
673 return null; // not reached
677 # Now we have an explicit index into the servers array
678 $conn = $this->openConnection( $i, $domain, $flags );
680 // Throw an exception
681 $this->reportConnectionError();
682 return null; // not reached
685 # Profile any new connections that happen
686 if ( $this->connsOpened
> $oldConnsOpened ) {
687 $host = $conn->getServer();
688 $dbname = $conn->getDBname();
689 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
693 # Make master-requested DB handles inherit any read-only mode setting
694 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
700 public function reuseConnection( $conn ) {
701 $serverIndex = $conn->getLBInfo( 'serverIndex' );
702 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
703 if ( $serverIndex === null ||
$refCount === null ) {
705 * This can happen in code like:
706 * foreach ( $dbs as $db ) {
707 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
709 * $lb->reuseConnection( $conn );
711 * When a connection to the local DB is opened in this way, reuseConnection()
715 } elseif ( $conn instanceof DBConnRef
) {
716 // DBConnRef already handles calling reuseConnection() and only passes the live
717 // Database instance to this method. Any caller passing in a DBConnRef is broken.
718 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
719 ( new RuntimeException() )->getTraceAsString() );
724 if ( $this->disabled
) {
725 return; // DBConnRef handle probably survived longer than the LoadBalancer
728 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
729 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
730 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
732 $connFreeKey = self
::KEY_FOREIGN_FREE
;
733 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
736 $domain = $conn->getDomainID();
737 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
738 throw new InvalidArgumentException( __METHOD__
.
739 ": connection $serverIndex/$domain not found; it may have already been freed." );
740 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
741 throw new InvalidArgumentException( __METHOD__
.
742 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
745 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
746 if ( $refCount <= 0 ) {
747 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
748 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
749 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
750 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
752 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
754 $this->connLogger
->debug( __METHOD__
.
755 ": reference count for $serverIndex/$domain reduced to $refCount" );
759 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
760 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
762 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
765 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
766 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
768 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
771 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
772 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
774 return new MaintainableDBConnRef(
775 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
778 public function openConnection( $i, $domain = false, $flags = 0 ) {
779 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
780 $domain = false; // local connection requested
783 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
784 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
785 // Load CP positions before connecting so that doWait() triggers later if needed
786 $this->chronProtInitialized
= true;
787 $this->chronProt
->initLB( $this );
790 // Check if an auto-commit connection is being requested. If so, it will not reuse the
791 // main set of DB connections but rather its own pool since:
792 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
793 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
794 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
796 if ( $domain !== false ) {
797 // Connection is to a foreign domain
798 $conn = $this->openForeignConnection( $i, $domain, $flags );
800 // Connection is to the local domain
801 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
802 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
803 $conn = $this->mConns
[$connKey][$i][0];
805 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
806 throw new InvalidArgumentException( "No server with index '$i'." );
808 // Open a new connection
809 $server = $this->mServers
[$i];
810 $server['serverIndex'] = $i;
811 $server['autoCommitOnly'] = $autoCommit;
812 $conn = $this->reallyOpenConnection( $server, false );
813 $host = $this->getServerName( $i );
814 if ( $conn->isOpen() ) {
815 $this->connLogger
->debug( "Connected to database $i at '$host'." );
816 $this->mConns
[$connKey][$i][0] = $conn;
818 $this->connLogger
->warning( "Failed to connect to database $i at '$host'." );
819 $this->errorConnection
= $conn;
825 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
826 // Connection was made but later unrecoverably lost for some reason.
827 // Do not return a handle that will just throw exceptions on use,
828 // but let the calling code (e.g. getReaderIndex) try another server.
829 // See DatabaseMyslBase::ping() for how this can happen.
830 $this->errorConnection
= $conn;
834 if ( $autoCommit && $conn instanceof IDatabase
) {
835 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
842 * Open a connection to a foreign DB, or return one if it is already open.
844 * Increments a reference count on the returned connection which locks the
845 * connection to the requested domain. This reference count can be
846 * decremented by calling reuseConnection().
848 * If a connection is open to the appropriate server already, but with the wrong
849 * database, it will be switched to the right database and returned, as long as
850 * it has been freed first with reuseConnection().
852 * On error, returns false, and the connection which caused the
853 * error will be available via $this->errorConnection.
855 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
857 * @param int $i Server index
858 * @param string $domain Domain ID to open
859 * @param int $flags Class CONN_* constant bitfield
862 private function openForeignConnection( $i, $domain, $flags = 0 ) {
863 $domainInstance = DatabaseDomain
::newFromId( $domain );
864 $dbName = $domainInstance->getDatabase();
865 $prefix = $domainInstance->getTablePrefix();
866 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
869 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
870 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
872 $connFreeKey = self
::KEY_FOREIGN_FREE
;
873 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
876 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
877 // Reuse an in-use connection for the same domain
878 $conn = $this->mConns
[$connInUseKey][$i][$domain];
879 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
880 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
881 // Reuse a free connection for the same domain
882 $conn = $this->mConns
[$connFreeKey][$i][$domain];
883 unset( $this->mConns
[$connFreeKey][$i][$domain] );
884 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
885 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
886 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
887 // Reuse a free connection from another domain
888 $conn = reset( $this->mConns
[$connFreeKey][$i] );
889 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
890 // The empty string as a DB name means "don't care".
891 // DatabaseMysqlBase::open() already handle this on connection.
892 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
893 $this->mLastError
= "Error selecting database '$dbName' on server " .
894 $conn->getServer() . " from client host {$this->host}";
895 $this->errorConnection
= $conn;
898 $conn->tablePrefix( $prefix );
899 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
900 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
901 $this->connLogger
->debug( __METHOD__
.
902 ": reusing free connection from $oldDomain for $domain" );
905 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
906 throw new InvalidArgumentException( "No server with index '$i'." );
908 // Open a new connection
909 $server = $this->mServers
[$i];
910 $server['serverIndex'] = $i;
911 $server['foreignPoolRefCount'] = 0;
912 $server['foreign'] = true;
913 $server['autoCommitOnly'] = $autoCommit;
914 $conn = $this->reallyOpenConnection( $server, $dbName );
915 if ( !$conn->isOpen() ) {
916 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
917 $this->errorConnection
= $conn;
920 $conn->tablePrefix( $prefix );
921 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
922 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
926 // Increment reference count
927 if ( $conn instanceof IDatabase
) {
928 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
929 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
936 * Test if the specified index represents an open connection
938 * @param int $index Server index
942 private function isOpen( $index ) {
943 if ( !is_integer( $index ) ) {
947 return (bool)$this->getAnyOpenConnection( $index );
951 * Really opens a connection. Uncached.
952 * Returns a Database object whether or not the connection was successful.
955 * @param array $server
956 * @param string|bool $dbNameOverride Use "" to not select any database
958 * @throws DBAccessError
959 * @throws InvalidArgumentException
961 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
962 if ( $this->disabled
) {
963 throw new DBAccessError();
966 if ( $dbNameOverride !== false ) {
967 $server['dbname'] = $dbNameOverride;
970 // Let the handle know what the cluster master is (e.g. "db1052")
971 $masterName = $this->getServerName( $this->getWriterIndex() );
972 $server['clusterMasterHost'] = $masterName;
974 // Log when many connection are made on requests
975 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
976 $this->perfLogger
->warning( __METHOD__
. ": " .
977 "{$this->connsOpened}+ connections made (master=$masterName)" );
980 $server['srvCache'] = $this->srvCache
;
981 // Set loggers and profilers
982 $server['connLogger'] = $this->connLogger
;
983 $server['queryLogger'] = $this->queryLogger
;
984 $server['errorLogger'] = $this->errorLogger
;
985 $server['profiler'] = $this->profiler
;
986 $server['trxProfiler'] = $this->trxProfiler
;
987 // Use the same agent and PHP mode for all DB handles
988 $server['cliMode'] = $this->cliMode
;
989 $server['agent'] = $this->agent
;
990 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
991 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
992 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
994 // Create a live connection object
996 $db = Database
::factory( $server['type'], $server );
997 } catch ( DBConnectionError
$e ) {
998 // FIXME: This is probably the ugliest thing I have ever done to
999 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1003 $db->setLBInfo( $server );
1004 $db->setLazyMasterHandle(
1005 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1007 $db->setTableAliases( $this->tableAliases
);
1009 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1010 if ( $this->trxRoundId
!== false ) {
1011 $this->applyTransactionRoundFlags( $db );
1013 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1014 $db->setTransactionListener( $name, $callback );
1022 * @throws DBConnectionError
1024 private function reportConnectionError() {
1025 $conn = $this->errorConnection
; // the connection which caused the error
1027 'method' => __METHOD__
,
1028 'last_error' => $this->mLastError
,
1031 if ( $conn instanceof IDatabase
) {
1032 $context['db_server'] = $conn->getServer();
1033 $this->connLogger
->warning(
1034 "Connection error: {last_error} ({db_server})",
1038 // throws DBConnectionError
1039 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1041 // No last connection, probably due to all servers being too busy
1042 $this->connLogger
->error(
1043 "LB failure with no last connection. Connection error: {last_error}",
1047 // If all servers were busy, mLastError will contain something sensible
1048 throw new DBConnectionError( null, $this->mLastError
);
1052 public function getWriterIndex() {
1056 public function haveIndex( $i ) {
1057 return array_key_exists( $i, $this->mServers
);
1060 public function isNonZeroLoad( $i ) {
1061 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1064 public function getServerCount() {
1065 return count( $this->mServers
);
1068 public function getServerName( $i ) {
1069 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1070 $name = $this->mServers
[$i]['hostName'];
1071 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1072 $name = $this->mServers
[$i]['host'];
1077 return ( $name != '' ) ?
$name : 'localhost';
1080 public function getServerType( $i ) {
1081 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
1085 * @deprecated Since 1.30, no alternative
1087 public function getServerInfo( $i ) {
1088 wfDeprecated( __METHOD__
, '1.30' );
1089 if ( isset( $this->mServers
[$i] ) ) {
1090 return $this->mServers
[$i];
1097 * @deprecated Since 1.30, construct new object
1099 public function setServerInfo( $i, array $serverInfo ) {
1100 wfDeprecated( __METHOD__
, '1.30' );
1101 $this->mServers
[$i] = $serverInfo;
1104 public function getMasterPos() {
1105 # If this entire request was served from a replica DB without opening a connection to the
1106 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1107 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1108 if ( !$masterConn ) {
1109 $serverCount = count( $this->mServers
);
1110 for ( $i = 1; $i < $serverCount; $i++
) {
1111 $conn = $this->getAnyOpenConnection( $i );
1113 return $conn->getReplicaPos();
1117 return $masterConn->getMasterPos();
1123 public function disable() {
1125 $this->disabled
= true;
1128 public function closeAll() {
1129 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1130 $host = $conn->getServer();
1131 $this->connLogger
->debug( "Closing connection to database '$host'." );
1136 self
::KEY_LOCAL
=> [],
1137 self
::KEY_FOREIGN_INUSE
=> [],
1138 self
::KEY_FOREIGN_FREE
=> [],
1139 self
::KEY_LOCAL_NOROUND
=> [],
1140 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1141 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1143 $this->connsOpened
= 0;
1146 public function closeConnection( IDatabase
$conn ) {
1147 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1148 foreach ( $this->mConns
as $type => $connsByServer ) {
1149 if ( !isset( $connsByServer[$serverIndex] ) ) {
1153 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1154 if ( $conn === $trackedConn ) {
1155 $host = $this->getServerName( $i );
1156 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1157 unset( $this->mConns
[$type][$serverIndex][$i] );
1158 --$this->connsOpened
;
1167 public function commitAll( $fname = __METHOD__
) {
1170 $restore = ( $this->trxRoundId
!== false );
1171 $this->trxRoundId
= false;
1172 $this->forEachOpenConnection(
1173 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1175 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1176 } catch ( DBError
$e ) {
1177 call_user_func( $this->errorLogger
, $e );
1178 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1180 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1181 $this->undoTransactionRoundFlags( $conn );
1187 throw new DBExpectedError(
1189 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1194 public function finalizeMasterChanges() {
1195 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1196 // Any error should cause all DB transactions to be rolled back together
1197 $conn->setTrxEndCallbackSuppression( false );
1198 $conn->runOnTransactionPreCommitCallbacks();
1199 // Defer post-commit callbacks until COMMIT finishes for all DBs
1200 $conn->setTrxEndCallbackSuppression( true );
1204 public function approveMasterChanges( array $options ) {
1205 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1206 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1207 // If atomic sections or explicit transactions are still open, some caller must have
1208 // caught an exception but failed to properly rollback any changes. Detect that and
1209 // throw and error (causing rollback).
1210 if ( $conn->explicitTrxActive() ) {
1211 throw new DBTransactionError(
1213 "Explicit transaction still active. A caller may have caught an error."
1216 // Assert that the time to replicate the transaction will be sane.
1217 // If this fails, then all DB transactions will be rollback back together.
1218 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1219 if ( $limit > 0 && $time > $limit ) {
1220 throw new DBTransactionSizeError(
1222 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1226 // If a connection sits idle while slow queries execute on another, that connection
1227 // may end up dropped before the commit round is reached. Ping servers to detect this.
1228 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1229 throw new DBTransactionError(
1231 "A connection to the {$conn->getDBname()} database was lost before commit."
1237 public function beginMasterChanges( $fname = __METHOD__
) {
1238 if ( $this->trxRoundId
!== false ) {
1239 throw new DBTransactionError(
1241 "$fname: Transaction round '{$this->trxRoundId}' already started."
1244 $this->trxRoundId
= $fname;
1247 $this->forEachOpenMasterConnection(
1248 function ( Database
$conn ) use ( $fname, &$failures ) {
1249 $conn->setTrxEndCallbackSuppression( true );
1251 $conn->flushSnapshot( $fname );
1252 } catch ( DBError
$e ) {
1253 call_user_func( $this->errorLogger
, $e );
1254 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1256 $conn->setTrxEndCallbackSuppression( false );
1257 $this->applyTransactionRoundFlags( $conn );
1262 throw new DBExpectedError(
1264 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1269 public function commitMasterChanges( $fname = __METHOD__
) {
1272 /** @noinspection PhpUnusedLocalVariableInspection */
1273 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1275 $restore = ( $this->trxRoundId
!== false );
1276 $this->trxRoundId
= false;
1277 $this->forEachOpenMasterConnection(
1278 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1280 if ( $conn->writesOrCallbacksPending() ) {
1281 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1282 } elseif ( $restore ) {
1283 $conn->flushSnapshot( $fname );
1285 } catch ( DBError
$e ) {
1286 call_user_func( $this->errorLogger
, $e );
1287 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1290 $this->undoTransactionRoundFlags( $conn );
1296 throw new DBExpectedError(
1298 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1303 public function runMasterPostTrxCallbacks( $type ) {
1304 $e = null; // first exception
1305 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1306 $conn->setTrxEndCallbackSuppression( false );
1307 if ( $conn->writesOrCallbacksPending() ) {
1308 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1309 // (which finished its callbacks already). Warn and recover in this case. Let the
1310 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1311 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1313 } elseif ( $conn->trxLevel() ) {
1314 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1315 // thus leaving an implicit read-only transaction open at this point. It
1316 // also happens if onTransactionIdle() callbacks leave implicit transactions
1317 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1318 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1322 $conn->runOnTransactionIdleCallbacks( $type );
1323 } catch ( Exception
$ex ) {
1327 $conn->runTransactionListenerCallbacks( $type );
1328 } catch ( Exception
$ex ) {
1336 public function rollbackMasterChanges( $fname = __METHOD__
) {
1337 $restore = ( $this->trxRoundId
!== false );
1338 $this->trxRoundId
= false;
1339 $this->forEachOpenMasterConnection(
1340 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1341 if ( $conn->writesOrCallbacksPending() ) {
1342 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1345 $this->undoTransactionRoundFlags( $conn );
1351 public function suppressTransactionEndCallbacks() {
1352 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1353 $conn->setTrxEndCallbackSuppression( true );
1358 * @param IDatabase $conn
1360 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1361 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1362 return; // transaction rounds do not apply to these connections
1365 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1366 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1367 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1368 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1369 // If config has explicitly requested DBO_TRX be either on or off by not
1370 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1371 // for things like blob stores (ExternalStore) which want auto-commit mode.
1376 * @param IDatabase $conn
1378 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1379 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1380 return; // transaction rounds do not apply to these connections
1383 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1384 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1388 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1389 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1390 $conn->flushSnapshot( __METHOD__
);
1394 public function hasMasterConnection() {
1395 return $this->isOpen( $this->getWriterIndex() );
1398 public function hasMasterChanges() {
1400 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1401 $pending |
= $conn->writesOrCallbacksPending();
1404 return (bool)$pending;
1407 public function lastMasterChangeTimestamp() {
1409 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1410 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1416 public function hasOrMadeRecentMasterChanges( $age = null ) {
1417 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1419 return ( $this->hasMasterChanges()
1420 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1423 public function pendingMasterChangeCallers() {
1425 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1426 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1432 public function getLaggedReplicaMode( $domain = false ) {
1433 // No-op if there is only one DB (also avoids recursion)
1434 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1436 // See if laggedReplicaMode gets set
1437 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1438 $this->reuseConnection( $conn );
1439 } catch ( DBConnectionError
$e ) {
1440 // Avoid expensive re-connect attempts and failures
1441 $this->allReplicasDownMode
= true;
1442 $this->laggedReplicaMode
= true;
1446 return $this->laggedReplicaMode
;
1450 * @param bool $domain
1452 * @deprecated 1.28; use getLaggedReplicaMode()
1454 public function getLaggedSlaveMode( $domain = false ) {
1455 return $this->getLaggedReplicaMode( $domain );
1458 public function laggedReplicaUsed() {
1459 return $this->laggedReplicaMode
;
1465 * @deprecated Since 1.28; use laggedReplicaUsed()
1467 public function laggedSlaveUsed() {
1468 return $this->laggedReplicaUsed();
1471 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1472 if ( $this->readOnlyReason
!== false ) {
1473 return $this->readOnlyReason
;
1474 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1475 if ( $this->allReplicasDownMode
) {
1476 return 'The database has been automatically locked ' .
1477 'until the replica database servers become available';
1479 return 'The database has been automatically locked ' .
1480 'while the replica database servers catch up to the master.';
1482 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1483 return 'The database master is running in read-only mode.';
1490 * @param string $domain Domain ID, or false for the current domain
1491 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1494 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1495 $cache = $this->wanCache
;
1496 $masterServer = $this->getServerName( $this->getWriterIndex() );
1498 return (bool)$cache->getWithSetCallback(
1499 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1500 self
::TTL_CACHE_READONLY
,
1501 function () use ( $domain, $conn ) {
1502 $old = $this->trxProfiler
->setSilenced( true );
1504 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1505 $readOnly = (int)$dbw->serverIsReadOnly();
1507 $this->reuseConnection( $dbw );
1509 } catch ( DBError
$e ) {
1512 $this->trxProfiler
->setSilenced( $old );
1515 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1519 public function allowLagged( $mode = null ) {
1520 if ( $mode === null ) {
1521 return $this->mAllowLagged
;
1523 $this->mAllowLagged
= $mode;
1525 return $this->mAllowLagged
;
1528 public function pingAll() {
1530 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1531 if ( !$conn->ping() ) {
1539 public function forEachOpenConnection( $callback, array $params = [] ) {
1540 foreach ( $this->mConns
as $connsByServer ) {
1541 foreach ( $connsByServer as $serverConns ) {
1542 foreach ( $serverConns as $conn ) {
1543 $mergedParams = array_merge( [ $conn ], $params );
1544 call_user_func_array( $callback, $mergedParams );
1550 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1551 $masterIndex = $this->getWriterIndex();
1552 foreach ( $this->mConns
as $connsByServer ) {
1553 if ( isset( $connsByServer[$masterIndex] ) ) {
1554 /** @var IDatabase $conn */
1555 foreach ( $connsByServer[$masterIndex] as $conn ) {
1556 $mergedParams = array_merge( [ $conn ], $params );
1557 call_user_func_array( $callback, $mergedParams );
1563 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1564 foreach ( $this->mConns
as $connsByServer ) {
1565 foreach ( $connsByServer as $i => $serverConns ) {
1566 if ( $i === $this->getWriterIndex() ) {
1567 continue; // skip master
1569 foreach ( $serverConns as $conn ) {
1570 $mergedParams = array_merge( [ $conn ], $params );
1571 call_user_func_array( $callback, $mergedParams );
1577 public function getMaxLag( $domain = false ) {
1582 if ( $this->getServerCount() <= 1 ) {
1583 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1586 $lagTimes = $this->getLagTimes( $domain );
1587 foreach ( $lagTimes as $i => $lag ) {
1588 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1590 $host = $this->mServers
[$i]['host'];
1595 return [ $host, $maxLag, $maxIndex ];
1598 public function getLagTimes( $domain = false ) {
1599 if ( $this->getServerCount() <= 1 ) {
1600 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1603 $knownLagTimes = []; // map of (server index => 0 seconds)
1604 $indexesWithLag = [];
1605 foreach ( $this->mServers
as $i => $server ) {
1606 if ( empty( $server['is static'] ) ) {
1607 $indexesWithLag[] = $i; // DB server might have replication lag
1609 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1613 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1616 public function safeGetLag( IDatabase
$conn ) {
1617 if ( $this->getServerCount() <= 1 ) {
1620 return $conn->getLag();
1625 * @param IDatabase $conn
1626 * @param DBMasterPos|bool $pos
1627 * @param int $timeout
1630 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1631 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1632 return true; // server is not a replica DB
1636 // Get the current master position, opening a connection if needed
1637 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1638 if ( $masterConn ) {
1639 $pos = $masterConn->getMasterPos();
1641 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1642 $pos = $masterConn->getMasterPos();
1643 $this->closeConnection( $masterConn );
1647 if ( $pos instanceof DBMasterPos
) {
1648 $result = $conn->masterPosWait( $pos, $timeout );
1649 if ( $result == -1 ||
is_null( $result ) ) {
1650 $msg = __METHOD__
. ': Timed out waiting on {host} pos {pos}';
1651 $this->replLogger
->warning( $msg,
1652 [ 'host' => $conn->getServer(), 'pos' => $pos ] );
1655 $this->replLogger
->info( __METHOD__
. ': Done' );
1659 $ok = false; // something is misconfigured
1660 $this->replLogger
->error( 'Could not get master pos for {host}',
1661 [ 'host' => $conn->getServer() ] );
1667 public function setTransactionListener( $name, callable
$callback = null ) {
1669 $this->trxRecurringCallbacks
[$name] = $callback;
1671 unset( $this->trxRecurringCallbacks
[$name] );
1673 $this->forEachOpenMasterConnection(
1674 function ( IDatabase
$conn ) use ( $name, $callback ) {
1675 $conn->setTransactionListener( $name, $callback );
1680 public function setTableAliases( array $aliases ) {
1681 $this->tableAliases
= $aliases;
1684 public function setDomainPrefix( $prefix ) {
1685 // Find connections to explicit foreign domains still marked as in-use...
1687 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1688 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1689 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1690 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1691 $domainsInUse[] = $conn->getDomainID();
1695 // Do not switch connections to explicit foreign domains unless marked as safe
1696 if ( $domainsInUse ) {
1697 $domains = implode( ', ', $domainsInUse );
1698 throw new DBUnexpectedError( null,
1699 "Foreign domain connections are still in use ($domains)." );
1702 $this->localDomain
= new DatabaseDomain(
1703 $this->localDomain
->getDatabase(),
1708 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1709 $db->tablePrefix( $prefix );
1714 * Make PHP ignore user aborts/disconnects until the returned
1715 * value leaves scope. This returns null and does nothing in CLI mode.
1717 * @return ScopedCallback|null
1719 final protected function getScopedPHPBehaviorForCommit() {
1720 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1721 $old = ignore_user_abort( true ); // avoid half-finished operations
1722 return new ScopedCallback( function () use ( $old ) {
1723 ignore_user_abort( $old );
1730 function __destruct() {
1731 // Avoid connection leaks for sanity
1736 class_alias( LoadBalancer
::class, 'LoadBalancer' );