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
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use InvalidArgumentException
;
36 * Database connection, tracking, load balancing, and transaction manager for a cluster
40 class LoadBalancer
implements ILoadBalancer
{
41 /** @var array[] Map of (server index => server config array) */
43 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
45 /** @var float[] Map of (server index => weight) */
47 /** @var array[] Map of (group => server index => weight) */
49 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
50 private $mAllowLagged;
51 /** @var int Seconds to spend waiting on replica DB lag to resolve */
52 private $mWaitTimeout;
53 /** @var array The LoadMonitor configuration */
54 private $loadMonitorConfig;
55 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
56 private $tableAliases = [];
58 /** @var ILoadMonitor */
60 /** @var ChronologyProtector|null */
64 /** @var WANObjectCache */
66 /** @var object|string Class name or object With profileIn/profileOut methods */
68 /** @var TransactionProfiler */
69 protected $trxProfiler;
70 /** @var LoggerInterface */
71 protected $replLogger;
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var LoggerInterface */
77 protected $perfLogger;
79 /** @var Database DB connection object that caused a problem */
80 private $errorConnection;
81 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
83 /** @var bool|DBMasterPos False if not set */
85 /** @var bool Whether the generic reader fell back to a lagged replica DB */
86 private $laggedReplicaMode = false;
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $allReplicasDownMode = false;
89 /** @var string The last DB selection or connection error */
90 private $mLastError = 'Unknown error';
91 /** @var string|bool Reason the LB is read-only or false if not */
92 private $readOnlyReason = false;
93 /** @var int Total connections opened */
94 private $connsOpened = 0;
95 /** @var string|bool String if a requested DBO_TRX transaction round is active */
96 private $trxRoundId = false;
97 /** @var array[] Map of (name => callable) */
98 private $trxRecurringCallbacks = [];
99 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
100 private $localDomain;
101 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
102 private $localDomainIdAlias;
103 /** @var string Current server name */
105 /** @var bool Whether this PHP instance is for a CLI script */
107 /** @var string Agent name for query profiling */
110 /** @var callable Exception logger */
111 private $errorLogger;
114 private $disabled = false;
116 private $chronProtInitialized = false;
118 private $maxLag = self
::MAX_LAG_DEFAULT
;
120 /** @var int Warn when this many connection are held */
121 const CONN_HELD_WARN_THRESHOLD
= 10;
123 /** @var int Default 'maxLag' when unspecified */
124 const MAX_LAG_DEFAULT
= 10;
125 /** @var int Seconds to cache master server read-only status */
126 const TTL_CACHE_READONLY
= 5;
128 const KEY_LOCAL
= 'local';
129 const KEY_FOREIGN_FREE
= 'foreignFree';
130 const KEY_FOREIGN_INUSE
= 'foreignInUse';
132 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
133 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
134 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
136 public function __construct( array $params ) {
137 if ( !isset( $params['servers'] ) ) {
138 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
140 $this->mServers
= $params['servers'];
141 foreach ( $this->mServers
as $i => $server ) {
143 $this->mServers
[$i]['master'] = true;
145 $this->mServers
[$i]['replica'] = true;
149 $this->localDomain
= isset( $params['localDomain'] )
150 ? DatabaseDomain
::newFromId( $params['localDomain'] )
151 : DatabaseDomain
::newUnspecified();
152 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
153 // always true, gracefully handle the case when they fail to account for escaping.
154 if ( $this->localDomain
->getTablePrefix() != '' ) {
155 $this->localDomainIdAlias
=
156 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
158 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
161 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
163 $this->mReadIndex
= -1;
165 // Connection were transaction rounds may be applied
166 self
::KEY_LOCAL
=> [],
167 self
::KEY_FOREIGN_INUSE
=> [],
168 self
::KEY_FOREIGN_FREE
=> [],
169 // Auto-committing counterpart connections that ignore transaction rounds
170 self
::KEY_LOCAL_NOROUND
=> [],
171 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
172 self
::KEY_FOREIGN_FREE_NOROUND
=> []
175 $this->mWaitForPos
= false;
176 $this->mAllowLagged
= false;
178 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
179 $this->readOnlyReason
= $params['readOnlyReason'];
182 if ( isset( $params['maxLag'] ) ) {
183 $this->maxLag
= $params['maxLag'];
186 if ( isset( $params['loadMonitor'] ) ) {
187 $this->loadMonitorConfig
= $params['loadMonitor'];
189 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
191 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
193 foreach ( $params['servers'] as $i => $server ) {
194 $this->mLoads
[$i] = $server['load'];
195 if ( isset( $server['groupLoads'] ) ) {
196 foreach ( $server['groupLoads'] as $group => $ratio ) {
197 if ( !isset( $this->mGroupLoads
[$group] ) ) {
198 $this->mGroupLoads
[$group] = [];
200 $this->mGroupLoads
[$group][$i] = $ratio;
205 if ( isset( $params['srvCache'] ) ) {
206 $this->srvCache
= $params['srvCache'];
208 $this->srvCache
= new EmptyBagOStuff();
210 if ( isset( $params['wanCache'] ) ) {
211 $this->wanCache
= $params['wanCache'];
213 $this->wanCache
= WANObjectCache
::newEmpty();
215 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
216 if ( isset( $params['trxProfiler'] ) ) {
217 $this->trxProfiler
= $params['trxProfiler'];
219 $this->trxProfiler
= new TransactionProfiler();
222 $this->errorLogger
= isset( $params['errorLogger'] )
223 ?
$params['errorLogger']
224 : function ( Exception
$e ) {
225 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
228 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
229 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
232 $this->host
= isset( $params['hostname'] )
233 ?
$params['hostname']
234 : ( gethostname() ?
: 'unknown' );
235 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
236 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
238 if ( isset( $params['chronologyProtector'] ) ) {
239 $this->chronProt
= $params['chronologyProtector'];
244 * Get a LoadMonitor instance
246 * @return ILoadMonitor
248 private function getLoadMonitor() {
249 if ( !isset( $this->loadMonitor
) ) {
251 'LoadMonitor' => LoadMonitor
::class,
252 'LoadMonitorNull' => LoadMonitorNull
::class,
253 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
256 $class = $this->loadMonitorConfig
['class'];
257 if ( isset( $compat[$class] ) ) {
258 $class = $compat[$class];
261 $this->loadMonitor
= new $class(
262 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
263 $this->loadMonitor
->setLogger( $this->replLogger
);
266 return $this->loadMonitor
;
270 * @param array $loads
271 * @param bool|string $domain Domain to get non-lagged for
272 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
273 * @return bool|int|string
275 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
276 $lags = $this->getLagTimes( $domain );
278 # Unset excessively lagged servers
279 foreach ( $lags as $i => $lag ) {
281 # How much lag this server nominally is allowed to have
282 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
283 ?
$this->mServers
[$i]['max lag']
284 : $this->maxLag
; // default
285 # Constrain that futher by $maxLag argument
286 $maxServerLag = min( $maxServerLag, $maxLag );
288 $host = $this->getServerName( $i );
289 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
290 $this->replLogger
->error(
291 "Server {host} is not replicating?", [ 'host' => $host ] );
293 } elseif ( $lag > $maxServerLag ) {
294 $this->replLogger
->info(
295 "Server {host} has {lag} seconds of lag (>= {maxlag})",
296 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
303 # Find out if all the replica DBs with non-zero load are lagged
305 foreach ( $loads as $load ) {
309 # No appropriate DB servers except maybe the master and some replica DBs with zero load
310 # Do NOT use the master
311 # Instead, this function will return false, triggering read-only mode,
312 # and a lagged replica DB will be used instead.
316 if ( count( $loads ) == 0 ) {
320 # Return a random representative of the remainder
321 return ArrayUtils
::pickRandom( $loads );
324 public function getReaderIndex( $group = false, $domain = false ) {
325 if ( count( $this->mServers
) == 1 ) {
326 // Skip the load balancing if there's only one server
327 return $this->getWriterIndex();
328 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
329 // Shortcut if the generic reader index was already cached
330 return $this->mReadIndex
;
333 if ( $group !== false ) {
334 // Use the server weight array for this load group
335 if ( isset( $this->mGroupLoads
[$group] ) ) {
336 $loads = $this->mGroupLoads
[$group];
338 // No loads for this group, return false and the caller can use some other group
339 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
344 // Use the generic load group
345 $loads = $this->mLoads
;
348 // Scale the configured load ratios according to each server's load and state
349 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
351 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
352 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
353 if ( $i === false ) {
354 // Replica DB connection unsuccessful
358 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
359 // Before any data queries are run, wait for the server to catch up to the
360 // specified position. This is used to improve session consistency. Note that
361 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
362 // so update laggedReplicaMode as needed for consistency.
363 if ( !$this->doWait( $i ) ) {
364 $laggedReplicaMode = true;
368 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
369 // Cache the generic reader index for future ungrouped DB_REPLICA handles
370 $this->mReadIndex
= $i;
371 // Record if the generic reader index is in "lagged replica DB" mode
372 if ( $laggedReplicaMode ) {
373 $this->laggedReplicaMode
= true;
377 $serverName = $this->getServerName( $i );
378 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
384 * @param array $loads List of server weights
385 * @param string|bool $domain
386 * @return array (reader index, lagged replica mode) or false on failure
388 private function pickReaderIndex( array $loads, $domain = false ) {
389 if ( !count( $loads ) ) {
390 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
393 /** @var int|bool $i Index of selected server */
395 /** @var bool $laggedReplicaMode Whether server is considered lagged */
396 $laggedReplicaMode = false;
398 // Quickly look through the available servers for a server that meets criteria...
399 $currentLoads = $loads;
400 while ( count( $currentLoads ) ) {
401 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
402 $i = ArrayUtils
::pickRandom( $currentLoads );
405 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
406 // ChronologyProtecter sets mWaitForPos for session consistency.
407 // This triggers doWait() after connect, so it's especially good to
408 // avoid lagged servers so as to avoid excessive delay in that method.
409 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
410 // Aim for <= 1 second of waiting (being too picky can backfire)
411 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
413 if ( $i === false ) {
414 // Any server with less lag than it's 'max lag' param is preferable
415 $i = $this->getRandomNonLagged( $currentLoads, $domain );
417 if ( $i === false && count( $currentLoads ) != 0 ) {
418 // All replica DBs lagged. Switch to read-only mode
419 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
420 $i = ArrayUtils
::pickRandom( $currentLoads );
421 $laggedReplicaMode = true;
425 if ( $i === false ) {
426 // pickRandom() returned false.
427 // This is permanent and means the configuration or the load monitor
428 // wants us to return false.
429 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
431 return [ false, false ];
434 $serverName = $this->getServerName( $i );
435 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
437 $conn = $this->openConnection( $i, $domain );
439 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
440 unset( $currentLoads[$i] ); // avoid this server next iteration
445 // Decrement reference counter, we are finished with this connection.
446 // It will be incremented for the caller later.
447 if ( $domain !== false ) {
448 $this->reuseConnection( $conn );
451 // Return this server
455 // If all servers were down, quit now
456 if ( !count( $currentLoads ) ) {
457 $this->connLogger
->error( "All servers down" );
460 return [ $i, $laggedReplicaMode ];
463 public function waitFor( $pos ) {
464 $oldPos = $this->mWaitForPos
;
466 $this->mWaitForPos
= $pos;
467 // If a generic reader connection was already established, then wait now
468 $i = $this->mReadIndex
;
470 if ( !$this->doWait( $i ) ) {
471 $this->laggedReplicaMode
= true;
475 // Restore the older position if it was higher since this is used for lag-protection
476 $this->setWaitForPositionIfHigher( $oldPos );
480 public function waitForOne( $pos, $timeout = null ) {
481 $oldPos = $this->mWaitForPos
;
483 $this->mWaitForPos
= $pos;
485 $i = $this->mReadIndex
;
487 // Pick a generic replica DB if there isn't one yet
488 $readLoads = $this->mLoads
;
489 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
490 $readLoads = array_filter( $readLoads ); // with non-zero load
491 $i = ArrayUtils
::pickRandom( $readLoads );
495 $ok = $this->doWait( $i, true, $timeout );
497 $ok = true; // no applicable loads
500 # Restore the old position, as this is not used for lag-protection but for throttling
501 $this->mWaitForPos
= $oldPos;
507 public function waitForAll( $pos, $timeout = null ) {
508 $oldPos = $this->mWaitForPos
;
510 $this->mWaitForPos
= $pos;
511 $serverCount = count( $this->mServers
);
514 for ( $i = 1; $i < $serverCount; $i++
) {
515 if ( $this->mLoads
[$i] > 0 ) {
516 $ok = $this->doWait( $i, true, $timeout ) && $ok;
520 # Restore the old position, as this is not used for lag-protection but for throttling
521 $this->mWaitForPos
= $oldPos;
528 * @param DBMasterPos|bool $pos
530 private function setWaitForPositionIfHigher( $pos ) {
535 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
536 $this->mWaitForPos
= $pos;
542 * @return IDatabase|bool
544 public function getAnyOpenConnection( $i ) {
545 foreach ( $this->mConns
as $connsByServer ) {
546 if ( !empty( $connsByServer[$i] ) ) {
547 /** @var IDatabase[] $serverConns */
548 $serverConns = $connsByServer[$i];
550 return reset( $serverConns );
558 * Wait for a given replica DB to catch up to the master pos stored in $this
559 * @param int $index Server index
560 * @param bool $open Check the server even if a new connection has to be made
561 * @param int $timeout Max seconds to wait; default is mWaitTimeout
564 protected function doWait( $index, $open = false, $timeout = null ) {
565 $close = false; // close the connection afterwards
567 // Check if we already know that the DB has reached this point
568 $server = $this->getServerName( $index );
569 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
570 /** @var DBMasterPos $knownReachedPos */
571 $knownReachedPos = $this->srvCache
->get( $key );
573 $knownReachedPos instanceof DBMasterPos
&&
574 $knownReachedPos->hasReached( $this->mWaitForPos
)
576 $this->replLogger
->debug( __METHOD__
.
577 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
578 [ 'dbserver' => $server ] );
582 // Find a connection to wait on, creating one if needed and allowed
583 $conn = $this->getAnyOpenConnection( $index );
586 $this->replLogger
->debug( __METHOD__
. ': no connection open for {dbserver}',
587 [ 'dbserver' => $server ] );
591 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
593 $this->replLogger
->warning( __METHOD__
. ': failed to connect to {dbserver}',
594 [ 'dbserver' => $server ] );
598 // Avoid connection spam in waitForAll() when connections
599 // are made just for the sake of doing this lag check.
604 $this->replLogger
->info( __METHOD__
. ': Waiting for replica DB {dbserver} to catch up...',
605 [ 'dbserver' => $server ] );
606 $timeout = $timeout ?
: $this->mWaitTimeout
;
607 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
609 if ( $result == -1 ||
is_null( $result ) ) {
610 // Timed out waiting for replica DB, use master instead
611 $this->replLogger
->warning(
612 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
613 [ 'host' => $server, 'pos' => $this->mWaitForPos
]
617 $this->replLogger
->info( __METHOD__
. ": Done" );
619 // Remember that the DB reached this point
620 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
624 $this->closeConnection( $conn );
630 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
631 if ( $i === null ||
$i === false ) {
632 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
633 ' with invalid server index' );
636 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
637 $domain = false; // local connection requested
640 $groups = ( $groups === false ||
$groups === [] )
641 ?
[ false ] // check one "group": the generic pool
644 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
645 $oldConnsOpened = $this->connsOpened
; // connections open now
647 if ( $i == self
::DB_MASTER
) {
648 $i = $this->getWriterIndex();
650 # Try to find an available server in any the query groups (in order)
651 foreach ( $groups as $group ) {
652 $groupIndex = $this->getReaderIndex( $group, $domain );
653 if ( $groupIndex !== false ) {
660 # Operation-based index
661 if ( $i == self
::DB_REPLICA
) {
662 $this->mLastError
= 'Unknown error'; // reset error string
663 # Try the general server pool if $groups are unavailable.
664 $i = ( $groups === [ false ] )
665 ?
false // don't bother with this if that is what was tried above
666 : $this->getReaderIndex( false, $domain );
667 # Couldn't find a working server in getReaderIndex()?
668 if ( $i === false ) {
669 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
670 // Throw an exception
671 $this->reportConnectionError();
672 return null; // not reached
676 # Now we have an explicit index into the servers array
677 $conn = $this->openConnection( $i, $domain, $flags );
679 // Throw an exception
680 $this->reportConnectionError();
681 return null; // not reached
684 # Profile any new connections that happen
685 if ( $this->connsOpened
> $oldConnsOpened ) {
686 $host = $conn->getServer();
687 $dbname = $conn->getDBname();
688 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
692 # Make master-requested DB handles inherit any read-only mode setting
693 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
699 public function reuseConnection( $conn ) {
700 $serverIndex = $conn->getLBInfo( 'serverIndex' );
701 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
702 if ( $serverIndex === null ||
$refCount === null ) {
704 * This can happen in code like:
705 * foreach ( $dbs as $db ) {
706 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
708 * $lb->reuseConnection( $conn );
710 * When a connection to the local DB is opened in this way, reuseConnection()
714 } elseif ( $conn instanceof DBConnRef
) {
715 // DBConnRef already handles calling reuseConnection() and only passes the live
716 // Database instance to this method. Any caller passing in a DBConnRef is broken.
717 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
718 ( new RuntimeException() )->getTraceAsString() );
723 if ( $this->disabled
) {
724 return; // DBConnRef handle probably survived longer than the LoadBalancer
727 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
728 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
729 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
731 $connFreeKey = self
::KEY_FOREIGN_FREE
;
732 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
735 $domain = $conn->getDomainID();
736 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
737 throw new InvalidArgumentException( __METHOD__
.
738 ": connection $serverIndex/$domain not found; it may have already been freed." );
739 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
740 throw new InvalidArgumentException( __METHOD__
.
741 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
744 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
745 if ( $refCount <= 0 ) {
746 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
747 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
748 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
749 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
751 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
753 $this->connLogger
->debug( __METHOD__
.
754 ": reference count for $serverIndex/$domain reduced to $refCount" );
758 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
759 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
761 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
764 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
765 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
767 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
770 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
771 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
773 return new MaintainableDBConnRef(
774 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
777 public function openConnection( $i, $domain = false, $flags = 0 ) {
778 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
779 $domain = false; // local connection requested
782 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
783 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
784 // Load CP positions before connecting so that doWait() triggers later if needed
785 $this->chronProtInitialized
= true;
786 $this->chronProt
->initLB( $this );
789 // Check if an auto-commit connection is being requested. If so, it will not reuse the
790 // main set of DB connections but rather its own pool since:
791 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
792 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
793 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
795 if ( $domain !== false ) {
796 // Connection is to a foreign domain
797 $conn = $this->openForeignConnection( $i, $domain, $flags );
799 // Connection is to the local domain
800 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
801 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
802 $conn = $this->mConns
[$connKey][$i][0];
804 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
805 throw new InvalidArgumentException( "No server with index '$i'." );
807 // Open a new connection
808 $server = $this->mServers
[$i];
809 $server['serverIndex'] = $i;
810 $server['autoCommitOnly'] = $autoCommit;
811 $conn = $this->reallyOpenConnection( $server, false );
812 $host = $this->getServerName( $i );
813 if ( $conn->isOpen() ) {
814 $this->connLogger
->debug( "Connected to database $i at '$host'." );
815 $this->mConns
[$connKey][$i][0] = $conn;
817 $this->connLogger
->warning( "Failed to connect to database $i at '$host'." );
818 $this->errorConnection
= $conn;
824 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
825 // Connection was made but later unrecoverably lost for some reason.
826 // Do not return a handle that will just throw exceptions on use,
827 // but let the calling code (e.g. getReaderIndex) try another server.
828 // See DatabaseMyslBase::ping() for how this can happen.
829 $this->errorConnection
= $conn;
833 if ( $autoCommit && $conn instanceof IDatabase
) {
834 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
841 * Open a connection to a foreign DB, or return one if it is already open.
843 * Increments a reference count on the returned connection which locks the
844 * connection to the requested domain. This reference count can be
845 * decremented by calling reuseConnection().
847 * If a connection is open to the appropriate server already, but with the wrong
848 * database, it will be switched to the right database and returned, as long as
849 * it has been freed first with reuseConnection().
851 * On error, returns false, and the connection which caused the
852 * error will be available via $this->errorConnection.
854 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
856 * @param int $i Server index
857 * @param string $domain Domain ID to open
858 * @param int $flags Class CONN_* constant bitfield
861 private function openForeignConnection( $i, $domain, $flags = 0 ) {
862 $domainInstance = DatabaseDomain
::newFromId( $domain );
863 $dbName = $domainInstance->getDatabase();
864 $prefix = $domainInstance->getTablePrefix();
865 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
868 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
869 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
871 $connFreeKey = self
::KEY_FOREIGN_FREE
;
872 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
875 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
876 // Reuse an in-use connection for the same domain
877 $conn = $this->mConns
[$connInUseKey][$i][$domain];
878 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
879 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
880 // Reuse a free connection for the same domain
881 $conn = $this->mConns
[$connFreeKey][$i][$domain];
882 unset( $this->mConns
[$connFreeKey][$i][$domain] );
883 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
884 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
885 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
886 // Reuse a free connection from another domain
887 $conn = reset( $this->mConns
[$connFreeKey][$i] );
888 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
889 // The empty string as a DB name means "don't care".
890 // DatabaseMysqlBase::open() already handle this on connection.
891 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
892 $this->mLastError
= "Error selecting database '$dbName' on server " .
893 $conn->getServer() . " from client host {$this->host}";
894 $this->errorConnection
= $conn;
897 $conn->tablePrefix( $prefix );
898 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
899 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
900 $this->connLogger
->debug( __METHOD__
.
901 ": reusing free connection from $oldDomain for $domain" );
904 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
905 throw new InvalidArgumentException( "No server with index '$i'." );
907 // Open a new connection
908 $server = $this->mServers
[$i];
909 $server['serverIndex'] = $i;
910 $server['foreignPoolRefCount'] = 0;
911 $server['foreign'] = true;
912 $server['autoCommitOnly'] = $autoCommit;
913 $conn = $this->reallyOpenConnection( $server, $dbName );
914 if ( !$conn->isOpen() ) {
915 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
916 $this->errorConnection
= $conn;
919 $conn->tablePrefix( $prefix );
920 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
921 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
925 // Increment reference count
926 if ( $conn instanceof IDatabase
) {
927 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
928 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
935 * Test if the specified index represents an open connection
937 * @param int $index Server index
941 private function isOpen( $index ) {
942 if ( !is_integer( $index ) ) {
946 return (bool)$this->getAnyOpenConnection( $index );
950 * Really opens a connection. Uncached.
951 * Returns a Database object whether or not the connection was successful.
954 * @param array $server
955 * @param string|bool $dbNameOverride Use "" to not select any database
957 * @throws DBAccessError
958 * @throws InvalidArgumentException
960 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
961 if ( $this->disabled
) {
962 throw new DBAccessError();
965 if ( $dbNameOverride !== false ) {
966 $server['dbname'] = $dbNameOverride;
969 // Let the handle know what the cluster master is (e.g. "db1052")
970 $masterName = $this->getServerName( $this->getWriterIndex() );
971 $server['clusterMasterHost'] = $masterName;
973 // Log when many connection are made on requests
974 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
975 $this->perfLogger
->warning( __METHOD__
. ": " .
976 "{$this->connsOpened}+ connections made (master=$masterName)" );
979 $server['srvCache'] = $this->srvCache
;
980 // Set loggers and profilers
981 $server['connLogger'] = $this->connLogger
;
982 $server['queryLogger'] = $this->queryLogger
;
983 $server['errorLogger'] = $this->errorLogger
;
984 $server['profiler'] = $this->profiler
;
985 $server['trxProfiler'] = $this->trxProfiler
;
986 // Use the same agent and PHP mode for all DB handles
987 $server['cliMode'] = $this->cliMode
;
988 $server['agent'] = $this->agent
;
989 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
990 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
991 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
993 // Create a live connection object
995 $db = Database
::factory( $server['type'], $server );
996 } catch ( DBConnectionError
$e ) {
997 // FIXME: This is probably the ugliest thing I have ever done to
998 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1002 $db->setLBInfo( $server );
1003 $db->setLazyMasterHandle(
1004 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1006 $db->setTableAliases( $this->tableAliases
);
1008 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1009 if ( $this->trxRoundId
!== false ) {
1010 $this->applyTransactionRoundFlags( $db );
1012 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1013 $db->setTransactionListener( $name, $callback );
1021 * @throws DBConnectionError
1023 private function reportConnectionError() {
1024 $conn = $this->errorConnection
; // the connection which caused the error
1026 'method' => __METHOD__
,
1027 'last_error' => $this->mLastError
,
1030 if ( $conn instanceof IDatabase
) {
1031 $context['db_server'] = $conn->getServer();
1032 $this->connLogger
->warning(
1033 "Connection error: {last_error} ({db_server})",
1037 // throws DBConnectionError
1038 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1040 // No last connection, probably due to all servers being too busy
1041 $this->connLogger
->error(
1042 "LB failure with no last connection. Connection error: {last_error}",
1046 // If all servers were busy, mLastError will contain something sensible
1047 throw new DBConnectionError( null, $this->mLastError
);
1051 public function getWriterIndex() {
1055 public function haveIndex( $i ) {
1056 return array_key_exists( $i, $this->mServers
);
1059 public function isNonZeroLoad( $i ) {
1060 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1063 public function getServerCount() {
1064 return count( $this->mServers
);
1067 public function getServerName( $i ) {
1068 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1069 $name = $this->mServers
[$i]['hostName'];
1070 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1071 $name = $this->mServers
[$i]['host'];
1076 return ( $name != '' ) ?
$name : 'localhost';
1079 public function getServerType( $i ) {
1080 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
1084 * @deprecated Since 1.30, no alternative
1086 public function getServerInfo( $i ) {
1087 wfDeprecated( __METHOD__
, '1.30' );
1088 if ( isset( $this->mServers
[$i] ) ) {
1089 return $this->mServers
[$i];
1096 * @deprecated Since 1.30, construct new object
1098 public function setServerInfo( $i, array $serverInfo ) {
1099 wfDeprecated( __METHOD__
, '1.30' );
1100 $this->mServers
[$i] = $serverInfo;
1103 public function getMasterPos() {
1104 # If this entire request was served from a replica DB without opening a connection to the
1105 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1106 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1107 if ( !$masterConn ) {
1108 $serverCount = count( $this->mServers
);
1109 for ( $i = 1; $i < $serverCount; $i++
) {
1110 $conn = $this->getAnyOpenConnection( $i );
1112 return $conn->getReplicaPos();
1116 return $masterConn->getMasterPos();
1122 public function disable() {
1124 $this->disabled
= true;
1127 public function closeAll() {
1128 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1129 $host = $conn->getServer();
1130 $this->connLogger
->debug( "Closing connection to database '$host'." );
1135 self
::KEY_LOCAL
=> [],
1136 self
::KEY_FOREIGN_INUSE
=> [],
1137 self
::KEY_FOREIGN_FREE
=> [],
1138 self
::KEY_LOCAL_NOROUND
=> [],
1139 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1140 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1142 $this->connsOpened
= 0;
1145 public function closeConnection( IDatabase
$conn ) {
1146 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1147 foreach ( $this->mConns
as $type => $connsByServer ) {
1148 if ( !isset( $connsByServer[$serverIndex] ) ) {
1152 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1153 if ( $conn === $trackedConn ) {
1154 $host = $this->getServerName( $i );
1155 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1156 unset( $this->mConns
[$type][$serverIndex][$i] );
1157 --$this->connsOpened
;
1166 public function commitAll( $fname = __METHOD__
) {
1169 $restore = ( $this->trxRoundId
!== false );
1170 $this->trxRoundId
= false;
1171 $this->forEachOpenConnection(
1172 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1174 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1175 } catch ( DBError
$e ) {
1176 call_user_func( $this->errorLogger
, $e );
1177 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1179 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1180 $this->undoTransactionRoundFlags( $conn );
1186 throw new DBExpectedError(
1188 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1193 public function finalizeMasterChanges() {
1194 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1195 // Any error should cause all DB transactions to be rolled back together
1196 $conn->setTrxEndCallbackSuppression( false );
1197 $conn->runOnTransactionPreCommitCallbacks();
1198 // Defer post-commit callbacks until COMMIT finishes for all DBs
1199 $conn->setTrxEndCallbackSuppression( true );
1203 public function approveMasterChanges( array $options ) {
1204 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1205 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1206 // If atomic sections or explicit transactions are still open, some caller must have
1207 // caught an exception but failed to properly rollback any changes. Detect that and
1208 // throw and error (causing rollback).
1209 if ( $conn->explicitTrxActive() ) {
1210 throw new DBTransactionError(
1212 "Explicit transaction still active. A caller may have caught an error."
1215 // Assert that the time to replicate the transaction will be sane.
1216 // If this fails, then all DB transactions will be rollback back together.
1217 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1218 if ( $limit > 0 && $time > $limit ) {
1219 throw new DBTransactionSizeError(
1221 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1225 // If a connection sits idle while slow queries execute on another, that connection
1226 // may end up dropped before the commit round is reached. Ping servers to detect this.
1227 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1228 throw new DBTransactionError(
1230 "A connection to the {$conn->getDBname()} database was lost before commit."
1236 public function beginMasterChanges( $fname = __METHOD__
) {
1237 if ( $this->trxRoundId
!== false ) {
1238 throw new DBTransactionError(
1240 "$fname: Transaction round '{$this->trxRoundId}' already started."
1243 $this->trxRoundId
= $fname;
1246 $this->forEachOpenMasterConnection(
1247 function ( Database
$conn ) use ( $fname, &$failures ) {
1248 $conn->setTrxEndCallbackSuppression( true );
1250 $conn->flushSnapshot( $fname );
1251 } catch ( DBError
$e ) {
1252 call_user_func( $this->errorLogger
, $e );
1253 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1255 $conn->setTrxEndCallbackSuppression( false );
1256 $this->applyTransactionRoundFlags( $conn );
1261 throw new DBExpectedError(
1263 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1268 public function commitMasterChanges( $fname = __METHOD__
) {
1271 /** @noinspection PhpUnusedLocalVariableInspection */
1272 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1274 $restore = ( $this->trxRoundId
!== false );
1275 $this->trxRoundId
= false;
1276 $this->forEachOpenMasterConnection(
1277 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1279 if ( $conn->writesOrCallbacksPending() ) {
1280 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1281 } elseif ( $restore ) {
1282 $conn->flushSnapshot( $fname );
1284 } catch ( DBError
$e ) {
1285 call_user_func( $this->errorLogger
, $e );
1286 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1289 $this->undoTransactionRoundFlags( $conn );
1295 throw new DBExpectedError(
1297 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1302 public function runMasterPostTrxCallbacks( $type ) {
1303 $e = null; // first exception
1304 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1305 $conn->setTrxEndCallbackSuppression( false );
1306 if ( $conn->writesOrCallbacksPending() ) {
1307 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1308 // (which finished its callbacks already). Warn and recover in this case. Let the
1309 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1310 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1312 } elseif ( $conn->trxLevel() ) {
1313 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1314 // thus leaving an implicit read-only transaction open at this point. It
1315 // also happens if onTransactionIdle() callbacks leave implicit transactions
1316 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1317 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1321 $conn->runOnTransactionIdleCallbacks( $type );
1322 } catch ( Exception
$ex ) {
1326 $conn->runTransactionListenerCallbacks( $type );
1327 } catch ( Exception
$ex ) {
1335 public function rollbackMasterChanges( $fname = __METHOD__
) {
1336 $restore = ( $this->trxRoundId
!== false );
1337 $this->trxRoundId
= false;
1338 $this->forEachOpenMasterConnection(
1339 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1340 if ( $conn->writesOrCallbacksPending() ) {
1341 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1344 $this->undoTransactionRoundFlags( $conn );
1350 public function suppressTransactionEndCallbacks() {
1351 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1352 $conn->setTrxEndCallbackSuppression( true );
1357 * @param IDatabase $conn
1359 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1360 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1361 return; // transaction rounds do not apply to these connections
1364 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1365 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1366 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1367 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1368 // If config has explicitly requested DBO_TRX be either on or off by not
1369 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1370 // for things like blob stores (ExternalStore) which want auto-commit mode.
1375 * @param IDatabase $conn
1377 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1378 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1379 return; // transaction rounds do not apply to these connections
1382 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1383 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1387 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1388 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1389 $conn->flushSnapshot( __METHOD__
);
1393 public function hasMasterConnection() {
1394 return $this->isOpen( $this->getWriterIndex() );
1397 public function hasMasterChanges() {
1399 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1400 $pending |
= $conn->writesOrCallbacksPending();
1403 return (bool)$pending;
1406 public function lastMasterChangeTimestamp() {
1408 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1409 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1415 public function hasOrMadeRecentMasterChanges( $age = null ) {
1416 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1418 return ( $this->hasMasterChanges()
1419 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1422 public function pendingMasterChangeCallers() {
1424 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1425 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1431 public function getLaggedReplicaMode( $domain = false ) {
1432 // No-op if there is only one DB (also avoids recursion)
1433 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1435 // See if laggedReplicaMode gets set
1436 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1437 $this->reuseConnection( $conn );
1438 } catch ( DBConnectionError
$e ) {
1439 // Avoid expensive re-connect attempts and failures
1440 $this->allReplicasDownMode
= true;
1441 $this->laggedReplicaMode
= true;
1445 return $this->laggedReplicaMode
;
1449 * @param bool $domain
1451 * @deprecated 1.28; use getLaggedReplicaMode()
1453 public function getLaggedSlaveMode( $domain = false ) {
1454 return $this->getLaggedReplicaMode( $domain );
1457 public function laggedReplicaUsed() {
1458 return $this->laggedReplicaMode
;
1464 * @deprecated Since 1.28; use laggedReplicaUsed()
1466 public function laggedSlaveUsed() {
1467 return $this->laggedReplicaUsed();
1470 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1471 if ( $this->readOnlyReason
!== false ) {
1472 return $this->readOnlyReason
;
1473 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1474 if ( $this->allReplicasDownMode
) {
1475 return 'The database has been automatically locked ' .
1476 'until the replica database servers become available';
1478 return 'The database has been automatically locked ' .
1479 'while the replica database servers catch up to the master.';
1481 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1482 return 'The database master is running in read-only mode.';
1489 * @param string $domain Domain ID, or false for the current domain
1490 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1493 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1494 $cache = $this->wanCache
;
1495 $masterServer = $this->getServerName( $this->getWriterIndex() );
1497 return (bool)$cache->getWithSetCallback(
1498 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1499 self
::TTL_CACHE_READONLY
,
1500 function () use ( $domain, $conn ) {
1501 $old = $this->trxProfiler
->setSilenced( true );
1503 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1504 $readOnly = (int)$dbw->serverIsReadOnly();
1506 $this->reuseConnection( $dbw );
1508 } catch ( DBError
$e ) {
1511 $this->trxProfiler
->setSilenced( $old );
1514 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1518 public function allowLagged( $mode = null ) {
1519 if ( $mode === null ) {
1520 return $this->mAllowLagged
;
1522 $this->mAllowLagged
= $mode;
1524 return $this->mAllowLagged
;
1527 public function pingAll() {
1529 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1530 if ( !$conn->ping() ) {
1538 public function forEachOpenConnection( $callback, array $params = [] ) {
1539 foreach ( $this->mConns
as $connsByServer ) {
1540 foreach ( $connsByServer as $serverConns ) {
1541 foreach ( $serverConns as $conn ) {
1542 $mergedParams = array_merge( [ $conn ], $params );
1543 call_user_func_array( $callback, $mergedParams );
1549 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1550 $masterIndex = $this->getWriterIndex();
1551 foreach ( $this->mConns
as $connsByServer ) {
1552 if ( isset( $connsByServer[$masterIndex] ) ) {
1553 /** @var IDatabase $conn */
1554 foreach ( $connsByServer[$masterIndex] as $conn ) {
1555 $mergedParams = array_merge( [ $conn ], $params );
1556 call_user_func_array( $callback, $mergedParams );
1562 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1563 foreach ( $this->mConns
as $connsByServer ) {
1564 foreach ( $connsByServer as $i => $serverConns ) {
1565 if ( $i === $this->getWriterIndex() ) {
1566 continue; // skip master
1568 foreach ( $serverConns as $conn ) {
1569 $mergedParams = array_merge( [ $conn ], $params );
1570 call_user_func_array( $callback, $mergedParams );
1576 public function getMaxLag( $domain = false ) {
1581 if ( $this->getServerCount() <= 1 ) {
1582 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1585 $lagTimes = $this->getLagTimes( $domain );
1586 foreach ( $lagTimes as $i => $lag ) {
1587 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1589 $host = $this->mServers
[$i]['host'];
1594 return [ $host, $maxLag, $maxIndex ];
1597 public function getLagTimes( $domain = false ) {
1598 if ( $this->getServerCount() <= 1 ) {
1599 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1602 $knownLagTimes = []; // map of (server index => 0 seconds)
1603 $indexesWithLag = [];
1604 foreach ( $this->mServers
as $i => $server ) {
1605 if ( empty( $server['is static'] ) ) {
1606 $indexesWithLag[] = $i; // DB server might have replication lag
1608 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1612 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1615 public function safeGetLag( IDatabase
$conn ) {
1616 if ( $this->getServerCount() <= 1 ) {
1619 return $conn->getLag();
1624 * @param IDatabase $conn
1625 * @param DBMasterPos|bool $pos
1626 * @param int $timeout
1629 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1630 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1631 return true; // server is not a replica DB
1635 // Get the current master position, opening a connection if needed
1636 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1637 if ( $masterConn ) {
1638 $pos = $masterConn->getMasterPos();
1640 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1641 $pos = $masterConn->getMasterPos();
1642 $this->closeConnection( $masterConn );
1646 if ( $pos instanceof DBMasterPos
) {
1647 $result = $conn->masterPosWait( $pos, $timeout );
1648 if ( $result == -1 ||
is_null( $result ) ) {
1649 $msg = __METHOD__
. ': Timed out waiting on {host} pos {pos}';
1650 $this->replLogger
->warning( $msg,
1651 [ 'host' => $conn->getServer(), 'pos' => $pos ] );
1654 $this->replLogger
->info( __METHOD__
. ': Done' );
1658 $ok = false; // something is misconfigured
1659 $this->replLogger
->error( 'Could not get master pos for {host}',
1660 [ 'host' => $conn->getServer() ] );
1666 public function setTransactionListener( $name, callable
$callback = null ) {
1668 $this->trxRecurringCallbacks
[$name] = $callback;
1670 unset( $this->trxRecurringCallbacks
[$name] );
1672 $this->forEachOpenMasterConnection(
1673 function ( IDatabase
$conn ) use ( $name, $callback ) {
1674 $conn->setTransactionListener( $name, $callback );
1679 public function setTableAliases( array $aliases ) {
1680 $this->tableAliases
= $aliases;
1683 public function setDomainPrefix( $prefix ) {
1684 // Find connections to explicit foreign domains still marked as in-use...
1686 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1687 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1688 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1689 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1690 $domainsInUse[] = $conn->getDomainID();
1694 // Do not switch connections to explicit foreign domains unless marked as safe
1695 if ( $domainsInUse ) {
1696 $domains = implode( ', ', $domainsInUse );
1697 throw new DBUnexpectedError( null,
1698 "Foreign domain connections are still in use ($domains)." );
1701 $this->localDomain
= new DatabaseDomain(
1702 $this->localDomain
->getDatabase(),
1707 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1708 $db->tablePrefix( $prefix );
1713 * Make PHP ignore user aborts/disconnects until the returned
1714 * value leaves scope. This returns null and does nothing in CLI mode.
1716 * @return ScopedCallback|null
1718 final protected function getScopedPHPBehaviorForCommit() {
1719 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1720 $old = ignore_user_abort( true ); // avoid half-finished operations
1721 return new ScopedCallback( function () use ( $old ) {
1722 ignore_user_abort( $old );
1729 function __destruct() {
1730 // Avoid connection leaks for sanity
1735 class_alias( LoadBalancer
::class, 'LoadBalancer' );