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'] )
237 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
238 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
240 if ( isset( $params['chronologyProtector'] ) ) {
241 $this->chronProt
= $params['chronologyProtector'];
246 * Get a LoadMonitor instance
248 * @return ILoadMonitor
250 private function getLoadMonitor() {
251 if ( !isset( $this->loadMonitor
) ) {
253 'LoadMonitor' => LoadMonitor
::class,
254 'LoadMonitorNull' => LoadMonitorNull
::class,
255 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
258 $class = $this->loadMonitorConfig
['class'];
259 if ( isset( $compat[$class] ) ) {
260 $class = $compat[$class];
263 $this->loadMonitor
= new $class(
264 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
265 $this->loadMonitor
->setLogger( $this->replLogger
);
268 return $this->loadMonitor
;
272 * @param array $loads
273 * @param bool|string $domain Domain to get non-lagged for
274 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
275 * @return bool|int|string
277 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
278 $lags = $this->getLagTimes( $domain );
280 # Unset excessively lagged servers
281 foreach ( $lags as $i => $lag ) {
283 # How much lag this server nominally is allowed to have
284 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
285 ?
$this->mServers
[$i]['max lag']
286 : $this->maxLag
; // default
287 # Constrain that futher by $maxLag argument
288 $maxServerLag = min( $maxServerLag, $maxLag );
290 $host = $this->getServerName( $i );
291 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
292 $this->replLogger
->error(
293 "Server {host} is not replicating?", [ 'host' => $host ] );
295 } elseif ( $lag > $maxServerLag ) {
296 $this->replLogger
->info(
297 "Server {host} has {lag} seconds of lag (>= {maxlag})",
298 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
305 # Find out if all the replica DBs with non-zero load are lagged
307 foreach ( $loads as $load ) {
311 # No appropriate DB servers except maybe the master and some replica DBs with zero load
312 # Do NOT use the master
313 # Instead, this function will return false, triggering read-only mode,
314 # and a lagged replica DB will be used instead.
318 if ( count( $loads ) == 0 ) {
322 # Return a random representative of the remainder
323 return ArrayUtils
::pickRandom( $loads );
326 public function getReaderIndex( $group = false, $domain = false ) {
327 if ( count( $this->mServers
) == 1 ) {
328 // Skip the load balancing if there's only one server
329 return $this->getWriterIndex();
330 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
331 // Shortcut if the generic reader index was already cached
332 return $this->mReadIndex
;
335 if ( $group !== false ) {
336 // Use the server weight array for this load group
337 if ( isset( $this->mGroupLoads
[$group] ) ) {
338 $loads = $this->mGroupLoads
[$group];
340 // No loads for this group, return false and the caller can use some other group
341 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
346 // Use the generic load group
347 $loads = $this->mLoads
;
350 // Scale the configured load ratios according to each server's load and state
351 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
353 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
354 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
355 if ( $i === false ) {
356 // Replica DB connection unsuccessful
360 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
361 // Before any data queries are run, wait for the server to catch up to the
362 // specified position. This is used to improve session consistency. Note that
363 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
364 // so update laggedReplicaMode as needed for consistency.
365 if ( !$this->doWait( $i ) ) {
366 $laggedReplicaMode = true;
370 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
371 // Cache the generic reader index for future ungrouped DB_REPLICA handles
372 $this->mReadIndex
= $i;
373 // Record if the generic reader index is in "lagged replica DB" mode
374 if ( $laggedReplicaMode ) {
375 $this->laggedReplicaMode
= true;
379 $serverName = $this->getServerName( $i );
380 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
386 * @param array $loads List of server weights
387 * @param string|bool $domain
388 * @return array (reader index, lagged replica mode) or false on failure
390 private function pickReaderIndex( array $loads, $domain = false ) {
391 if ( !count( $loads ) ) {
392 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
395 /** @var int|bool $i Index of selected server */
397 /** @var bool $laggedReplicaMode Whether server is considered lagged */
398 $laggedReplicaMode = false;
400 // Quickly look through the available servers for a server that meets criteria...
401 $currentLoads = $loads;
402 while ( count( $currentLoads ) ) {
403 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
404 $i = ArrayUtils
::pickRandom( $currentLoads );
407 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
408 // ChronologyProtecter sets mWaitForPos for session consistency.
409 // This triggers doWait() after connect, so it's especially good to
410 // avoid lagged servers so as to avoid excessive delay in that method.
411 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
412 // Aim for <= 1 second of waiting (being too picky can backfire)
413 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
415 if ( $i === false ) {
416 // Any server with less lag than it's 'max lag' param is preferable
417 $i = $this->getRandomNonLagged( $currentLoads, $domain );
419 if ( $i === false && count( $currentLoads ) != 0 ) {
420 // All replica DBs lagged. Switch to read-only mode
421 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
422 $i = ArrayUtils
::pickRandom( $currentLoads );
423 $laggedReplicaMode = true;
427 if ( $i === false ) {
428 // pickRandom() returned false.
429 // This is permanent and means the configuration or the load monitor
430 // wants us to return false.
431 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
433 return [ false, false ];
436 $serverName = $this->getServerName( $i );
437 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
439 $conn = $this->openConnection( $i, $domain );
441 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
442 unset( $currentLoads[$i] ); // avoid this server next iteration
447 // Decrement reference counter, we are finished with this connection.
448 // It will be incremented for the caller later.
449 if ( $domain !== false ) {
450 $this->reuseConnection( $conn );
453 // Return this server
457 // If all servers were down, quit now
458 if ( !count( $currentLoads ) ) {
459 $this->connLogger
->error( "All servers down" );
462 return [ $i, $laggedReplicaMode ];
465 public function waitFor( $pos ) {
466 $oldPos = $this->mWaitForPos
;
468 $this->mWaitForPos
= $pos;
469 // If a generic reader connection was already established, then wait now
470 $i = $this->mReadIndex
;
472 if ( !$this->doWait( $i ) ) {
473 $this->laggedReplicaMode
= true;
477 // Restore the older position if it was higher since this is used for lag-protection
478 $this->setWaitForPositionIfHigher( $oldPos );
482 public function waitForOne( $pos, $timeout = null ) {
483 $oldPos = $this->mWaitForPos
;
485 $this->mWaitForPos
= $pos;
487 $i = $this->mReadIndex
;
489 // Pick a generic replica DB if there isn't one yet
490 $readLoads = $this->mLoads
;
491 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
492 $readLoads = array_filter( $readLoads ); // with non-zero load
493 $i = ArrayUtils
::pickRandom( $readLoads );
497 $ok = $this->doWait( $i, true, $timeout );
499 $ok = true; // no applicable loads
502 # Restore the old position, as this is not used for lag-protection but for throttling
503 $this->mWaitForPos
= $oldPos;
509 public function waitForAll( $pos, $timeout = null ) {
510 $oldPos = $this->mWaitForPos
;
512 $this->mWaitForPos
= $pos;
513 $serverCount = count( $this->mServers
);
516 for ( $i = 1; $i < $serverCount; $i++
) {
517 if ( $this->mLoads
[$i] > 0 ) {
518 $ok = $this->doWait( $i, true, $timeout ) && $ok;
522 # Restore the old position, as this is not used for lag-protection but for throttling
523 $this->mWaitForPos
= $oldPos;
530 * @param DBMasterPos|bool $pos
532 private function setWaitForPositionIfHigher( $pos ) {
537 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
538 $this->mWaitForPos
= $pos;
544 * @return IDatabase|bool
546 public function getAnyOpenConnection( $i ) {
547 foreach ( $this->mConns
as $connsByServer ) {
548 if ( !empty( $connsByServer[$i] ) ) {
549 /** @var IDatabase[] $serverConns */
550 $serverConns = $connsByServer[$i];
552 return reset( $serverConns );
560 * Wait for a given replica DB to catch up to the master pos stored in $this
561 * @param int $index Server index
562 * @param bool $open Check the server even if a new connection has to be made
563 * @param int $timeout Max seconds to wait; default is mWaitTimeout
566 protected function doWait( $index, $open = false, $timeout = null ) {
567 $close = false; // close the connection afterwards
569 // Check if we already know that the DB has reached this point
570 $server = $this->getServerName( $index );
571 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
572 /** @var DBMasterPos $knownReachedPos */
573 $knownReachedPos = $this->srvCache
->get( $key );
575 $knownReachedPos instanceof DBMasterPos
&&
576 $knownReachedPos->hasReached( $this->mWaitForPos
)
578 $this->replLogger
->debug( __METHOD__
.
579 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
580 [ 'dbserver' => $server ] );
584 // Find a connection to wait on, creating one if needed and allowed
585 $conn = $this->getAnyOpenConnection( $index );
588 $this->replLogger
->debug( __METHOD__
. ': no connection open for {dbserver}',
589 [ 'dbserver' => $server ] );
593 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
595 $this->replLogger
->warning( __METHOD__
. ': failed to connect to {dbserver}',
596 [ 'dbserver' => $server ] );
600 // Avoid connection spam in waitForAll() when connections
601 // are made just for the sake of doing this lag check.
606 $this->replLogger
->info( __METHOD__
. ': Waiting for replica DB {dbserver} to catch up...',
607 [ 'dbserver' => $server ] );
608 $timeout = $timeout ?
: $this->mWaitTimeout
;
609 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
611 if ( $result == -1 ||
is_null( $result ) ) {
612 // Timed out waiting for replica DB, use master instead
613 $this->replLogger
->warning(
614 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
615 [ 'host' => $server, 'pos' => $this->mWaitForPos
]
619 $this->replLogger
->info( __METHOD__
. ": Done" );
621 // Remember that the DB reached this point
622 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
626 $this->closeConnection( $conn );
632 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
633 if ( $i === null ||
$i === false ) {
634 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
635 ' with invalid server index' );
638 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
639 $domain = false; // local connection requested
642 $groups = ( $groups === false ||
$groups === [] )
643 ?
[ false ] // check one "group": the generic pool
646 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
647 $oldConnsOpened = $this->connsOpened
; // connections open now
649 if ( $i == self
::DB_MASTER
) {
650 $i = $this->getWriterIndex();
652 # Try to find an available server in any the query groups (in order)
653 foreach ( $groups as $group ) {
654 $groupIndex = $this->getReaderIndex( $group, $domain );
655 if ( $groupIndex !== false ) {
662 # Operation-based index
663 if ( $i == self
::DB_REPLICA
) {
664 $this->mLastError
= 'Unknown error'; // reset error string
665 # Try the general server pool if $groups are unavailable.
666 $i = ( $groups === [ false ] )
667 ?
false // don't bother with this if that is what was tried above
668 : $this->getReaderIndex( false, $domain );
669 # Couldn't find a working server in getReaderIndex()?
670 if ( $i === false ) {
671 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
672 // Throw an exception
673 $this->reportConnectionError();
674 return null; // not reached
678 # Now we have an explicit index into the servers array
679 $conn = $this->openConnection( $i, $domain, $flags );
681 // Throw an exception
682 $this->reportConnectionError();
683 return null; // not reached
686 # Profile any new connections that happen
687 if ( $this->connsOpened
> $oldConnsOpened ) {
688 $host = $conn->getServer();
689 $dbname = $conn->getDBname();
690 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
694 # Make master-requested DB handles inherit any read-only mode setting
695 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
701 public function reuseConnection( $conn ) {
702 $serverIndex = $conn->getLBInfo( 'serverIndex' );
703 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
704 if ( $serverIndex === null ||
$refCount === null ) {
706 * This can happen in code like:
707 * foreach ( $dbs as $db ) {
708 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
710 * $lb->reuseConnection( $conn );
712 * When a connection to the local DB is opened in this way, reuseConnection()
716 } elseif ( $conn instanceof DBConnRef
) {
717 // DBConnRef already handles calling reuseConnection() and only passes the live
718 // Database instance to this method. Any caller passing in a DBConnRef is broken.
719 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
720 ( new RuntimeException() )->getTraceAsString() );
725 if ( $this->disabled
) {
726 return; // DBConnRef handle probably survived longer than the LoadBalancer
729 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
730 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
731 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
733 $connFreeKey = self
::KEY_FOREIGN_FREE
;
734 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
737 $domain = $conn->getDomainID();
738 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
739 throw new InvalidArgumentException( __METHOD__
.
740 ": connection $serverIndex/$domain not found; it may have already been freed." );
741 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
742 throw new InvalidArgumentException( __METHOD__
.
743 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
746 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
747 if ( $refCount <= 0 ) {
748 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
749 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
750 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
751 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
753 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
755 $this->connLogger
->debug( __METHOD__
.
756 ": reference count for $serverIndex/$domain reduced to $refCount" );
760 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
761 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
763 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
766 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
767 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
769 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
772 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
773 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
775 return new MaintainableDBConnRef(
776 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
779 public function openConnection( $i, $domain = false, $flags = 0 ) {
780 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
781 $domain = false; // local connection requested
784 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
785 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
786 // Load CP positions before connecting so that doWait() triggers later if needed
787 $this->chronProtInitialized
= true;
788 $this->chronProt
->initLB( $this );
791 // Check if an auto-commit connection is being requested. If so, it will not reuse the
792 // main set of DB connections but rather its own pool since:
793 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
794 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
795 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
797 if ( $domain !== false ) {
798 // Connection is to a foreign domain
799 $conn = $this->openForeignConnection( $i, $domain, $flags );
801 // Connection is to the local domain
802 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
803 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
804 $conn = $this->mConns
[$connKey][$i][0];
806 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
807 throw new InvalidArgumentException( "No server with index '$i'." );
809 // Open a new connection
810 $server = $this->mServers
[$i];
811 $server['serverIndex'] = $i;
812 $server['autoCommitOnly'] = $autoCommit;
813 $conn = $this->reallyOpenConnection( $server, false );
814 $host = $this->getServerName( $i );
815 if ( $conn->isOpen() ) {
816 $this->connLogger
->debug( "Connected to database $i at '$host'." );
817 $this->mConns
[$connKey][$i][0] = $conn;
819 $this->connLogger
->warning( "Failed to connect to database $i at '$host'." );
820 $this->errorConnection
= $conn;
826 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
827 // Connection was made but later unrecoverably lost for some reason.
828 // Do not return a handle that will just throw exceptions on use,
829 // but let the calling code (e.g. getReaderIndex) try another server.
830 // See DatabaseMyslBase::ping() for how this can happen.
831 $this->errorConnection
= $conn;
835 if ( $autoCommit && $conn instanceof IDatabase
) {
836 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
843 * Open a connection to a foreign DB, or return one if it is already open.
845 * Increments a reference count on the returned connection which locks the
846 * connection to the requested domain. This reference count can be
847 * decremented by calling reuseConnection().
849 * If a connection is open to the appropriate server already, but with the wrong
850 * database, it will be switched to the right database and returned, as long as
851 * it has been freed first with reuseConnection().
853 * On error, returns false, and the connection which caused the
854 * error will be available via $this->errorConnection.
856 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
858 * @param int $i Server index
859 * @param string $domain Domain ID to open
860 * @param int $flags Class CONN_* constant bitfield
863 private function openForeignConnection( $i, $domain, $flags = 0 ) {
864 $domainInstance = DatabaseDomain
::newFromId( $domain );
865 $dbName = $domainInstance->getDatabase();
866 $prefix = $domainInstance->getTablePrefix();
867 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
870 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
871 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
873 $connFreeKey = self
::KEY_FOREIGN_FREE
;
874 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
877 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
878 // Reuse an in-use connection for the same domain
879 $conn = $this->mConns
[$connInUseKey][$i][$domain];
880 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
881 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
882 // Reuse a free connection for the same domain
883 $conn = $this->mConns
[$connFreeKey][$i][$domain];
884 unset( $this->mConns
[$connFreeKey][$i][$domain] );
885 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
886 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
887 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
888 // Reuse a free connection from another domain
889 $conn = reset( $this->mConns
[$connFreeKey][$i] );
890 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
891 // The empty string as a DB name means "don't care".
892 // DatabaseMysqlBase::open() already handle this on connection.
893 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
894 $this->mLastError
= "Error selecting database '$dbName' on server " .
895 $conn->getServer() . " from client host {$this->host}";
896 $this->errorConnection
= $conn;
899 $conn->tablePrefix( $prefix );
900 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
901 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
902 $this->connLogger
->debug( __METHOD__
.
903 ": reusing free connection from $oldDomain for $domain" );
906 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
907 throw new InvalidArgumentException( "No server with index '$i'." );
909 // Open a new connection
910 $server = $this->mServers
[$i];
911 $server['serverIndex'] = $i;
912 $server['foreignPoolRefCount'] = 0;
913 $server['foreign'] = true;
914 $server['autoCommitOnly'] = $autoCommit;
915 $conn = $this->reallyOpenConnection( $server, $dbName );
916 if ( !$conn->isOpen() ) {
917 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
918 $this->errorConnection
= $conn;
921 $conn->tablePrefix( $prefix );
922 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
923 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
927 // Increment reference count
928 if ( $conn instanceof IDatabase
) {
929 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
930 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
937 * Test if the specified index represents an open connection
939 * @param int $index Server index
943 private function isOpen( $index ) {
944 if ( !is_int( $index ) ) {
948 return (bool)$this->getAnyOpenConnection( $index );
952 * Really opens a connection. Uncached.
953 * Returns a Database object whether or not the connection was successful.
956 * @param array $server
957 * @param string|bool $dbNameOverride Use "" to not select any database
959 * @throws DBAccessError
960 * @throws InvalidArgumentException
962 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
963 if ( $this->disabled
) {
964 throw new DBAccessError();
967 if ( $dbNameOverride !== false ) {
968 $server['dbname'] = $dbNameOverride;
971 // Let the handle know what the cluster master is (e.g. "db1052")
972 $masterName = $this->getServerName( $this->getWriterIndex() );
973 $server['clusterMasterHost'] = $masterName;
975 // Log when many connection are made on requests
976 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
977 $this->perfLogger
->warning( __METHOD__
. ": " .
978 "{$this->connsOpened}+ connections made (master=$masterName)" );
981 $server['srvCache'] = $this->srvCache
;
982 // Set loggers and profilers
983 $server['connLogger'] = $this->connLogger
;
984 $server['queryLogger'] = $this->queryLogger
;
985 $server['errorLogger'] = $this->errorLogger
;
986 $server['profiler'] = $this->profiler
;
987 $server['trxProfiler'] = $this->trxProfiler
;
988 // Use the same agent and PHP mode for all DB handles
989 $server['cliMode'] = $this->cliMode
;
990 $server['agent'] = $this->agent
;
991 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
992 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
993 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
995 // Create a live connection object
997 $db = Database
::factory( $server['type'], $server );
998 } catch ( DBConnectionError
$e ) {
999 // FIXME: This is probably the ugliest thing I have ever done to
1000 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1004 $db->setLBInfo( $server );
1005 $db->setLazyMasterHandle(
1006 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1008 $db->setTableAliases( $this->tableAliases
);
1010 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1011 if ( $this->trxRoundId
!== false ) {
1012 $this->applyTransactionRoundFlags( $db );
1014 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1015 $db->setTransactionListener( $name, $callback );
1023 * @throws DBConnectionError
1025 private function reportConnectionError() {
1026 $conn = $this->errorConnection
; // the connection which caused the error
1028 'method' => __METHOD__
,
1029 'last_error' => $this->mLastError
,
1032 if ( $conn instanceof IDatabase
) {
1033 $context['db_server'] = $conn->getServer();
1034 $this->connLogger
->warning(
1035 "Connection error: {last_error} ({db_server})",
1039 // throws DBConnectionError
1040 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1042 // No last connection, probably due to all servers being too busy
1043 $this->connLogger
->error(
1044 "LB failure with no last connection. Connection error: {last_error}",
1048 // If all servers were busy, mLastError will contain something sensible
1049 throw new DBConnectionError( null, $this->mLastError
);
1053 public function getWriterIndex() {
1057 public function haveIndex( $i ) {
1058 return array_key_exists( $i, $this->mServers
);
1061 public function isNonZeroLoad( $i ) {
1062 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1065 public function getServerCount() {
1066 return count( $this->mServers
);
1069 public function getServerName( $i ) {
1070 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1071 $name = $this->mServers
[$i]['hostName'];
1072 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1073 $name = $this->mServers
[$i]['host'];
1078 return ( $name != '' ) ?
$name : 'localhost';
1081 public function getServerType( $i ) {
1082 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
1085 public function getMasterPos() {
1086 # If this entire request was served from a replica DB without opening a connection to the
1087 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1088 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1089 if ( !$masterConn ) {
1090 $serverCount = count( $this->mServers
);
1091 for ( $i = 1; $i < $serverCount; $i++
) {
1092 $conn = $this->getAnyOpenConnection( $i );
1094 return $conn->getReplicaPos();
1098 return $masterConn->getMasterPos();
1104 public function disable() {
1106 $this->disabled
= true;
1109 public function closeAll() {
1110 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1111 $host = $conn->getServer();
1112 $this->connLogger
->debug( "Closing connection to database '$host'." );
1117 self
::KEY_LOCAL
=> [],
1118 self
::KEY_FOREIGN_INUSE
=> [],
1119 self
::KEY_FOREIGN_FREE
=> [],
1120 self
::KEY_LOCAL_NOROUND
=> [],
1121 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1122 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1124 $this->connsOpened
= 0;
1127 public function closeConnection( IDatabase
$conn ) {
1128 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1129 foreach ( $this->mConns
as $type => $connsByServer ) {
1130 if ( !isset( $connsByServer[$serverIndex] ) ) {
1134 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1135 if ( $conn === $trackedConn ) {
1136 $host = $this->getServerName( $i );
1137 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1138 unset( $this->mConns
[$type][$serverIndex][$i] );
1139 --$this->connsOpened
;
1148 public function commitAll( $fname = __METHOD__
) {
1151 $restore = ( $this->trxRoundId
!== false );
1152 $this->trxRoundId
= false;
1153 $this->forEachOpenConnection(
1154 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1156 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1157 } catch ( DBError
$e ) {
1158 call_user_func( $this->errorLogger
, $e );
1159 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1161 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1162 $this->undoTransactionRoundFlags( $conn );
1168 throw new DBExpectedError(
1170 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1175 public function finalizeMasterChanges() {
1176 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1177 // Any error should cause all DB transactions to be rolled back together
1178 $conn->setTrxEndCallbackSuppression( false );
1179 $conn->runOnTransactionPreCommitCallbacks();
1180 // Defer post-commit callbacks until COMMIT finishes for all DBs
1181 $conn->setTrxEndCallbackSuppression( true );
1185 public function approveMasterChanges( array $options ) {
1186 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1187 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1188 // If atomic sections or explicit transactions are still open, some caller must have
1189 // caught an exception but failed to properly rollback any changes. Detect that and
1190 // throw and error (causing rollback).
1191 if ( $conn->explicitTrxActive() ) {
1192 throw new DBTransactionError(
1194 "Explicit transaction still active. A caller may have caught an error."
1197 // Assert that the time to replicate the transaction will be sane.
1198 // If this fails, then all DB transactions will be rollback back together.
1199 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1200 if ( $limit > 0 && $time > $limit ) {
1201 throw new DBTransactionSizeError(
1203 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1207 // If a connection sits idle while slow queries execute on another, that connection
1208 // may end up dropped before the commit round is reached. Ping servers to detect this.
1209 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1210 throw new DBTransactionError(
1212 "A connection to the {$conn->getDBname()} database was lost before commit."
1218 public function beginMasterChanges( $fname = __METHOD__
) {
1219 if ( $this->trxRoundId
!== false ) {
1220 throw new DBTransactionError(
1222 "$fname: Transaction round '{$this->trxRoundId}' already started."
1225 $this->trxRoundId
= $fname;
1228 $this->forEachOpenMasterConnection(
1229 function ( Database
$conn ) use ( $fname, &$failures ) {
1230 $conn->setTrxEndCallbackSuppression( true );
1232 $conn->flushSnapshot( $fname );
1233 } catch ( DBError
$e ) {
1234 call_user_func( $this->errorLogger
, $e );
1235 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1237 $conn->setTrxEndCallbackSuppression( false );
1238 $this->applyTransactionRoundFlags( $conn );
1243 throw new DBExpectedError(
1245 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1250 public function commitMasterChanges( $fname = __METHOD__
) {
1253 /** @noinspection PhpUnusedLocalVariableInspection */
1254 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1256 $restore = ( $this->trxRoundId
!== false );
1257 $this->trxRoundId
= false;
1258 $this->forEachOpenMasterConnection(
1259 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1261 if ( $conn->writesOrCallbacksPending() ) {
1262 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1263 } elseif ( $restore ) {
1264 $conn->flushSnapshot( $fname );
1266 } catch ( DBError
$e ) {
1267 call_user_func( $this->errorLogger
, $e );
1268 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1271 $this->undoTransactionRoundFlags( $conn );
1277 throw new DBExpectedError(
1279 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1284 public function runMasterPostTrxCallbacks( $type ) {
1285 $e = null; // first exception
1286 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1287 $conn->setTrxEndCallbackSuppression( false );
1288 if ( $conn->writesOrCallbacksPending() ) {
1289 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1290 // (which finished its callbacks already). Warn and recover in this case. Let the
1291 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1292 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1294 } elseif ( $conn->trxLevel() ) {
1295 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1296 // thus leaving an implicit read-only transaction open at this point. It
1297 // also happens if onTransactionIdle() callbacks leave implicit transactions
1298 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1299 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1303 $conn->runOnTransactionIdleCallbacks( $type );
1304 } catch ( Exception
$ex ) {
1308 $conn->runTransactionListenerCallbacks( $type );
1309 } catch ( Exception
$ex ) {
1317 public function rollbackMasterChanges( $fname = __METHOD__
) {
1318 $restore = ( $this->trxRoundId
!== false );
1319 $this->trxRoundId
= false;
1320 $this->forEachOpenMasterConnection(
1321 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1322 if ( $conn->writesOrCallbacksPending() ) {
1323 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1326 $this->undoTransactionRoundFlags( $conn );
1332 public function suppressTransactionEndCallbacks() {
1333 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1334 $conn->setTrxEndCallbackSuppression( true );
1339 * @param IDatabase $conn
1341 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1342 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1343 return; // transaction rounds do not apply to these connections
1346 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1347 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1348 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1349 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1350 // If config has explicitly requested DBO_TRX be either on or off by not
1351 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1352 // for things like blob stores (ExternalStore) which want auto-commit mode.
1357 * @param IDatabase $conn
1359 private function undoTransactionRoundFlags( 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 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1369 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1370 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1371 $conn->flushSnapshot( __METHOD__
);
1375 public function hasMasterConnection() {
1376 return $this->isOpen( $this->getWriterIndex() );
1379 public function hasMasterChanges() {
1381 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1382 $pending |
= $conn->writesOrCallbacksPending();
1385 return (bool)$pending;
1388 public function lastMasterChangeTimestamp() {
1390 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1391 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1397 public function hasOrMadeRecentMasterChanges( $age = null ) {
1398 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1400 return ( $this->hasMasterChanges()
1401 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1404 public function pendingMasterChangeCallers() {
1406 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1407 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1413 public function getLaggedReplicaMode( $domain = false ) {
1414 // No-op if there is only one DB (also avoids recursion)
1415 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1417 // See if laggedReplicaMode gets set
1418 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1419 $this->reuseConnection( $conn );
1420 } catch ( DBConnectionError
$e ) {
1421 // Avoid expensive re-connect attempts and failures
1422 $this->allReplicasDownMode
= true;
1423 $this->laggedReplicaMode
= true;
1427 return $this->laggedReplicaMode
;
1431 * @param bool $domain
1433 * @deprecated 1.28; use getLaggedReplicaMode()
1435 public function getLaggedSlaveMode( $domain = false ) {
1436 return $this->getLaggedReplicaMode( $domain );
1439 public function laggedReplicaUsed() {
1440 return $this->laggedReplicaMode
;
1446 * @deprecated Since 1.28; use laggedReplicaUsed()
1448 public function laggedSlaveUsed() {
1449 return $this->laggedReplicaUsed();
1452 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1453 if ( $this->readOnlyReason
!== false ) {
1454 return $this->readOnlyReason
;
1455 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1456 if ( $this->allReplicasDownMode
) {
1457 return 'The database has been automatically locked ' .
1458 'until the replica database servers become available';
1460 return 'The database has been automatically locked ' .
1461 'while the replica database servers catch up to the master.';
1463 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1464 return 'The database master is running in read-only mode.';
1471 * @param string $domain Domain ID, or false for the current domain
1472 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1475 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1476 $cache = $this->wanCache
;
1477 $masterServer = $this->getServerName( $this->getWriterIndex() );
1479 return (bool)$cache->getWithSetCallback(
1480 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1481 self
::TTL_CACHE_READONLY
,
1482 function () use ( $domain, $conn ) {
1483 $old = $this->trxProfiler
->setSilenced( true );
1485 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1486 $readOnly = (int)$dbw->serverIsReadOnly();
1488 $this->reuseConnection( $dbw );
1490 } catch ( DBError
$e ) {
1493 $this->trxProfiler
->setSilenced( $old );
1496 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1500 public function allowLagged( $mode = null ) {
1501 if ( $mode === null ) {
1502 return $this->mAllowLagged
;
1504 $this->mAllowLagged
= $mode;
1506 return $this->mAllowLagged
;
1509 public function pingAll() {
1511 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1512 if ( !$conn->ping() ) {
1520 public function forEachOpenConnection( $callback, array $params = [] ) {
1521 foreach ( $this->mConns
as $connsByServer ) {
1522 foreach ( $connsByServer as $serverConns ) {
1523 foreach ( $serverConns as $conn ) {
1524 $mergedParams = array_merge( [ $conn ], $params );
1525 call_user_func_array( $callback, $mergedParams );
1531 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1532 $masterIndex = $this->getWriterIndex();
1533 foreach ( $this->mConns
as $connsByServer ) {
1534 if ( isset( $connsByServer[$masterIndex] ) ) {
1535 /** @var IDatabase $conn */
1536 foreach ( $connsByServer[$masterIndex] as $conn ) {
1537 $mergedParams = array_merge( [ $conn ], $params );
1538 call_user_func_array( $callback, $mergedParams );
1544 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1545 foreach ( $this->mConns
as $connsByServer ) {
1546 foreach ( $connsByServer as $i => $serverConns ) {
1547 if ( $i === $this->getWriterIndex() ) {
1548 continue; // skip master
1550 foreach ( $serverConns as $conn ) {
1551 $mergedParams = array_merge( [ $conn ], $params );
1552 call_user_func_array( $callback, $mergedParams );
1558 public function getMaxLag( $domain = false ) {
1563 if ( $this->getServerCount() <= 1 ) {
1564 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1567 $lagTimes = $this->getLagTimes( $domain );
1568 foreach ( $lagTimes as $i => $lag ) {
1569 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1571 $host = $this->mServers
[$i]['host'];
1576 return [ $host, $maxLag, $maxIndex ];
1579 public function getLagTimes( $domain = false ) {
1580 if ( $this->getServerCount() <= 1 ) {
1581 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1584 $knownLagTimes = []; // map of (server index => 0 seconds)
1585 $indexesWithLag = [];
1586 foreach ( $this->mServers
as $i => $server ) {
1587 if ( empty( $server['is static'] ) ) {
1588 $indexesWithLag[] = $i; // DB server might have replication lag
1590 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1594 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1597 public function safeGetLag( IDatabase
$conn ) {
1598 if ( $this->getServerCount() <= 1 ) {
1601 return $conn->getLag();
1606 * @param IDatabase $conn
1607 * @param DBMasterPos|bool $pos
1608 * @param int $timeout
1611 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1612 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1613 return true; // server is not a replica DB
1617 // Get the current master position, opening a connection if needed
1618 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1619 if ( $masterConn ) {
1620 $pos = $masterConn->getMasterPos();
1622 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1623 $pos = $masterConn->getMasterPos();
1624 $this->closeConnection( $masterConn );
1628 if ( $pos instanceof DBMasterPos
) {
1629 $result = $conn->masterPosWait( $pos, $timeout );
1630 if ( $result == -1 ||
is_null( $result ) ) {
1631 $msg = __METHOD__
. ': Timed out waiting on {host} pos {pos}';
1632 $this->replLogger
->warning( $msg,
1633 [ 'host' => $conn->getServer(), 'pos' => $pos ] );
1636 $this->replLogger
->info( __METHOD__
. ': Done' );
1640 $ok = false; // something is misconfigured
1641 $this->replLogger
->error( 'Could not get master pos for {host}',
1642 [ 'host' => $conn->getServer() ] );
1648 public function setTransactionListener( $name, callable
$callback = null ) {
1650 $this->trxRecurringCallbacks
[$name] = $callback;
1652 unset( $this->trxRecurringCallbacks
[$name] );
1654 $this->forEachOpenMasterConnection(
1655 function ( IDatabase
$conn ) use ( $name, $callback ) {
1656 $conn->setTransactionListener( $name, $callback );
1661 public function setTableAliases( array $aliases ) {
1662 $this->tableAliases
= $aliases;
1665 public function setDomainPrefix( $prefix ) {
1666 // Find connections to explicit foreign domains still marked as in-use...
1668 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1669 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1670 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1671 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1672 $domainsInUse[] = $conn->getDomainID();
1676 // Do not switch connections to explicit foreign domains unless marked as safe
1677 if ( $domainsInUse ) {
1678 $domains = implode( ', ', $domainsInUse );
1679 throw new DBUnexpectedError( null,
1680 "Foreign domain connections are still in use ($domains)." );
1683 $this->localDomain
= new DatabaseDomain(
1684 $this->localDomain
->getDatabase(),
1689 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1690 $db->tablePrefix( $prefix );
1695 * Make PHP ignore user aborts/disconnects until the returned
1696 * value leaves scope. This returns null and does nothing in CLI mode.
1698 * @return ScopedCallback|null
1700 final protected function getScopedPHPBehaviorForCommit() {
1701 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1702 $old = ignore_user_abort( true ); // avoid half-finished operations
1703 return new ScopedCallback( function () use ( $old ) {
1704 ignore_user_abort( $old );
1711 function __destruct() {
1712 // Avoid connection leaks for sanity
1717 class_alias( LoadBalancer
::class, 'LoadBalancer' );