3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use InvalidArgumentException
;
36 * Database connection, tracking, load balancing, and transaction manager for a cluster
40 class LoadBalancer
implements ILoadBalancer
{
41 /** @var array[] Map of (server index => server config array) */
43 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
45 /** @var float[] Map of (server index => weight) */
47 /** @var array[] Map of (group => server index => weight) */
49 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
50 private $mAllowLagged;
51 /** @var int Seconds to spend waiting on replica DB lag to resolve */
52 private $mWaitTimeout;
53 /** @var array The LoadMonitor configuration */
54 private $loadMonitorConfig;
55 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
56 private $tableAliases = [];
58 /** @var ILoadMonitor */
60 /** @var ChronologyProtector|null */
64 /** @var WANObjectCache */
66 /** @var object|string Class name or object With profileIn/profileOut methods */
68 /** @var TransactionProfiler */
69 protected $trxProfiler;
70 /** @var LoggerInterface */
71 protected $replLogger;
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var LoggerInterface */
77 protected $perfLogger;
79 /** @var Database DB connection object that caused a problem */
80 private $errorConnection;
81 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
83 /** @var bool|DBMasterPos False if not set */
85 /** @var bool Whether the generic reader fell back to a lagged replica DB */
86 private $laggedReplicaMode = false;
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $allReplicasDownMode = false;
89 /** @var string The last DB selection or connection error */
90 private $mLastError = 'Unknown error';
91 /** @var string|bool Reason the LB is read-only or false if not */
92 private $readOnlyReason = false;
93 /** @var int Total connections opened */
94 private $connsOpened = 0;
95 /** @var string|bool String if a requested DBO_TRX transaction round is active */
96 private $trxRoundId = false;
97 /** @var array[] Map of (name => callable) */
98 private $trxRecurringCallbacks = [];
99 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
100 private $localDomain;
101 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
102 private $localDomainIdAlias;
103 /** @var string Current server name */
105 /** @var bool Whether this PHP instance is for a CLI script */
107 /** @var string Agent name for query profiling */
110 /** @var callable Exception logger */
111 private $errorLogger;
114 private $disabled = false;
116 private $chronProtInitialized = false;
118 private $maxLag = self
::MAX_LAG_DEFAULT
;
120 /** @var int Warn when this many connection are held */
121 const CONN_HELD_WARN_THRESHOLD
= 10;
123 /** @var int Default 'maxLag' when unspecified */
124 const MAX_LAG_DEFAULT
= 10;
125 /** @var int Seconds to cache master server read-only status */
126 const TTL_CACHE_READONLY
= 5;
128 const KEY_LOCAL
= 'local';
129 const KEY_FOREIGN_FREE
= 'foreignFree';
130 const KEY_FOREIGN_INUSE
= 'foreignInUse';
132 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
133 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
134 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
136 public function __construct( array $params ) {
137 if ( !isset( $params['servers'] ) ) {
138 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
140 $this->mServers
= $params['servers'];
141 foreach ( $this->mServers
as $i => $server ) {
143 $this->mServers
[$i]['master'] = true;
145 $this->mServers
[$i]['replica'] = true;
149 $this->localDomain
= isset( $params['localDomain'] )
150 ? DatabaseDomain
::newFromId( $params['localDomain'] )
151 : DatabaseDomain
::newUnspecified();
152 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
153 // always true, gracefully handle the case when they fail to account for escaping.
154 if ( $this->localDomain
->getTablePrefix() != '' ) {
155 $this->localDomainIdAlias
=
156 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
158 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
161 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
163 $this->mReadIndex
= -1;
165 // Connection were transaction rounds may be applied
166 self
::KEY_LOCAL
=> [],
167 self
::KEY_FOREIGN_INUSE
=> [],
168 self
::KEY_FOREIGN_FREE
=> [],
169 // Auto-committing counterpart connections that ignore transaction rounds
170 self
::KEY_LOCAL_NOROUND
=> [],
171 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
172 self
::KEY_FOREIGN_FREE_NOROUND
=> []
175 $this->mWaitForPos
= false;
176 $this->mAllowLagged
= false;
178 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
179 $this->readOnlyReason
= $params['readOnlyReason'];
182 if ( isset( $params['maxLag'] ) ) {
183 $this->maxLag
= $params['maxLag'];
186 if ( isset( $params['loadMonitor'] ) ) {
187 $this->loadMonitorConfig
= $params['loadMonitor'];
189 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
191 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
193 foreach ( $params['servers'] as $i => $server ) {
194 $this->mLoads
[$i] = $server['load'];
195 if ( isset( $server['groupLoads'] ) ) {
196 foreach ( $server['groupLoads'] as $group => $ratio ) {
197 if ( !isset( $this->mGroupLoads
[$group] ) ) {
198 $this->mGroupLoads
[$group] = [];
200 $this->mGroupLoads
[$group][$i] = $ratio;
205 if ( isset( $params['srvCache'] ) ) {
206 $this->srvCache
= $params['srvCache'];
208 $this->srvCache
= new EmptyBagOStuff();
210 if ( isset( $params['wanCache'] ) ) {
211 $this->wanCache
= $params['wanCache'];
213 $this->wanCache
= WANObjectCache
::newEmpty();
215 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
216 if ( isset( $params['trxProfiler'] ) ) {
217 $this->trxProfiler
= $params['trxProfiler'];
219 $this->trxProfiler
= new TransactionProfiler();
222 $this->errorLogger
= isset( $params['errorLogger'] )
223 ?
$params['errorLogger']
224 : function ( Exception
$e ) {
225 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
228 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
229 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
232 $this->host
= isset( $params['hostname'] )
233 ?
$params['hostname']
234 : ( gethostname() ?
: 'unknown' );
235 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
236 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
238 if ( isset( $params['chronologyProtector'] ) ) {
239 $this->chronProt
= $params['chronologyProtector'];
244 * Get a LoadMonitor instance
246 * @return ILoadMonitor
248 private function getLoadMonitor() {
249 if ( !isset( $this->loadMonitor
) ) {
251 'LoadMonitor' => LoadMonitor
::class,
252 'LoadMonitorNull' => LoadMonitorNull
::class,
253 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
256 $class = $this->loadMonitorConfig
['class'];
257 if ( isset( $compat[$class] ) ) {
258 $class = $compat[$class];
261 $this->loadMonitor
= new $class(
262 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
263 $this->loadMonitor
->setLogger( $this->replLogger
);
266 return $this->loadMonitor
;
270 * @param array $loads
271 * @param bool|string $domain Domain to get non-lagged for
272 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
273 * @return bool|int|string
275 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
276 $lags = $this->getLagTimes( $domain );
278 # Unset excessively lagged servers
279 foreach ( $lags as $i => $lag ) {
281 # How much lag this server nominally is allowed to have
282 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
283 ?
$this->mServers
[$i]['max lag']
284 : $this->maxLag
; // default
285 # Constrain that futher by $maxLag argument
286 $maxServerLag = min( $maxServerLag, $maxLag );
288 $host = $this->getServerName( $i );
289 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
290 $this->replLogger
->error(
291 "Server {host} is not replicating?", [ 'host' => $host ] );
293 } elseif ( $lag > $maxServerLag ) {
294 $this->replLogger
->info(
295 "Server {host} has {lag} seconds of lag (>= {maxlag})",
296 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
303 # Find out if all the replica DBs with non-zero load are lagged
305 foreach ( $loads as $load ) {
309 # No appropriate DB servers except maybe the master and some replica DBs with zero load
310 # Do NOT use the master
311 # Instead, this function will return false, triggering read-only mode,
312 # and a lagged replica DB will be used instead.
316 if ( count( $loads ) == 0 ) {
320 # Return a random representative of the remainder
321 return ArrayUtils
::pickRandom( $loads );
324 public function getReaderIndex( $group = false, $domain = false ) {
325 if ( count( $this->mServers
) == 1 ) {
326 // Skip the load balancing if there's only one server
327 return $this->getWriterIndex();
328 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
329 // Shortcut if the generic reader index was already cached
330 return $this->mReadIndex
;
333 if ( $group !== false ) {
334 // Use the server weight array for this load group
335 if ( isset( $this->mGroupLoads
[$group] ) ) {
336 $loads = $this->mGroupLoads
[$group];
338 // No loads for this group, return false and the caller can use some other group
339 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
344 // Use the generic load group
345 $loads = $this->mLoads
;
348 // Scale the configured load ratios according to each server's load and state
349 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
351 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
352 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
353 if ( $i === false ) {
354 // Replica DB connection unsuccessful
358 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
359 // Before any data queries are run, wait for the server to catch up to the
360 // specified position. This is used to improve session consistency. Note that
361 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
362 // so update laggedReplicaMode as needed for consistency.
363 if ( !$this->doWait( $i ) ) {
364 $laggedReplicaMode = true;
368 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
369 // Cache the generic reader index for future ungrouped DB_REPLICA handles
370 $this->mReadIndex
= $i;
371 // Record if the generic reader index is in "lagged replica DB" mode
372 if ( $laggedReplicaMode ) {
373 $this->laggedReplicaMode
= true;
377 $serverName = $this->getServerName( $i );
378 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
384 * @param array $loads List of server weights
385 * @param string|bool $domain
386 * @return array (reader index, lagged replica mode) or false on failure
388 private function pickReaderIndex( array $loads, $domain = false ) {
389 if ( !count( $loads ) ) {
390 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
393 /** @var int|bool $i Index of selected server */
395 /** @var bool $laggedReplicaMode Whether server is considered lagged */
396 $laggedReplicaMode = false;
398 // Quickly look through the available servers for a server that meets criteria...
399 $currentLoads = $loads;
400 while ( count( $currentLoads ) ) {
401 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
402 $i = ArrayUtils
::pickRandom( $currentLoads );
405 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
406 // ChronologyProtecter sets mWaitForPos for session consistency.
407 // This triggers doWait() after connect, so it's especially good to
408 // avoid lagged servers so as to avoid excessive delay in that method.
409 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
410 // Aim for <= 1 second of waiting (being too picky can backfire)
411 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
413 if ( $i === false ) {
414 // Any server with less lag than it's 'max lag' param is preferable
415 $i = $this->getRandomNonLagged( $currentLoads, $domain );
417 if ( $i === false && count( $currentLoads ) != 0 ) {
418 // All replica DBs lagged. Switch to read-only mode
419 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
420 $i = ArrayUtils
::pickRandom( $currentLoads );
421 $laggedReplicaMode = true;
425 if ( $i === false ) {
426 // pickRandom() returned false.
427 // This is permanent and means the configuration or the load monitor
428 // wants us to return false.
429 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
431 return [ false, false ];
434 $serverName = $this->getServerName( $i );
435 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
437 $conn = $this->openConnection( $i, $domain );
439 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
440 unset( $currentLoads[$i] ); // avoid this server next iteration
445 // Decrement reference counter, we are finished with this connection.
446 // It will be incremented for the caller later.
447 if ( $domain !== false ) {
448 $this->reuseConnection( $conn );
451 // Return this server
455 // If all servers were down, quit now
456 if ( !count( $currentLoads ) ) {
457 $this->connLogger
->error( "All servers down" );
460 return [ $i, $laggedReplicaMode ];
463 public function waitFor( $pos ) {
464 $oldPos = $this->mWaitForPos
;
466 $this->mWaitForPos
= $pos;
467 // If a generic reader connection was already established, then wait now
468 $i = $this->mReadIndex
;
470 if ( !$this->doWait( $i ) ) {
471 $this->laggedReplicaMode
= true;
475 // Restore the older position if it was higher since this is used for lag-protection
476 $this->setWaitForPositionIfHigher( $oldPos );
480 public function waitForOne( $pos, $timeout = null ) {
481 $oldPos = $this->mWaitForPos
;
483 $this->mWaitForPos
= $pos;
485 $i = $this->mReadIndex
;
487 // Pick a generic replica DB if there isn't one yet
488 $readLoads = $this->mLoads
;
489 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
490 $readLoads = array_filter( $readLoads ); // with non-zero load
491 $i = ArrayUtils
::pickRandom( $readLoads );
495 $ok = $this->doWait( $i, true, $timeout );
497 $ok = true; // no applicable loads
500 # Restore the old position, as this is not used for lag-protection but for throttling
501 $this->mWaitForPos
= $oldPos;
507 public function waitForAll( $pos, $timeout = null ) {
508 $oldPos = $this->mWaitForPos
;
510 $this->mWaitForPos
= $pos;
511 $serverCount = count( $this->mServers
);
514 for ( $i = 1; $i < $serverCount; $i++
) {
515 if ( $this->mLoads
[$i] > 0 ) {
516 $ok = $this->doWait( $i, true, $timeout ) && $ok;
520 # Restore the old position, as this is not used for lag-protection but for throttling
521 $this->mWaitForPos
= $oldPos;
528 * @param DBMasterPos|bool $pos
530 private function setWaitForPositionIfHigher( $pos ) {
535 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
536 $this->mWaitForPos
= $pos;
542 * @return IDatabase|bool
544 public function getAnyOpenConnection( $i ) {
545 foreach ( $this->mConns
as $connsByServer ) {
546 if ( !empty( $connsByServer[$i] ) ) {
547 /** @var IDatabase[] $serverConns */
548 $serverConns = $connsByServer[$i];
550 return reset( $serverConns );
558 * Wait for a given replica DB to catch up to the master pos stored in $this
559 * @param int $index Server index
560 * @param bool $open Check the server even if a new connection has to be made
561 * @param int $timeout Max seconds to wait; default is mWaitTimeout
564 protected function doWait( $index, $open = false, $timeout = null ) {
565 $close = false; // close the connection afterwards
567 // Check if we already know that the DB has reached this point
568 $server = $this->getServerName( $index );
569 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
570 /** @var DBMasterPos $knownReachedPos */
571 $knownReachedPos = $this->srvCache
->get( $key );
573 $knownReachedPos instanceof DBMasterPos
&&
574 $knownReachedPos->hasReached( $this->mWaitForPos
)
576 $this->replLogger
->debug( __METHOD__
.
577 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
578 [ 'dbserver' => $server ] );
582 // Find a connection to wait on, creating one if needed and allowed
583 $conn = $this->getAnyOpenConnection( $index );
586 $this->replLogger
->debug( __METHOD__
. ': no connection open for {dbserver}',
587 [ 'dbserver' => $server ] );
591 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
593 $this->replLogger
->warning( __METHOD__
. ': failed to connect to {dbserver}',
594 [ 'dbserver' => $server ] );
598 // Avoid connection spam in waitForAll() when connections
599 // are made just for the sake of doing this lag check.
604 $this->replLogger
->info( __METHOD__
. ': Waiting for replica DB {dbserver} to catch up...',
605 [ 'dbserver' => $server ] );
606 $timeout = $timeout ?
: $this->mWaitTimeout
;
607 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
609 if ( $result == -1 ||
is_null( $result ) ) {
610 // Timed out waiting for replica DB, use master instead
611 $this->replLogger
->warning(
612 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
613 [ 'host' => $server, 'pos' => $this->mWaitForPos
]
617 $this->replLogger
->info( __METHOD__
. ": Done" );
619 // Remember that the DB reached this point
620 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
624 $this->closeConnection( $conn );
630 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
631 if ( $i === null ||
$i === false ) {
632 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
633 ' with invalid server index' );
636 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
637 $domain = false; // local connection requested
640 $groups = ( $groups === false ||
$groups === [] )
641 ?
[ false ] // check one "group": the generic pool
644 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
645 $oldConnsOpened = $this->connsOpened
; // connections open now
647 if ( $i == self
::DB_MASTER
) {
648 if ( $flags & self
::CONN_NO_WRITE
) {
649 throw new InvalidArgumentException(
650 'Cannot set CONN_NO_WRITE flag on master connection!'
654 $i = $this->getWriterIndex();
656 # Try to find an available server in any the query groups (in order)
657 foreach ( $groups as $group ) {
658 $groupIndex = $this->getReaderIndex( $group, $domain );
659 if ( $groupIndex !== false ) {
665 // Request no-write connection, even if $i == $this->getWriterIndex().
666 $flags |
= self
::CONN_NO_WRITE
;
669 # Operation-based index
670 if ( $i == self
::DB_REPLICA
) {
671 $this->mLastError
= 'Unknown error'; // reset error string
672 # Try the general server pool if $groups are unavailable.
673 $i = ( $groups === [ false ] )
674 ?
false // don't bother with this if that is what was tried above
675 : $this->getReaderIndex( false, $domain );
676 # Couldn't find a working server in getReaderIndex()?
677 if ( $i === false ) {
678 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
679 // Throw an exception
680 $this->reportConnectionError();
681 return null; // not reached
684 // Request no-write connection, even if $i == $this->getWriterIndex().
685 $flags |
= self
::CONN_NO_WRITE
;
688 # Now we have an explicit index into the servers array
689 $conn = $this->openConnection( $i, $domain, $flags );
691 // Throw an exception
692 $this->reportConnectionError();
693 return null; // not reached
696 # Profile any new connections that happen
697 if ( $this->connsOpened
> $oldConnsOpened ) {
698 $host = $conn->getServer();
699 $dbname = $conn->getDBname();
700 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
704 # Make master-requested DB handles inherit any read-only mode setting
705 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
711 public function reuseConnection( $conn ) {
712 $serverIndex = $conn->getLBInfo( 'serverIndex' );
713 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
714 if ( $serverIndex === null ||
$refCount === null ) {
716 * This can happen in code like:
717 * foreach ( $dbs as $db ) {
718 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
720 * $lb->reuseConnection( $conn );
722 * When a connection to the local DB is opened in this way, reuseConnection()
726 } elseif ( $conn instanceof DBConnRef
) {
727 // DBConnRef already handles calling reuseConnection() and only passes the live
728 // Database instance to this method. Any caller passing in a DBConnRef is broken.
729 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
730 ( new RuntimeException() )->getTraceAsString() );
735 if ( $this->disabled
) {
736 return; // DBConnRef handle probably survived longer than the LoadBalancer
739 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
740 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
741 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
743 $connFreeKey = self
::KEY_FOREIGN_FREE
;
744 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
747 $domain = $conn->getDomainID();
748 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
749 throw new InvalidArgumentException( __METHOD__
.
750 ": connection $serverIndex/$domain not found; it may have already been freed." );
751 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
752 throw new InvalidArgumentException( __METHOD__
.
753 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
756 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
757 if ( $refCount <= 0 ) {
758 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
759 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
760 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
761 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
763 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
765 $this->connLogger
->debug( __METHOD__
.
766 ": reference count for $serverIndex/$domain reduced to $refCount" );
770 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
771 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
773 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
776 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
777 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
779 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
782 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
783 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
785 return new MaintainableDBConnRef(
786 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
789 public function openConnection( $i, $domain = false, $flags = 0 ) {
790 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
791 $domain = false; // local connection requested
794 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
795 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
796 // Load CP positions before connecting so that doWait() triggers later if needed
797 $this->chronProtInitialized
= true;
798 $this->chronProt
->initLB( $this );
801 // Check if an auto-commit connection is being requested. If so, it will not reuse the
802 // main set of DB connections but rather its own pool since:
803 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
804 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
805 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
806 $noWrite = ( ( $flags & self
::CONN_NO_WRITE
) == self
::CONN_NO_WRITE
);
808 if ( $noWrite && $i === $this->getWriterIndex() ) {
809 // We can't disable writes on the master connection!
810 // TODO: Wrap the master connection, so write operations fail!
814 if ( $domain !== false ) {
815 // Connection is to a foreign domain
816 $conn = $this->openForeignConnection( $i, $domain, $flags );
818 // Connection is to the local domain
819 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
820 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
821 $conn = $this->mConns
[$connKey][$i][0];
823 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
824 throw new InvalidArgumentException( "No server with index '$i'." );
826 // Open a new connection
827 $server = $this->mServers
[$i];
828 $server['serverIndex'] = $i;
829 $server['noWrite'] = $noWrite;
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
);
886 $noWrite = ( ( $flags & self
::CONN_NO_WRITE
) == self
::CONN_NO_WRITE
);
888 if ( $noWrite && $i === $this->getWriterIndex() ) {
889 // We can't disable writes on the master connection!
890 // TODO: Wrap the master connection, so write operations fail!
895 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
896 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
898 $connFreeKey = self
::KEY_FOREIGN_FREE
;
899 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
902 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
903 // Reuse an in-use connection for the same domain
904 $conn = $this->mConns
[$connInUseKey][$i][$domain];
905 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
906 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
907 // Reuse a free connection for the same domain
908 $conn = $this->mConns
[$connFreeKey][$i][$domain];
909 unset( $this->mConns
[$connFreeKey][$i][$domain] );
910 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
911 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
912 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
913 // Reuse a free connection from another domain
914 $conn = reset( $this->mConns
[$connFreeKey][$i] );
915 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
916 // The empty string as a DB name means "don't care".
917 // DatabaseMysqlBase::open() already handle this on connection.
918 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
919 $this->mLastError
= "Error selecting database '$dbName' on server " .
920 $conn->getServer() . " from client host {$this->host}";
921 $this->errorConnection
= $conn;
924 $conn->tablePrefix( $prefix );
925 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
926 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
927 $this->connLogger
->debug( __METHOD__
.
928 ": reusing free connection from $oldDomain for $domain" );
931 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
932 throw new InvalidArgumentException( "No server with index '$i'." );
934 // Open a new connection
935 $server = $this->mServers
[$i];
936 $server['serverIndex'] = $i;
937 $server['foreignPoolRefCount'] = 0;
938 $server['foreign'] = true;
939 $server['autoCommitOnly'] = $autoCommit;
940 $server['noWrite'] = $noWrite;
941 $conn = $this->reallyOpenConnection( $server, $dbName );
942 if ( !$conn->isOpen() ) {
943 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
944 $this->errorConnection
= $conn;
947 $conn->tablePrefix( $prefix );
948 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
949 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
953 // Increment reference count
954 if ( $conn instanceof IDatabase
) {
955 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
956 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
963 * Test if the specified index represents an open connection
965 * @param int $index Server index
969 private function isOpen( $index ) {
970 if ( !is_integer( $index ) ) {
974 return (bool)$this->getAnyOpenConnection( $index );
978 * Really opens a connection. Uncached.
979 * Returns a Database object whether or not the connection was successful.
982 * @param array $server
983 * @param string|bool $dbNameOverride Use "" to not select any database
985 * @throws DBAccessError
986 * @throws InvalidArgumentException
988 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
989 if ( $this->disabled
) {
990 throw new DBAccessError();
993 if ( $dbNameOverride !== false ) {
994 $server['dbname'] = $dbNameOverride;
997 // Let the handle know what the cluster master is (e.g. "db1052")
998 $masterName = $this->getServerName( $this->getWriterIndex() );
999 $server['clusterMasterHost'] = $masterName;
1001 // Log when many connection are made on requests
1002 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1003 $this->perfLogger
->warning( __METHOD__
. ": " .
1004 "{$this->connsOpened}+ connections made (master=$masterName)" );
1007 $server['srvCache'] = $this->srvCache
;
1008 // Set loggers and profilers
1009 $server['connLogger'] = $this->connLogger
;
1010 $server['queryLogger'] = $this->queryLogger
;
1011 $server['errorLogger'] = $this->errorLogger
;
1012 $server['profiler'] = $this->profiler
;
1013 $server['trxProfiler'] = $this->trxProfiler
;
1014 // Use the same agent and PHP mode for all DB handles
1015 $server['cliMode'] = $this->cliMode
;
1016 $server['agent'] = $this->agent
;
1017 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1018 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1019 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1021 // Create a live connection object
1023 $db = Database
::factory( $server['type'], $server );
1024 } catch ( DBConnectionError
$e ) {
1025 // FIXME: This is probably the ugliest thing I have ever done to
1026 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1030 $db->setLBInfo( $server );
1031 $db->setLazyMasterHandle(
1032 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1034 $db->setTableAliases( $this->tableAliases
);
1036 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1037 if ( $this->trxRoundId
!== false ) {
1038 $this->applyTransactionRoundFlags( $db );
1040 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1041 $db->setTransactionListener( $name, $callback );
1049 * @throws DBConnectionError
1051 private function reportConnectionError() {
1052 $conn = $this->errorConnection
; // the connection which caused the error
1054 'method' => __METHOD__
,
1055 'last_error' => $this->mLastError
,
1058 if ( $conn instanceof IDatabase
) {
1059 $context['db_server'] = $conn->getServer();
1060 $this->connLogger
->warning(
1061 "Connection error: {last_error} ({db_server})",
1065 // throws DBConnectionError
1066 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1068 // No last connection, probably due to all servers being too busy
1069 $this->connLogger
->error(
1070 "LB failure with no last connection. Connection error: {last_error}",
1074 // If all servers were busy, mLastError will contain something sensible
1075 throw new DBConnectionError( null, $this->mLastError
);
1079 public function getWriterIndex() {
1083 public function haveIndex( $i ) {
1084 return array_key_exists( $i, $this->mServers
);
1087 public function isNonZeroLoad( $i ) {
1088 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1091 public function getServerCount() {
1092 return count( $this->mServers
);
1095 public function getServerName( $i ) {
1096 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1097 $name = $this->mServers
[$i]['hostName'];
1098 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1099 $name = $this->mServers
[$i]['host'];
1104 return ( $name != '' ) ?
$name : 'localhost';
1107 public function getServerType( $i ) {
1108 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
1112 * @deprecated Since 1.30, no alternative
1114 public function getServerInfo( $i ) {
1115 wfDeprecated( __METHOD__
, '1.30' );
1116 if ( isset( $this->mServers
[$i] ) ) {
1117 return $this->mServers
[$i];
1124 * @deprecated Since 1.30, construct new object
1126 public function setServerInfo( $i, array $serverInfo ) {
1127 wfDeprecated( __METHOD__
, '1.30' );
1128 $this->mServers
[$i] = $serverInfo;
1131 public function getMasterPos() {
1132 # If this entire request was served from a replica DB without opening a connection to the
1133 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1134 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1135 if ( !$masterConn ) {
1136 $serverCount = count( $this->mServers
);
1137 for ( $i = 1; $i < $serverCount; $i++
) {
1138 $conn = $this->getAnyOpenConnection( $i );
1140 return $conn->getReplicaPos();
1144 return $masterConn->getMasterPos();
1150 public function disable() {
1152 $this->disabled
= true;
1155 public function closeAll() {
1156 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1157 $host = $conn->getServer();
1158 $this->connLogger
->debug( "Closing connection to database '$host'." );
1163 self
::KEY_LOCAL
=> [],
1164 self
::KEY_FOREIGN_INUSE
=> [],
1165 self
::KEY_FOREIGN_FREE
=> [],
1166 self
::KEY_LOCAL_NOROUND
=> [],
1167 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1168 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1170 $this->connsOpened
= 0;
1173 public function closeConnection( IDatabase
$conn ) {
1174 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1175 foreach ( $this->mConns
as $type => $connsByServer ) {
1176 if ( !isset( $connsByServer[$serverIndex] ) ) {
1180 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1181 if ( $conn === $trackedConn ) {
1182 $host = $this->getServerName( $i );
1183 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1184 unset( $this->mConns
[$type][$serverIndex][$i] );
1185 --$this->connsOpened
;
1194 public function commitAll( $fname = __METHOD__
) {
1197 $restore = ( $this->trxRoundId
!== false );
1198 $this->trxRoundId
= false;
1199 $this->forEachOpenConnection(
1200 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1202 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1203 } catch ( DBError
$e ) {
1204 call_user_func( $this->errorLogger
, $e );
1205 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1207 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1208 $this->undoTransactionRoundFlags( $conn );
1214 throw new DBExpectedError(
1216 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1221 public function finalizeMasterChanges() {
1222 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1223 // Any error should cause all DB transactions to be rolled back together
1224 $conn->setTrxEndCallbackSuppression( false );
1225 $conn->runOnTransactionPreCommitCallbacks();
1226 // Defer post-commit callbacks until COMMIT finishes for all DBs
1227 $conn->setTrxEndCallbackSuppression( true );
1231 public function approveMasterChanges( array $options ) {
1232 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1233 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1234 // If atomic sections or explicit transactions are still open, some caller must have
1235 // caught an exception but failed to properly rollback any changes. Detect that and
1236 // throw and error (causing rollback).
1237 if ( $conn->explicitTrxActive() ) {
1238 throw new DBTransactionError(
1240 "Explicit transaction still active. A caller may have caught an error."
1243 // Assert that the time to replicate the transaction will be sane.
1244 // If this fails, then all DB transactions will be rollback back together.
1245 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1246 if ( $limit > 0 && $time > $limit ) {
1247 throw new DBTransactionSizeError(
1249 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1253 // If a connection sits idle while slow queries execute on another, that connection
1254 // may end up dropped before the commit round is reached. Ping servers to detect this.
1255 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1256 throw new DBTransactionError(
1258 "A connection to the {$conn->getDBname()} database was lost before commit."
1264 public function beginMasterChanges( $fname = __METHOD__
) {
1265 if ( $this->trxRoundId
!== false ) {
1266 throw new DBTransactionError(
1268 "$fname: Transaction round '{$this->trxRoundId}' already started."
1271 $this->trxRoundId
= $fname;
1274 $this->forEachOpenMasterConnection(
1275 function ( Database
$conn ) use ( $fname, &$failures ) {
1276 $conn->setTrxEndCallbackSuppression( true );
1278 $conn->flushSnapshot( $fname );
1279 } catch ( DBError
$e ) {
1280 call_user_func( $this->errorLogger
, $e );
1281 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1283 $conn->setTrxEndCallbackSuppression( false );
1284 $this->applyTransactionRoundFlags( $conn );
1289 throw new DBExpectedError(
1291 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1296 public function commitMasterChanges( $fname = __METHOD__
) {
1299 /** @noinspection PhpUnusedLocalVariableInspection */
1300 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1302 $restore = ( $this->trxRoundId
!== false );
1303 $this->trxRoundId
= false;
1304 $this->forEachOpenMasterConnection(
1305 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1307 if ( $conn->writesOrCallbacksPending() ) {
1308 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1309 } elseif ( $restore ) {
1310 $conn->flushSnapshot( $fname );
1312 } catch ( DBError
$e ) {
1313 call_user_func( $this->errorLogger
, $e );
1314 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1317 $this->undoTransactionRoundFlags( $conn );
1323 throw new DBExpectedError(
1325 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1330 public function runMasterPostTrxCallbacks( $type ) {
1331 $e = null; // first exception
1332 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1333 $conn->setTrxEndCallbackSuppression( false );
1334 if ( $conn->writesOrCallbacksPending() ) {
1335 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1336 // (which finished its callbacks already). Warn and recover in this case. Let the
1337 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1338 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1340 } elseif ( $conn->trxLevel() ) {
1341 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1342 // thus leaving an implicit read-only transaction open at this point. It
1343 // also happens if onTransactionIdle() callbacks leave implicit transactions
1344 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1345 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1349 $conn->runOnTransactionIdleCallbacks( $type );
1350 } catch ( Exception
$ex ) {
1354 $conn->runTransactionListenerCallbacks( $type );
1355 } catch ( Exception
$ex ) {
1363 public function rollbackMasterChanges( $fname = __METHOD__
) {
1364 $restore = ( $this->trxRoundId
!== false );
1365 $this->trxRoundId
= false;
1366 $this->forEachOpenMasterConnection(
1367 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1368 if ( $conn->writesOrCallbacksPending() ) {
1369 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1372 $this->undoTransactionRoundFlags( $conn );
1378 public function suppressTransactionEndCallbacks() {
1379 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1380 $conn->setTrxEndCallbackSuppression( true );
1385 * @param IDatabase $conn
1387 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1388 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1389 return; // transaction rounds do not apply to these connections
1392 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1393 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1394 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1395 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1396 // If config has explicitly requested DBO_TRX be either on or off by not
1397 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1398 // for things like blob stores (ExternalStore) which want auto-commit mode.
1403 * @param IDatabase $conn
1405 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1406 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1407 return; // transaction rounds do not apply to these connections
1410 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1411 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1415 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1416 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1417 $conn->flushSnapshot( __METHOD__
);
1421 public function hasMasterConnection() {
1422 return $this->isOpen( $this->getWriterIndex() );
1425 public function hasMasterChanges() {
1427 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1428 $pending |
= $conn->writesOrCallbacksPending();
1431 return (bool)$pending;
1434 public function lastMasterChangeTimestamp() {
1436 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1437 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1443 public function hasOrMadeRecentMasterChanges( $age = null ) {
1444 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1446 return ( $this->hasMasterChanges()
1447 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1450 public function pendingMasterChangeCallers() {
1452 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1453 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1459 public function getLaggedReplicaMode( $domain = false ) {
1460 // No-op if there is only one DB (also avoids recursion)
1461 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1463 // See if laggedReplicaMode gets set
1464 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1465 $this->reuseConnection( $conn );
1466 } catch ( DBConnectionError
$e ) {
1467 // Avoid expensive re-connect attempts and failures
1468 $this->allReplicasDownMode
= true;
1469 $this->laggedReplicaMode
= true;
1473 return $this->laggedReplicaMode
;
1477 * @param bool $domain
1479 * @deprecated 1.28; use getLaggedReplicaMode()
1481 public function getLaggedSlaveMode( $domain = false ) {
1482 return $this->getLaggedReplicaMode( $domain );
1485 public function laggedReplicaUsed() {
1486 return $this->laggedReplicaMode
;
1492 * @deprecated Since 1.28; use laggedReplicaUsed()
1494 public function laggedSlaveUsed() {
1495 return $this->laggedReplicaUsed();
1498 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1499 if ( $this->readOnlyReason
!== false ) {
1500 return $this->readOnlyReason
;
1501 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1502 if ( $this->allReplicasDownMode
) {
1503 return 'The database has been automatically locked ' .
1504 'until the replica database servers become available';
1506 return 'The database has been automatically locked ' .
1507 'while the replica database servers catch up to the master.';
1509 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1510 return 'The database master is running in read-only mode.';
1517 * @param string $domain Domain ID, or false for the current domain
1518 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1521 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1522 $cache = $this->wanCache
;
1523 $masterServer = $this->getServerName( $this->getWriterIndex() );
1525 return (bool)$cache->getWithSetCallback(
1526 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1527 self
::TTL_CACHE_READONLY
,
1528 function () use ( $domain, $conn ) {
1529 $old = $this->trxProfiler
->setSilenced( true );
1531 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1532 $readOnly = (int)$dbw->serverIsReadOnly();
1534 $this->reuseConnection( $dbw );
1536 } catch ( DBError
$e ) {
1539 $this->trxProfiler
->setSilenced( $old );
1542 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1546 public function allowLagged( $mode = null ) {
1547 if ( $mode === null ) {
1548 return $this->mAllowLagged
;
1550 $this->mAllowLagged
= $mode;
1552 return $this->mAllowLagged
;
1555 public function pingAll() {
1557 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1558 if ( !$conn->ping() ) {
1566 public function forEachOpenConnection( $callback, array $params = [] ) {
1567 foreach ( $this->mConns
as $connsByServer ) {
1568 foreach ( $connsByServer as $serverConns ) {
1569 foreach ( $serverConns as $conn ) {
1570 $mergedParams = array_merge( [ $conn ], $params );
1571 call_user_func_array( $callback, $mergedParams );
1577 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1578 $masterIndex = $this->getWriterIndex();
1579 foreach ( $this->mConns
as $connsByServer ) {
1580 if ( isset( $connsByServer[$masterIndex] ) ) {
1581 /** @var IDatabase $conn */
1582 foreach ( $connsByServer[$masterIndex] as $conn ) {
1583 $mergedParams = array_merge( [ $conn ], $params );
1584 call_user_func_array( $callback, $mergedParams );
1590 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1591 foreach ( $this->mConns
as $connsByServer ) {
1592 foreach ( $connsByServer as $i => $serverConns ) {
1593 if ( $i === $this->getWriterIndex() ) {
1594 continue; // skip master
1596 foreach ( $serverConns as $conn ) {
1597 $mergedParams = array_merge( [ $conn ], $params );
1598 call_user_func_array( $callback, $mergedParams );
1604 public function getMaxLag( $domain = false ) {
1609 if ( $this->getServerCount() <= 1 ) {
1610 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1613 $lagTimes = $this->getLagTimes( $domain );
1614 foreach ( $lagTimes as $i => $lag ) {
1615 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1617 $host = $this->mServers
[$i]['host'];
1622 return [ $host, $maxLag, $maxIndex ];
1625 public function getLagTimes( $domain = false ) {
1626 if ( $this->getServerCount() <= 1 ) {
1627 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1630 $knownLagTimes = []; // map of (server index => 0 seconds)
1631 $indexesWithLag = [];
1632 foreach ( $this->mServers
as $i => $server ) {
1633 if ( empty( $server['is static'] ) ) {
1634 $indexesWithLag[] = $i; // DB server might have replication lag
1636 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1640 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1643 public function safeGetLag( IDatabase
$conn ) {
1644 if ( $this->getServerCount() <= 1 ) {
1647 return $conn->getLag();
1652 * @param IDatabase $conn
1653 * @param DBMasterPos|bool $pos
1654 * @param int $timeout
1657 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1658 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1659 return true; // server is not a replica DB
1663 // Get the current master position, opening a connection if needed
1664 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1665 if ( $masterConn ) {
1666 $pos = $masterConn->getMasterPos();
1668 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1669 $pos = $masterConn->getMasterPos();
1670 $this->closeConnection( $masterConn );
1674 if ( $pos instanceof DBMasterPos
) {
1675 $result = $conn->masterPosWait( $pos, $timeout );
1676 if ( $result == -1 ||
is_null( $result ) ) {
1677 $msg = __METHOD__
. ': Timed out waiting on {host} pos {pos}';
1678 $this->replLogger
->warning( $msg,
1679 [ 'host' => $conn->getServer(), 'pos' => $pos ] );
1682 $this->replLogger
->info( __METHOD__
. ': Done' );
1686 $ok = false; // something is misconfigured
1687 $this->replLogger
->error( 'Could not get master pos for {host}',
1688 [ 'host' => $conn->getServer() ] );
1694 public function setTransactionListener( $name, callable
$callback = null ) {
1696 $this->trxRecurringCallbacks
[$name] = $callback;
1698 unset( $this->trxRecurringCallbacks
[$name] );
1700 $this->forEachOpenMasterConnection(
1701 function ( IDatabase
$conn ) use ( $name, $callback ) {
1702 $conn->setTransactionListener( $name, $callback );
1707 public function setTableAliases( array $aliases ) {
1708 $this->tableAliases
= $aliases;
1711 public function setDomainPrefix( $prefix ) {
1712 // Find connections to explicit foreign domains still marked as in-use...
1714 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1715 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1716 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1717 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1718 $domainsInUse[] = $conn->getDomainID();
1722 // Do not switch connections to explicit foreign domains unless marked as safe
1723 if ( $domainsInUse ) {
1724 $domains = implode( ', ', $domainsInUse );
1725 throw new DBUnexpectedError( null,
1726 "Foreign domain connections are still in use ($domains)." );
1729 $this->localDomain
= new DatabaseDomain(
1730 $this->localDomain
->getDatabase(),
1735 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1736 $db->tablePrefix( $prefix );
1741 * Make PHP ignore user aborts/disconnects until the returned
1742 * value leaves scope. This returns null and does nothing in CLI mode.
1744 * @return ScopedCallback|null
1746 final protected function getScopedPHPBehaviorForCommit() {
1747 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1748 $old = ignore_user_abort( true ); // avoid half-finished operations
1749 return new ScopedCallback( function () use ( $old ) {
1750 ignore_user_abort( $old );
1757 function __destruct() {
1758 // Avoid connection leaks for sanity
1763 class_alias( LoadBalancer
::class, 'LoadBalancer' );