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 the local (and default) database domain ID of connection handles
248 * @see DatabaseDomain
249 * @return string Database domain ID; this specifies DB name, schema, and table prefix
252 public function getLocalDomainID() {
253 return $this->localDomain
->getId();
257 * Get a LoadMonitor instance
259 * @return ILoadMonitor
261 private function getLoadMonitor() {
262 if ( !isset( $this->loadMonitor
) ) {
264 'LoadMonitor' => LoadMonitor
::class,
265 'LoadMonitorNull' => LoadMonitorNull
::class,
266 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
269 $class = $this->loadMonitorConfig
['class'];
270 if ( isset( $compat[$class] ) ) {
271 $class = $compat[$class];
274 $this->loadMonitor
= new $class(
275 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
276 $this->loadMonitor
->setLogger( $this->replLogger
);
279 return $this->loadMonitor
;
283 * @param array $loads
284 * @param bool|string $domain Domain to get non-lagged for
285 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
286 * @return bool|int|string
288 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
289 $lags = $this->getLagTimes( $domain );
291 # Unset excessively lagged servers
292 foreach ( $lags as $i => $lag ) {
294 # How much lag this server nominally is allowed to have
295 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
296 ?
$this->mServers
[$i]['max lag']
297 : $this->maxLag
; // default
298 # Constrain that futher by $maxLag argument
299 $maxServerLag = min( $maxServerLag, $maxLag );
301 $host = $this->getServerName( $i );
302 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
303 $this->replLogger
->error(
304 "Server {host} is not replicating?", [ 'host' => $host ] );
306 } elseif ( $lag > $maxServerLag ) {
307 $this->replLogger
->info(
308 "Server {host} has {lag} seconds of lag (>= {maxlag})",
309 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
316 # Find out if all the replica DBs with non-zero load are lagged
318 foreach ( $loads as $load ) {
322 # No appropriate DB servers except maybe the master and some replica DBs with zero load
323 # Do NOT use the master
324 # Instead, this function will return false, triggering read-only mode,
325 # and a lagged replica DB will be used instead.
329 if ( count( $loads ) == 0 ) {
333 # Return a random representative of the remainder
334 return ArrayUtils
::pickRandom( $loads );
337 public function getReaderIndex( $group = false, $domain = false ) {
338 if ( count( $this->mServers
) == 1 ) {
339 // Skip the load balancing if there's only one server
340 return $this->getWriterIndex();
341 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
342 // Shortcut if the generic reader index was already cached
343 return $this->mReadIndex
;
346 if ( $group !== false ) {
347 // Use the server weight array for this load group
348 if ( isset( $this->mGroupLoads
[$group] ) ) {
349 $loads = $this->mGroupLoads
[$group];
351 // No loads for this group, return false and the caller can use some other group
352 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
357 // Use the generic load group
358 $loads = $this->mLoads
;
361 // Scale the configured load ratios according to each server's load and state
362 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
364 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
365 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
366 if ( $i === false ) {
367 // Replica DB connection unsuccessful
371 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
372 // Before any data queries are run, wait for the server to catch up to the
373 // specified position. This is used to improve session consistency. Note that
374 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
375 // so update laggedReplicaMode as needed for consistency.
376 if ( !$this->doWait( $i ) ) {
377 $laggedReplicaMode = true;
381 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
382 // Cache the generic reader index for future ungrouped DB_REPLICA handles
383 $this->mReadIndex
= $i;
384 // Record if the generic reader index is in "lagged replica DB" mode
385 if ( $laggedReplicaMode ) {
386 $this->laggedReplicaMode
= true;
390 $serverName = $this->getServerName( $i );
391 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
397 * @param array $loads List of server weights
398 * @param string|bool $domain
399 * @return array (reader index, lagged replica mode) or false on failure
401 private function pickReaderIndex( array $loads, $domain = false ) {
402 if ( !count( $loads ) ) {
403 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
406 /** @var int|bool $i Index of selected server */
408 /** @var bool $laggedReplicaMode Whether server is considered lagged */
409 $laggedReplicaMode = false;
411 // Quickly look through the available servers for a server that meets criteria...
412 $currentLoads = $loads;
413 while ( count( $currentLoads ) ) {
414 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
415 $i = ArrayUtils
::pickRandom( $currentLoads );
418 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
419 // ChronologyProtecter sets mWaitForPos for session consistency.
420 // This triggers doWait() after connect, so it's especially good to
421 // avoid lagged servers so as to avoid excessive delay in that method.
422 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
423 // Aim for <= 1 second of waiting (being too picky can backfire)
424 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
426 if ( $i === false ) {
427 // Any server with less lag than it's 'max lag' param is preferable
428 $i = $this->getRandomNonLagged( $currentLoads, $domain );
430 if ( $i === false && count( $currentLoads ) != 0 ) {
431 // All replica DBs lagged. Switch to read-only mode
432 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
433 $i = ArrayUtils
::pickRandom( $currentLoads );
434 $laggedReplicaMode = true;
438 if ( $i === false ) {
439 // pickRandom() returned false.
440 // This is permanent and means the configuration or the load monitor
441 // wants us to return false.
442 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
444 return [ false, false ];
447 $serverName = $this->getServerName( $i );
448 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
450 $conn = $this->openConnection( $i, $domain );
452 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
453 unset( $currentLoads[$i] ); // avoid this server next iteration
458 // Decrement reference counter, we are finished with this connection.
459 // It will be incremented for the caller later.
460 if ( $domain !== false ) {
461 $this->reuseConnection( $conn );
464 // Return this server
468 // If all servers were down, quit now
469 if ( !count( $currentLoads ) ) {
470 $this->connLogger
->error( "All servers down" );
473 return [ $i, $laggedReplicaMode ];
476 public function waitFor( $pos ) {
477 $oldPos = $this->mWaitForPos
;
479 $this->mWaitForPos
= $pos;
480 // If a generic reader connection was already established, then wait now
481 $i = $this->mReadIndex
;
483 if ( !$this->doWait( $i ) ) {
484 $this->laggedReplicaMode
= true;
488 // Restore the older position if it was higher since this is used for lag-protection
489 $this->setWaitForPositionIfHigher( $oldPos );
493 public function waitForOne( $pos, $timeout = null ) {
494 $oldPos = $this->mWaitForPos
;
496 $this->mWaitForPos
= $pos;
498 $i = $this->mReadIndex
;
500 // Pick a generic replica DB if there isn't one yet
501 $readLoads = $this->mLoads
;
502 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
503 $readLoads = array_filter( $readLoads ); // with non-zero load
504 $i = ArrayUtils
::pickRandom( $readLoads );
508 $ok = $this->doWait( $i, true, $timeout );
510 $ok = true; // no applicable loads
513 # Restore the old position, as this is not used for lag-protection but for throttling
514 $this->mWaitForPos
= $oldPos;
520 public function waitForAll( $pos, $timeout = null ) {
521 $timeout = $timeout ?
: $this->mWaitTimeout
;
523 $oldPos = $this->mWaitForPos
;
525 $this->mWaitForPos
= $pos;
526 $serverCount = count( $this->mServers
);
529 for ( $i = 1; $i < $serverCount; $i++
) {
530 if ( $this->mLoads
[$i] > 0 ) {
531 $start = microtime( true );
532 $ok = $this->doWait( $i, true, max( 1, (int)$timeout ) ) && $ok;
533 $timeout -= ( microtime( true ) - $start );
534 if ( $timeout <= 0 ) {
535 break; // timeout reached
540 # Restore the old position, as this is not used for lag-protection but for throttling
541 $this->mWaitForPos
= $oldPos;
548 * @param DBMasterPos|bool $pos
550 private function setWaitForPositionIfHigher( $pos ) {
555 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
556 $this->mWaitForPos
= $pos;
562 * @return IDatabase|bool
564 public function getAnyOpenConnection( $i ) {
565 foreach ( $this->mConns
as $connsByServer ) {
566 if ( !empty( $connsByServer[$i] ) ) {
567 /** @var IDatabase[] $serverConns */
568 $serverConns = $connsByServer[$i];
570 return reset( $serverConns );
578 * Wait for a given replica DB to catch up to the master pos stored in $this
579 * @param int $index Server index
580 * @param bool $open Check the server even if a new connection has to be made
581 * @param int $timeout Max seconds to wait; default is mWaitTimeout
584 protected function doWait( $index, $open = false, $timeout = null ) {
585 $close = false; // close the connection afterwards
587 // Check if we already know that the DB has reached this point
588 $server = $this->getServerName( $index );
589 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
590 /** @var DBMasterPos $knownReachedPos */
591 $knownReachedPos = $this->srvCache
->get( $key );
593 $knownReachedPos instanceof DBMasterPos
&&
594 $knownReachedPos->hasReached( $this->mWaitForPos
)
596 $this->replLogger
->debug( __METHOD__
.
597 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
598 [ 'dbserver' => $server ] );
602 // Find a connection to wait on, creating one if needed and allowed
603 $conn = $this->getAnyOpenConnection( $index );
606 $this->replLogger
->debug( __METHOD__
. ': no connection open for {dbserver}',
607 [ 'dbserver' => $server ] );
611 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
613 $this->replLogger
->warning( __METHOD__
. ': failed to connect to {dbserver}',
614 [ 'dbserver' => $server ] );
618 // Avoid connection spam in waitForAll() when connections
619 // are made just for the sake of doing this lag check.
624 $this->replLogger
->info( __METHOD__
. ': Waiting for replica DB {dbserver} to catch up...',
625 [ 'dbserver' => $server ] );
626 $timeout = $timeout ?
: $this->mWaitTimeout
;
627 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
629 if ( $result == -1 ||
is_null( $result ) ) {
630 // Timed out waiting for replica DB, use master instead
631 $this->replLogger
->warning(
632 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
633 [ 'host' => $server, 'pos' => $this->mWaitForPos
]
637 $this->replLogger
->info( __METHOD__
. ": Done" );
639 // Remember that the DB reached this point
640 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
644 $this->closeConnection( $conn );
650 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
651 if ( $i === null ||
$i === false ) {
652 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
653 ' with invalid server index' );
656 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
657 $domain = false; // local connection requested
660 $groups = ( $groups === false ||
$groups === [] )
661 ?
[ false ] // check one "group": the generic pool
664 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
665 $oldConnsOpened = $this->connsOpened
; // connections open now
667 if ( $i == self
::DB_MASTER
) {
668 $i = $this->getWriterIndex();
670 # Try to find an available server in any the query groups (in order)
671 foreach ( $groups as $group ) {
672 $groupIndex = $this->getReaderIndex( $group, $domain );
673 if ( $groupIndex !== false ) {
680 # Operation-based index
681 if ( $i == self
::DB_REPLICA
) {
682 $this->mLastError
= 'Unknown error'; // reset error string
683 # Try the general server pool if $groups are unavailable.
684 $i = ( $groups === [ false ] )
685 ?
false // don't bother with this if that is what was tried above
686 : $this->getReaderIndex( false, $domain );
687 # Couldn't find a working server in getReaderIndex()?
688 if ( $i === false ) {
689 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
690 // Throw an exception
691 $this->reportConnectionError();
692 return null; // not reached
696 # Now we have an explicit index into the servers array
697 $conn = $this->openConnection( $i, $domain, $flags );
699 // Throw an exception
700 $this->reportConnectionError();
701 return null; // not reached
704 # Profile any new connections that happen
705 if ( $this->connsOpened
> $oldConnsOpened ) {
706 $host = $conn->getServer();
707 $dbname = $conn->getDBname();
708 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
712 # Make master-requested DB handles inherit any read-only mode setting
713 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
719 public function reuseConnection( $conn ) {
720 $serverIndex = $conn->getLBInfo( 'serverIndex' );
721 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
722 if ( $serverIndex === null ||
$refCount === null ) {
724 * This can happen in code like:
725 * foreach ( $dbs as $db ) {
726 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
728 * $lb->reuseConnection( $conn );
730 * When a connection to the local DB is opened in this way, reuseConnection()
734 } elseif ( $conn instanceof DBConnRef
) {
735 // DBConnRef already handles calling reuseConnection() and only passes the live
736 // Database instance to this method. Any caller passing in a DBConnRef is broken.
737 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
738 ( new RuntimeException() )->getTraceAsString() );
743 if ( $this->disabled
) {
744 return; // DBConnRef handle probably survived longer than the LoadBalancer
747 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
748 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
749 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
751 $connFreeKey = self
::KEY_FOREIGN_FREE
;
752 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
755 $domain = $conn->getDomainID();
756 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
757 throw new InvalidArgumentException( __METHOD__
.
758 ": connection $serverIndex/$domain not found; it may have already been freed." );
759 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
760 throw new InvalidArgumentException( __METHOD__
.
761 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
764 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
765 if ( $refCount <= 0 ) {
766 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
767 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
768 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
769 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
771 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
773 $this->connLogger
->debug( __METHOD__
.
774 ": reference count for $serverIndex/$domain reduced to $refCount" );
778 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
779 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
781 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
784 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
785 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
787 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
790 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
791 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
793 return new MaintainableDBConnRef(
794 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
797 public function openConnection( $i, $domain = false, $flags = 0 ) {
798 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
799 $domain = false; // local connection requested
802 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
803 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
804 // Load CP positions before connecting so that doWait() triggers later if needed
805 $this->chronProtInitialized
= true;
806 $this->chronProt
->initLB( $this );
809 // Check if an auto-commit connection is being requested. If so, it will not reuse the
810 // main set of DB connections but rather its own pool since:
811 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
812 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
813 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
815 if ( $domain !== false ) {
816 // Connection is to a foreign domain
817 $conn = $this->openForeignConnection( $i, $domain, $flags );
819 // Connection is to the local domain
820 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
821 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
822 $conn = $this->mConns
[$connKey][$i][0];
824 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
825 throw new InvalidArgumentException( "No server with index '$i'." );
827 // Open a new connection
828 $server = $this->mServers
[$i];
829 $server['serverIndex'] = $i;
830 $server['autoCommitOnly'] = $autoCommit;
831 $conn = $this->reallyOpenConnection( $server, false );
832 $host = $this->getServerName( $i );
833 if ( $conn->isOpen() ) {
834 $this->connLogger
->debug( "Connected to database $i at '$host'." );
835 $this->mConns
[$connKey][$i][0] = $conn;
837 $this->connLogger
->warning( "Failed to connect to database $i at '$host'." );
838 $this->errorConnection
= $conn;
844 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
845 // Connection was made but later unrecoverably lost for some reason.
846 // Do not return a handle that will just throw exceptions on use,
847 // but let the calling code (e.g. getReaderIndex) try another server.
848 // See DatabaseMyslBase::ping() for how this can happen.
849 $this->errorConnection
= $conn;
853 if ( $autoCommit && $conn instanceof IDatabase
) {
854 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
861 * Open a connection to a foreign DB, or return one if it is already open.
863 * Increments a reference count on the returned connection which locks the
864 * connection to the requested domain. This reference count can be
865 * decremented by calling reuseConnection().
867 * If a connection is open to the appropriate server already, but with the wrong
868 * database, it will be switched to the right database and returned, as long as
869 * it has been freed first with reuseConnection().
871 * On error, returns false, and the connection which caused the
872 * error will be available via $this->errorConnection.
874 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
876 * @param int $i Server index
877 * @param string $domain Domain ID to open
878 * @param int $flags Class CONN_* constant bitfield
881 private function openForeignConnection( $i, $domain, $flags = 0 ) {
882 $domainInstance = DatabaseDomain
::newFromId( $domain );
883 $dbName = $domainInstance->getDatabase();
884 $prefix = $domainInstance->getTablePrefix();
885 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
888 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
889 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
891 $connFreeKey = self
::KEY_FOREIGN_FREE
;
892 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
895 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
896 // Reuse an in-use connection for the same domain
897 $conn = $this->mConns
[$connInUseKey][$i][$domain];
898 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
899 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
900 // Reuse a free connection for the same domain
901 $conn = $this->mConns
[$connFreeKey][$i][$domain];
902 unset( $this->mConns
[$connFreeKey][$i][$domain] );
903 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
904 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
905 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
906 // Reuse a free connection from another domain
907 $conn = reset( $this->mConns
[$connFreeKey][$i] );
908 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
909 // The empty string as a DB name means "don't care".
910 // DatabaseMysqlBase::open() already handle this on connection.
911 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
912 $this->mLastError
= "Error selecting database '$dbName' on server " .
913 $conn->getServer() . " from client host {$this->host}";
914 $this->errorConnection
= $conn;
917 $conn->tablePrefix( $prefix );
918 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
919 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
920 $this->connLogger
->debug( __METHOD__
.
921 ": reusing free connection from $oldDomain for $domain" );
924 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
925 throw new InvalidArgumentException( "No server with index '$i'." );
927 // Open a new connection
928 $server = $this->mServers
[$i];
929 $server['serverIndex'] = $i;
930 $server['foreignPoolRefCount'] = 0;
931 $server['foreign'] = true;
932 $server['autoCommitOnly'] = $autoCommit;
933 $conn = $this->reallyOpenConnection( $server, $dbName );
934 if ( !$conn->isOpen() ) {
935 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
936 $this->errorConnection
= $conn;
939 $conn->tablePrefix( $prefix );
940 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
941 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
945 // Increment reference count
946 if ( $conn instanceof IDatabase
) {
947 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
948 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
955 * Test if the specified index represents an open connection
957 * @param int $index Server index
961 private function isOpen( $index ) {
962 if ( !is_int( $index ) ) {
966 return (bool)$this->getAnyOpenConnection( $index );
970 * Really opens a connection. Uncached.
971 * Returns a Database object whether or not the connection was successful.
974 * @param array $server
975 * @param string|bool $dbNameOverride Use "" to not select any database
977 * @throws DBAccessError
978 * @throws InvalidArgumentException
980 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
981 if ( $this->disabled
) {
982 throw new DBAccessError();
985 if ( $dbNameOverride !== false ) {
986 $server['dbname'] = $dbNameOverride;
989 // Let the handle know what the cluster master is (e.g. "db1052")
990 $masterName = $this->getServerName( $this->getWriterIndex() );
991 $server['clusterMasterHost'] = $masterName;
993 // Log when many connection are made on requests
994 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
995 $this->perfLogger
->warning( __METHOD__
. ": " .
996 "{$this->connsOpened}+ connections made (master=$masterName)" );
999 $server['srvCache'] = $this->srvCache
;
1000 // Set loggers and profilers
1001 $server['connLogger'] = $this->connLogger
;
1002 $server['queryLogger'] = $this->queryLogger
;
1003 $server['errorLogger'] = $this->errorLogger
;
1004 $server['profiler'] = $this->profiler
;
1005 $server['trxProfiler'] = $this->trxProfiler
;
1006 // Use the same agent and PHP mode for all DB handles
1007 $server['cliMode'] = $this->cliMode
;
1008 $server['agent'] = $this->agent
;
1009 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1010 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1011 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1013 // Create a live connection object
1015 $db = Database
::factory( $server['type'], $server );
1016 } catch ( DBConnectionError
$e ) {
1017 // FIXME: This is probably the ugliest thing I have ever done to
1018 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1022 $db->setLBInfo( $server );
1023 $db->setLazyMasterHandle(
1024 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1026 $db->setTableAliases( $this->tableAliases
);
1028 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1029 if ( $this->trxRoundId
!== false ) {
1030 $this->applyTransactionRoundFlags( $db );
1032 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1033 $db->setTransactionListener( $name, $callback );
1041 * @throws DBConnectionError
1043 private function reportConnectionError() {
1044 $conn = $this->errorConnection
; // the connection which caused the error
1046 'method' => __METHOD__
,
1047 'last_error' => $this->mLastError
,
1050 if ( $conn instanceof IDatabase
) {
1051 $context['db_server'] = $conn->getServer();
1052 $this->connLogger
->warning(
1053 "Connection error: {last_error} ({db_server})",
1057 // throws DBConnectionError
1058 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1060 // No last connection, probably due to all servers being too busy
1061 $this->connLogger
->error(
1062 "LB failure with no last connection. Connection error: {last_error}",
1066 // If all servers were busy, mLastError will contain something sensible
1067 throw new DBConnectionError( null, $this->mLastError
);
1071 public function getWriterIndex() {
1075 public function haveIndex( $i ) {
1076 return array_key_exists( $i, $this->mServers
);
1079 public function isNonZeroLoad( $i ) {
1080 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1083 public function getServerCount() {
1084 return count( $this->mServers
);
1087 public function getServerName( $i ) {
1088 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1089 $name = $this->mServers
[$i]['hostName'];
1090 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1091 $name = $this->mServers
[$i]['host'];
1096 return ( $name != '' ) ?
$name : 'localhost';
1099 public function getServerType( $i ) {
1100 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
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' );