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 Default 'waitTimeout' when unspecified */
126 const MAX_WAIT_DEFAULT
= 10;
127 /** @var int Seconds to cache master server read-only status */
128 const TTL_CACHE_READONLY
= 5;
130 const KEY_LOCAL
= 'local';
131 const KEY_FOREIGN_FREE
= 'foreignFree';
132 const KEY_FOREIGN_INUSE
= 'foreignInUse';
134 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
135 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
136 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
138 public function __construct( array $params ) {
139 if ( !isset( $params['servers'] ) ) {
140 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
142 $this->mServers
= $params['servers'];
143 foreach ( $this->mServers
as $i => $server ) {
145 $this->mServers
[$i]['master'] = true;
147 $this->mServers
[$i]['replica'] = true;
151 $localDomain = isset( $params['localDomain'] )
152 ? DatabaseDomain
::newFromId( $params['localDomain'] )
153 : DatabaseDomain
::newUnspecified();
154 $this->setLocalDomain( $localDomain );
156 $this->mWaitTimeout
= isset( $params['waitTimeout'] )
157 ?
$params['waitTimeout']
158 : self
::MAX_WAIT_DEFAULT
;
160 $this->mReadIndex
= -1;
162 // Connection were transaction rounds may be applied
163 self
::KEY_LOCAL
=> [],
164 self
::KEY_FOREIGN_INUSE
=> [],
165 self
::KEY_FOREIGN_FREE
=> [],
166 // Auto-committing counterpart connections that ignore transaction rounds
167 self
::KEY_LOCAL_NOROUND
=> [],
168 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
169 self
::KEY_FOREIGN_FREE_NOROUND
=> []
172 $this->mWaitForPos
= false;
173 $this->mAllowLagged
= false;
175 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
176 $this->readOnlyReason
= $params['readOnlyReason'];
179 if ( isset( $params['maxLag'] ) ) {
180 $this->maxLag
= $params['maxLag'];
183 if ( isset( $params['loadMonitor'] ) ) {
184 $this->loadMonitorConfig
= $params['loadMonitor'];
186 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
188 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
190 foreach ( $params['servers'] as $i => $server ) {
191 $this->mLoads
[$i] = $server['load'];
192 if ( isset( $server['groupLoads'] ) ) {
193 foreach ( $server['groupLoads'] as $group => $ratio ) {
194 if ( !isset( $this->mGroupLoads
[$group] ) ) {
195 $this->mGroupLoads
[$group] = [];
197 $this->mGroupLoads
[$group][$i] = $ratio;
202 if ( isset( $params['srvCache'] ) ) {
203 $this->srvCache
= $params['srvCache'];
205 $this->srvCache
= new EmptyBagOStuff();
207 if ( isset( $params['wanCache'] ) ) {
208 $this->wanCache
= $params['wanCache'];
210 $this->wanCache
= WANObjectCache
::newEmpty();
212 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
213 if ( isset( $params['trxProfiler'] ) ) {
214 $this->trxProfiler
= $params['trxProfiler'];
216 $this->trxProfiler
= new TransactionProfiler();
219 $this->errorLogger
= isset( $params['errorLogger'] )
220 ?
$params['errorLogger']
221 : function ( Exception
$e ) {
222 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
225 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
226 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
229 $this->host
= isset( $params['hostname'] )
230 ?
$params['hostname']
231 : ( gethostname() ?
: 'unknown' );
232 $this->cliMode
= isset( $params['cliMode'] )
234 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
235 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
237 if ( isset( $params['chronologyProtector'] ) ) {
238 $this->chronProt
= $params['chronologyProtector'];
243 * Get the local (and default) database domain ID of connection handles
245 * @see DatabaseDomain
246 * @return string Database domain ID; this specifies DB name, schema, and table prefix
249 public function getLocalDomainID() {
250 return $this->localDomain
->getId();
254 * Get a LoadMonitor instance
256 * @return ILoadMonitor
258 private function getLoadMonitor() {
259 if ( !isset( $this->loadMonitor
) ) {
261 'LoadMonitor' => LoadMonitor
::class,
262 'LoadMonitorNull' => LoadMonitorNull
::class,
263 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
266 $class = $this->loadMonitorConfig
['class'];
267 if ( isset( $compat[$class] ) ) {
268 $class = $compat[$class];
271 $this->loadMonitor
= new $class(
272 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
273 $this->loadMonitor
->setLogger( $this->replLogger
);
276 return $this->loadMonitor
;
280 * @param array $loads
281 * @param bool|string $domain Domain to get non-lagged for
282 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
283 * @return bool|int|string
285 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
286 $lags = $this->getLagTimes( $domain );
288 # Unset excessively lagged servers
289 foreach ( $lags as $i => $lag ) {
291 # How much lag this server nominally is allowed to have
292 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
293 ?
$this->mServers
[$i]['max lag']
294 : $this->maxLag
; // default
295 # Constrain that futher by $maxLag argument
296 $maxServerLag = min( $maxServerLag, $maxLag );
298 $host = $this->getServerName( $i );
299 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
300 $this->replLogger
->error(
301 "Server {host} is not replicating?", [ 'host' => $host ] );
303 } elseif ( $lag > $maxServerLag ) {
304 $this->replLogger
->info(
305 "Server {host} has {lag} seconds of lag (>= {maxlag})",
306 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
313 # Find out if all the replica DBs with non-zero load are lagged
315 foreach ( $loads as $load ) {
319 # No appropriate DB servers except maybe the master and some replica DBs with zero load
320 # Do NOT use the master
321 # Instead, this function will return false, triggering read-only mode,
322 # and a lagged replica DB will be used instead.
326 if ( count( $loads ) == 0 ) {
330 # Return a random representative of the remainder
331 return ArrayUtils
::pickRandom( $loads );
334 public function getReaderIndex( $group = false, $domain = false ) {
335 if ( count( $this->mServers
) == 1 ) {
336 // Skip the load balancing if there's only one server
337 return $this->getWriterIndex();
338 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
339 // Shortcut if the generic reader index was already cached
340 return $this->mReadIndex
;
343 if ( $group !== false ) {
344 // Use the server weight array for this load group
345 if ( isset( $this->mGroupLoads
[$group] ) ) {
346 $loads = $this->mGroupLoads
[$group];
348 // No loads for this group, return false and the caller can use some other group
349 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
354 // Use the generic load group
355 $loads = $this->mLoads
;
358 // Scale the configured load ratios according to each server's load and state
359 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
361 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
362 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
363 if ( $i === false ) {
364 // Replica DB connection unsuccessful
368 if ( $this->mWaitForPos
&& $i != $this->getWriterIndex() ) {
369 // Before any data queries are run, wait for the server to catch up to the
370 // specified position. This is used to improve session consistency. Note that
371 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
372 // so update laggedReplicaMode as needed for consistency.
373 if ( !$this->doWait( $i ) ) {
374 $laggedReplicaMode = true;
378 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
379 // Cache the generic reader index for future ungrouped DB_REPLICA handles
380 $this->mReadIndex
= $i;
381 // Record if the generic reader index is in "lagged replica DB" mode
382 if ( $laggedReplicaMode ) {
383 $this->laggedReplicaMode
= true;
387 $serverName = $this->getServerName( $i );
388 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
394 * @param array $loads List of server weights
395 * @param string|bool $domain
396 * @return array (reader index, lagged replica mode) or false on failure
398 private function pickReaderIndex( array $loads, $domain = false ) {
399 if ( !count( $loads ) ) {
400 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
403 /** @var int|bool $i Index of selected server */
405 /** @var bool $laggedReplicaMode Whether server is considered lagged */
406 $laggedReplicaMode = false;
408 // Quickly look through the available servers for a server that meets criteria...
409 $currentLoads = $loads;
410 while ( count( $currentLoads ) ) {
411 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
412 $i = ArrayUtils
::pickRandom( $currentLoads );
415 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
416 // ChronologyProtecter sets mWaitForPos for session consistency.
417 // This triggers doWait() after connect, so it's especially good to
418 // avoid lagged servers so as to avoid excessive delay in that method.
419 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
420 // Aim for <= 1 second of waiting (being too picky can backfire)
421 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
423 if ( $i === false ) {
424 // Any server with less lag than it's 'max lag' param is preferable
425 $i = $this->getRandomNonLagged( $currentLoads, $domain );
427 if ( $i === false && count( $currentLoads ) != 0 ) {
428 // All replica DBs lagged. Switch to read-only mode
429 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
430 $i = ArrayUtils
::pickRandom( $currentLoads );
431 $laggedReplicaMode = true;
435 if ( $i === false ) {
436 // pickRandom() returned false.
437 // This is permanent and means the configuration or the load monitor
438 // wants us to return false.
439 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
441 return [ false, false ];
444 $serverName = $this->getServerName( $i );
445 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
447 $conn = $this->openConnection( $i, $domain );
449 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
450 unset( $currentLoads[$i] ); // avoid this server next iteration
455 // Decrement reference counter, we are finished with this connection.
456 // It will be incremented for the caller later.
457 if ( $domain !== false ) {
458 $this->reuseConnection( $conn );
461 // Return this server
465 // If all servers were down, quit now
466 if ( !count( $currentLoads ) ) {
467 $this->connLogger
->error( "All servers down" );
470 return [ $i, $laggedReplicaMode ];
473 public function waitFor( $pos ) {
474 $oldPos = $this->mWaitForPos
;
476 $this->mWaitForPos
= $pos;
477 // If a generic reader connection was already established, then wait now
478 $i = $this->mReadIndex
;
480 if ( !$this->doWait( $i ) ) {
481 $this->laggedReplicaMode
= true;
485 // Restore the older position if it was higher since this is used for lag-protection
486 $this->setWaitForPositionIfHigher( $oldPos );
490 public function waitForOne( $pos, $timeout = null ) {
491 $oldPos = $this->mWaitForPos
;
493 $this->mWaitForPos
= $pos;
495 $i = $this->mReadIndex
;
497 // Pick a generic replica DB if there isn't one yet
498 $readLoads = $this->mLoads
;
499 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
500 $readLoads = array_filter( $readLoads ); // with non-zero load
501 $i = ArrayUtils
::pickRandom( $readLoads );
505 $ok = $this->doWait( $i, true, $timeout );
507 $ok = true; // no applicable loads
510 # Restore the old position, as this is not used for lag-protection but for throttling
511 $this->mWaitForPos
= $oldPos;
517 public function waitForAll( $pos, $timeout = null ) {
518 $timeout = $timeout ?
: $this->mWaitTimeout
;
520 $oldPos = $this->mWaitForPos
;
522 $this->mWaitForPos
= $pos;
523 $serverCount = count( $this->mServers
);
526 for ( $i = 1; $i < $serverCount; $i++
) {
527 if ( $this->mLoads
[$i] > 0 ) {
528 $start = microtime( true );
529 $ok = $this->doWait( $i, true, max( 1, (int)$timeout ) ) && $ok;
530 $timeout -= ( microtime( true ) - $start );
531 if ( $timeout <= 0 ) {
532 break; // timeout reached
537 # Restore the old position, as this is not used for lag-protection but for throttling
538 $this->mWaitForPos
= $oldPos;
545 * @param DBMasterPos|bool $pos
547 private function setWaitForPositionIfHigher( $pos ) {
552 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
553 $this->mWaitForPos
= $pos;
559 * @return IDatabase|bool
561 public function getAnyOpenConnection( $i ) {
562 foreach ( $this->mConns
as $connsByServer ) {
563 if ( !empty( $connsByServer[$i] ) ) {
564 /** @var IDatabase[] $serverConns */
565 $serverConns = $connsByServer[$i];
567 return reset( $serverConns );
575 * Wait for a given replica DB to catch up to the master pos stored in $this
576 * @param int $index Server index
577 * @param bool $open Check the server even if a new connection has to be made
578 * @param int $timeout Max seconds to wait; default is mWaitTimeout
581 protected function doWait( $index, $open = false, $timeout = null ) {
582 $close = false; // close the connection afterwards
584 // Check if we already know that the DB has reached this point
585 $server = $this->getServerName( $index );
586 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
587 /** @var DBMasterPos $knownReachedPos */
588 $knownReachedPos = $this->srvCache
->get( $key );
590 $knownReachedPos instanceof DBMasterPos
&&
591 $knownReachedPos->hasReached( $this->mWaitForPos
)
593 $this->replLogger
->debug(
595 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
596 [ 'dbserver' => $server ]
601 // Find a connection to wait on, creating one if needed and allowed
602 $conn = $this->getAnyOpenConnection( $index );
605 $this->replLogger
->debug(
606 __METHOD__
. ': no connection open for {dbserver}',
607 [ 'dbserver' => $server ]
612 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
614 $this->replLogger
->warning(
615 __METHOD__
. ': failed to connect to {dbserver}',
616 [ 'dbserver' => $server ]
621 // Avoid connection spam in waitForAll() when connections
622 // are made just for the sake of doing this lag check.
627 $this->replLogger
->info(
629 ': Waiting for replica DB {dbserver} to catch up...',
630 [ 'dbserver' => $server ]
633 $timeout = $timeout ?
: $this->mWaitTimeout
;
634 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
636 if ( $result === null ) {
637 $this->replLogger
->warning(
638 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
641 'pos' => $this->mWaitForPos
,
642 'trace' => ( new RuntimeException() )->getTraceAsString()
646 } elseif ( $result == -1 ) {
647 $this->replLogger
->warning(
648 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
651 'pos' => $this->mWaitForPos
,
652 'trace' => ( new RuntimeException() )->getTraceAsString()
657 $this->replLogger
->info( __METHOD__
. ": Done" );
659 // Remember that the DB reached this point
660 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
664 $this->closeConnection( $conn );
670 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
671 if ( $i === null ||
$i === false ) {
672 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
673 ' with invalid server index' );
676 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
677 $domain = false; // local connection requested
680 $groups = ( $groups === false ||
$groups === [] )
681 ?
[ false ] // check one "group": the generic pool
684 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
685 $oldConnsOpened = $this->connsOpened
; // connections open now
687 if ( $i == self
::DB_MASTER
) {
688 $i = $this->getWriterIndex();
690 # Try to find an available server in any the query groups (in order)
691 foreach ( $groups as $group ) {
692 $groupIndex = $this->getReaderIndex( $group, $domain );
693 if ( $groupIndex !== false ) {
700 # Operation-based index
701 if ( $i == self
::DB_REPLICA
) {
702 $this->mLastError
= 'Unknown error'; // reset error string
703 # Try the general server pool if $groups are unavailable.
704 $i = ( $groups === [ false ] )
705 ?
false // don't bother with this if that is what was tried above
706 : $this->getReaderIndex( false, $domain );
707 # Couldn't find a working server in getReaderIndex()?
708 if ( $i === false ) {
709 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
710 // Throw an exception
711 $this->reportConnectionError();
712 return null; // not reached
716 # Now we have an explicit index into the servers array
717 $conn = $this->openConnection( $i, $domain, $flags );
719 // Throw an exception
720 $this->reportConnectionError();
721 return null; // not reached
724 # Profile any new connections that happen
725 if ( $this->connsOpened
> $oldConnsOpened ) {
726 $host = $conn->getServer();
727 $dbname = $conn->getDBname();
728 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
732 # Make master-requested DB handles inherit any read-only mode setting
733 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
739 public function reuseConnection( $conn ) {
740 $serverIndex = $conn->getLBInfo( 'serverIndex' );
741 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
742 if ( $serverIndex === null ||
$refCount === null ) {
744 * This can happen in code like:
745 * foreach ( $dbs as $db ) {
746 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
748 * $lb->reuseConnection( $conn );
750 * When a connection to the local DB is opened in this way, reuseConnection()
754 } elseif ( $conn instanceof DBConnRef
) {
755 // DBConnRef already handles calling reuseConnection() and only passes the live
756 // Database instance to this method. Any caller passing in a DBConnRef is broken.
757 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
758 ( new RuntimeException() )->getTraceAsString() );
763 if ( $this->disabled
) {
764 return; // DBConnRef handle probably survived longer than the LoadBalancer
767 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
768 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
769 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
771 $connFreeKey = self
::KEY_FOREIGN_FREE
;
772 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
775 $domain = $conn->getDomainID();
776 if ( !isset( $this->mConns
[$connInUseKey][$serverIndex][$domain] ) ) {
777 throw new InvalidArgumentException( __METHOD__
.
778 ": connection $serverIndex/$domain not found; it may have already been freed." );
779 } elseif ( $this->mConns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
780 throw new InvalidArgumentException( __METHOD__
.
781 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
784 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
785 if ( $refCount <= 0 ) {
786 $this->mConns
[$connFreeKey][$serverIndex][$domain] = $conn;
787 unset( $this->mConns
[$connInUseKey][$serverIndex][$domain] );
788 if ( !$this->mConns
[$connInUseKey][$serverIndex] ) {
789 unset( $this->mConns
[$connInUseKey][$serverIndex] ); // clean up
791 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
793 $this->connLogger
->debug( __METHOD__
.
794 ": reference count for $serverIndex/$domain reduced to $refCount" );
798 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
799 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
801 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
804 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
805 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
807 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
810 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
811 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
813 return new MaintainableDBConnRef(
814 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
817 public function openConnection( $i, $domain = false, $flags = 0 ) {
818 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
819 $domain = false; // local connection requested
822 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
823 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
824 // Load CP positions before connecting so that doWait() triggers later if needed
825 $this->chronProtInitialized
= true;
826 $this->chronProt
->initLB( $this );
829 // Check if an auto-commit connection is being requested. If so, it will not reuse the
830 // main set of DB connections but rather its own pool since:
831 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
832 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
833 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
835 if ( $domain !== false ) {
836 // Connection is to a foreign domain
837 $conn = $this->openForeignConnection( $i, $domain, $flags );
839 // Connection is to the local domain
840 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
841 if ( isset( $this->mConns
[$connKey][$i][0] ) ) {
842 $conn = $this->mConns
[$connKey][$i][0];
844 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
845 throw new InvalidArgumentException( "No server with index '$i'." );
847 // Open a new connection
848 $server = $this->mServers
[$i];
849 $server['serverIndex'] = $i;
850 $server['autoCommitOnly'] = $autoCommit;
851 if ( $this->localDomain
->getDatabase() !== null ) {
852 // Use the local domain table prefix if the local domain is specified
853 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
855 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
856 $host = $this->getServerName( $i );
857 if ( $conn->isOpen() ) {
858 $this->connLogger
->debug( "Connected to database $i at '$host'." );
859 $this->mConns
[$connKey][$i][0] = $conn;
861 $this->connLogger
->warning( "Failed to connect to database $i at '$host'." );
862 $this->errorConnection
= $conn;
868 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
869 // Connection was made but later unrecoverably lost for some reason.
870 // Do not return a handle that will just throw exceptions on use,
871 // but let the calling code (e.g. getReaderIndex) try another server.
872 // See DatabaseMyslBase::ping() for how this can happen.
873 $this->errorConnection
= $conn;
877 if ( $autoCommit && $conn instanceof IDatabase
) {
878 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
885 * Open a connection to a foreign DB, or return one if it is already open.
887 * Increments a reference count on the returned connection which locks the
888 * connection to the requested domain. This reference count can be
889 * decremented by calling reuseConnection().
891 * If a connection is open to the appropriate server already, but with the wrong
892 * database, it will be switched to the right database and returned, as long as
893 * it has been freed first with reuseConnection().
895 * On error, returns false, and the connection which caused the
896 * error will be available via $this->errorConnection.
898 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
900 * @param int $i Server index
901 * @param string $domain Domain ID to open
902 * @param int $flags Class CONN_* constant bitfield
905 private function openForeignConnection( $i, $domain, $flags = 0 ) {
906 $domainInstance = DatabaseDomain
::newFromId( $domain );
907 $dbName = $domainInstance->getDatabase();
908 $prefix = $domainInstance->getTablePrefix();
909 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
912 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
913 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
915 $connFreeKey = self
::KEY_FOREIGN_FREE
;
916 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
919 if ( isset( $this->mConns
[$connInUseKey][$i][$domain] ) ) {
920 // Reuse an in-use connection for the same domain
921 $conn = $this->mConns
[$connInUseKey][$i][$domain];
922 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
923 } elseif ( isset( $this->mConns
[$connFreeKey][$i][$domain] ) ) {
924 // Reuse a free connection for the same domain
925 $conn = $this->mConns
[$connFreeKey][$i][$domain];
926 unset( $this->mConns
[$connFreeKey][$i][$domain] );
927 $this->mConns
[$connInUseKey][$i][$domain] = $conn;
928 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
929 } elseif ( !empty( $this->mConns
[$connFreeKey][$i] ) ) {
930 // Reuse a free connection from another domain
931 $conn = reset( $this->mConns
[$connFreeKey][$i] );
932 $oldDomain = key( $this->mConns
[$connFreeKey][$i] );
933 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
934 $this->mLastError
= "Error selecting database '$dbName' on server " .
935 $conn->getServer() . " from client host {$this->host}";
936 $this->errorConnection
= $conn;
939 $conn->tablePrefix( $prefix );
940 unset( $this->mConns
[$connFreeKey][$i][$oldDomain] );
941 // Note that if $domain is an empty string, getDomainID() might not match it
942 $this->mConns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
943 $this->connLogger
->debug( __METHOD__
.
944 ": reusing free connection from $oldDomain for $domain" );
947 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
948 throw new InvalidArgumentException( "No server with index '$i'." );
950 // Open a new connection
951 $server = $this->mServers
[$i];
952 $server['serverIndex'] = $i;
953 $server['foreignPoolRefCount'] = 0;
954 $server['foreign'] = true;
955 $server['autoCommitOnly'] = $autoCommit;
956 $conn = $this->reallyOpenConnection( $server, $domainInstance );
957 if ( !$conn->isOpen() ) {
958 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
959 $this->errorConnection
= $conn;
962 $conn->tablePrefix( $prefix ); // as specified
963 // Note that if $domain is an empty string, getDomainID() might not match it
964 $this->mConns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
965 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
969 // Increment reference count
970 if ( $conn instanceof IDatabase
) {
971 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
972 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
979 * Test if the specified index represents an open connection
981 * @param int $index Server index
985 private function isOpen( $index ) {
986 if ( !is_int( $index ) ) {
990 return (bool)$this->getAnyOpenConnection( $index );
994 * Open a new network connection to a server (uncached)
996 * Returns a Database object whether or not the connection was successful.
998 * @param array $server
999 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1001 * @throws DBAccessError
1002 * @throws InvalidArgumentException
1004 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1005 if ( $this->disabled
) {
1006 throw new DBAccessError();
1009 if ( $domainOverride->getDatabase() !== null ) {
1010 $server['dbname'] = $domainOverride->getDatabase();
1011 $server['schema'] = $domainOverride->getSchema();
1014 // Let the handle know what the cluster master is (e.g. "db1052")
1015 $masterName = $this->getServerName( $this->getWriterIndex() );
1016 $server['clusterMasterHost'] = $masterName;
1018 // Log when many connection are made on requests
1019 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1020 $this->perfLogger
->warning( __METHOD__
. ": " .
1021 "{$this->connsOpened}+ connections made (master=$masterName)" );
1024 $server['srvCache'] = $this->srvCache
;
1025 // Set loggers and profilers
1026 $server['connLogger'] = $this->connLogger
;
1027 $server['queryLogger'] = $this->queryLogger
;
1028 $server['errorLogger'] = $this->errorLogger
;
1029 $server['profiler'] = $this->profiler
;
1030 $server['trxProfiler'] = $this->trxProfiler
;
1031 // Use the same agent and PHP mode for all DB handles
1032 $server['cliMode'] = $this->cliMode
;
1033 $server['agent'] = $this->agent
;
1034 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1035 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1036 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1038 // Create a live connection object
1040 $db = Database
::factory( $server['type'], $server );
1041 } catch ( DBConnectionError
$e ) {
1042 // FIXME: This is probably the ugliest thing I have ever done to
1043 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1047 $db->setLBInfo( $server );
1048 $db->setLazyMasterHandle(
1049 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1051 $db->setTableAliases( $this->tableAliases
);
1053 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1054 if ( $this->trxRoundId
!== false ) {
1055 $this->applyTransactionRoundFlags( $db );
1057 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1058 $db->setTransactionListener( $name, $callback );
1066 * @throws DBConnectionError
1068 private function reportConnectionError() {
1069 $conn = $this->errorConnection
; // the connection which caused the error
1071 'method' => __METHOD__
,
1072 'last_error' => $this->mLastError
,
1075 if ( $conn instanceof IDatabase
) {
1076 $context['db_server'] = $conn->getServer();
1077 $this->connLogger
->warning(
1078 "Connection error: {last_error} ({db_server})",
1082 // throws DBConnectionError
1083 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1085 // No last connection, probably due to all servers being too busy
1086 $this->connLogger
->error(
1087 "LB failure with no last connection. Connection error: {last_error}",
1091 // If all servers were busy, mLastError will contain something sensible
1092 throw new DBConnectionError( null, $this->mLastError
);
1096 public function getWriterIndex() {
1100 public function haveIndex( $i ) {
1101 return array_key_exists( $i, $this->mServers
);
1104 public function isNonZeroLoad( $i ) {
1105 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1108 public function getServerCount() {
1109 return count( $this->mServers
);
1112 public function getServerName( $i ) {
1113 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1114 $name = $this->mServers
[$i]['hostName'];
1115 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1116 $name = $this->mServers
[$i]['host'];
1121 return ( $name != '' ) ?
$name : 'localhost';
1124 public function getServerType( $i ) {
1125 return isset( $this->mServers
[$i]['type'] ) ?
$this->mServers
[$i]['type'] : 'unknown';
1128 public function getMasterPos() {
1129 # If this entire request was served from a replica DB without opening a connection to the
1130 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1131 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1132 if ( !$masterConn ) {
1133 $serverCount = count( $this->mServers
);
1134 for ( $i = 1; $i < $serverCount; $i++
) {
1135 $conn = $this->getAnyOpenConnection( $i );
1137 return $conn->getReplicaPos();
1141 return $masterConn->getMasterPos();
1147 public function disable() {
1149 $this->disabled
= true;
1152 public function closeAll() {
1153 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1154 $host = $conn->getServer();
1155 $this->connLogger
->debug( "Closing connection to database '$host'." );
1160 self
::KEY_LOCAL
=> [],
1161 self
::KEY_FOREIGN_INUSE
=> [],
1162 self
::KEY_FOREIGN_FREE
=> [],
1163 self
::KEY_LOCAL_NOROUND
=> [],
1164 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1165 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1167 $this->connsOpened
= 0;
1170 public function closeConnection( IDatabase
$conn ) {
1171 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1172 foreach ( $this->mConns
as $type => $connsByServer ) {
1173 if ( !isset( $connsByServer[$serverIndex] ) ) {
1177 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1178 if ( $conn === $trackedConn ) {
1179 $host = $this->getServerName( $i );
1180 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1181 unset( $this->mConns
[$type][$serverIndex][$i] );
1182 --$this->connsOpened
;
1191 public function commitAll( $fname = __METHOD__
) {
1194 $restore = ( $this->trxRoundId
!== false );
1195 $this->trxRoundId
= false;
1196 $this->forEachOpenConnection(
1197 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1199 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1200 } catch ( DBError
$e ) {
1201 call_user_func( $this->errorLogger
, $e );
1202 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1204 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1205 $this->undoTransactionRoundFlags( $conn );
1211 throw new DBExpectedError(
1213 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1218 public function finalizeMasterChanges() {
1219 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1220 // Any error should cause all DB transactions to be rolled back together
1221 $conn->setTrxEndCallbackSuppression( false );
1222 $conn->runOnTransactionPreCommitCallbacks();
1223 // Defer post-commit callbacks until COMMIT finishes for all DBs
1224 $conn->setTrxEndCallbackSuppression( true );
1228 public function approveMasterChanges( array $options ) {
1229 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1230 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1231 // If atomic sections or explicit transactions are still open, some caller must have
1232 // caught an exception but failed to properly rollback any changes. Detect that and
1233 // throw and error (causing rollback).
1234 if ( $conn->explicitTrxActive() ) {
1235 throw new DBTransactionError(
1237 "Explicit transaction still active. A caller may have caught an error."
1240 // Assert that the time to replicate the transaction will be sane.
1241 // If this fails, then all DB transactions will be rollback back together.
1242 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1243 if ( $limit > 0 && $time > $limit ) {
1244 throw new DBTransactionSizeError(
1246 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1250 // If a connection sits idle while slow queries execute on another, that connection
1251 // may end up dropped before the commit round is reached. Ping servers to detect this.
1252 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1253 throw new DBTransactionError(
1255 "A connection to the {$conn->getDBname()} database was lost before commit."
1261 public function beginMasterChanges( $fname = __METHOD__
) {
1262 if ( $this->trxRoundId
!== false ) {
1263 throw new DBTransactionError(
1265 "$fname: Transaction round '{$this->trxRoundId}' already started."
1268 $this->trxRoundId
= $fname;
1271 $this->forEachOpenMasterConnection(
1272 function ( Database
$conn ) use ( $fname, &$failures ) {
1273 $conn->setTrxEndCallbackSuppression( true );
1275 $conn->flushSnapshot( $fname );
1276 } catch ( DBError
$e ) {
1277 call_user_func( $this->errorLogger
, $e );
1278 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1280 $conn->setTrxEndCallbackSuppression( false );
1281 $this->applyTransactionRoundFlags( $conn );
1286 throw new DBExpectedError(
1288 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1293 public function commitMasterChanges( $fname = __METHOD__
) {
1296 /** @noinspection PhpUnusedLocalVariableInspection */
1297 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1299 $restore = ( $this->trxRoundId
!== false );
1300 $this->trxRoundId
= false;
1301 $this->forEachOpenMasterConnection(
1302 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1304 if ( $conn->writesOrCallbacksPending() ) {
1305 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1306 } elseif ( $restore ) {
1307 $conn->flushSnapshot( $fname );
1309 } catch ( DBError
$e ) {
1310 call_user_func( $this->errorLogger
, $e );
1311 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1314 $this->undoTransactionRoundFlags( $conn );
1320 throw new DBExpectedError(
1322 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1327 public function runMasterPostTrxCallbacks( $type ) {
1328 $e = null; // first exception
1329 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1330 $conn->setTrxEndCallbackSuppression( false );
1331 if ( $conn->writesOrCallbacksPending() ) {
1332 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1333 // (which finished its callbacks already). Warn and recover in this case. Let the
1334 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1335 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1337 } elseif ( $conn->trxLevel() ) {
1338 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1339 // thus leaving an implicit read-only transaction open at this point. It
1340 // also happens if onTransactionIdle() callbacks leave implicit transactions
1341 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1342 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1346 $conn->runOnTransactionIdleCallbacks( $type );
1347 } catch ( Exception
$ex ) {
1351 $conn->runTransactionListenerCallbacks( $type );
1352 } catch ( Exception
$ex ) {
1360 public function rollbackMasterChanges( $fname = __METHOD__
) {
1361 $restore = ( $this->trxRoundId
!== false );
1362 $this->trxRoundId
= false;
1363 $this->forEachOpenMasterConnection(
1364 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1365 if ( $conn->writesOrCallbacksPending() ) {
1366 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1369 $this->undoTransactionRoundFlags( $conn );
1375 public function suppressTransactionEndCallbacks() {
1376 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1377 $conn->setTrxEndCallbackSuppression( true );
1382 * @param IDatabase $conn
1384 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1385 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1386 return; // transaction rounds do not apply to these connections
1389 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1390 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1391 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1392 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1393 // If config has explicitly requested DBO_TRX be either on or off by not
1394 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1395 // for things like blob stores (ExternalStore) which want auto-commit mode.
1400 * @param IDatabase $conn
1402 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1403 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1404 return; // transaction rounds do not apply to these connections
1407 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1408 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1412 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1413 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1414 $conn->flushSnapshot( __METHOD__
);
1418 public function hasMasterConnection() {
1419 return $this->isOpen( $this->getWriterIndex() );
1422 public function hasMasterChanges() {
1424 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1425 $pending |
= $conn->writesOrCallbacksPending();
1428 return (bool)$pending;
1431 public function lastMasterChangeTimestamp() {
1433 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1434 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1440 public function hasOrMadeRecentMasterChanges( $age = null ) {
1441 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1443 return ( $this->hasMasterChanges()
1444 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1447 public function pendingMasterChangeCallers() {
1449 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1450 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1456 public function getLaggedReplicaMode( $domain = false ) {
1457 // No-op if there is only one DB (also avoids recursion)
1458 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1460 // See if laggedReplicaMode gets set
1461 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1462 $this->reuseConnection( $conn );
1463 } catch ( DBConnectionError
$e ) {
1464 // Avoid expensive re-connect attempts and failures
1465 $this->allReplicasDownMode
= true;
1466 $this->laggedReplicaMode
= true;
1470 return $this->laggedReplicaMode
;
1474 * @param bool $domain
1476 * @deprecated 1.28; use getLaggedReplicaMode()
1478 public function getLaggedSlaveMode( $domain = false ) {
1479 return $this->getLaggedReplicaMode( $domain );
1482 public function laggedReplicaUsed() {
1483 return $this->laggedReplicaMode
;
1489 * @deprecated Since 1.28; use laggedReplicaUsed()
1491 public function laggedSlaveUsed() {
1492 return $this->laggedReplicaUsed();
1495 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1496 if ( $this->readOnlyReason
!== false ) {
1497 return $this->readOnlyReason
;
1498 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1499 if ( $this->allReplicasDownMode
) {
1500 return 'The database has been automatically locked ' .
1501 'until the replica database servers become available';
1503 return 'The database has been automatically locked ' .
1504 'while the replica database servers catch up to the master.';
1506 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1507 return 'The database master is running in read-only mode.';
1514 * @param string $domain Domain ID, or false for the current domain
1515 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1518 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1519 $cache = $this->wanCache
;
1520 $masterServer = $this->getServerName( $this->getWriterIndex() );
1522 return (bool)$cache->getWithSetCallback(
1523 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1524 self
::TTL_CACHE_READONLY
,
1525 function () use ( $domain, $conn ) {
1526 $old = $this->trxProfiler
->setSilenced( true );
1528 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1529 $readOnly = (int)$dbw->serverIsReadOnly();
1531 $this->reuseConnection( $dbw );
1533 } catch ( DBError
$e ) {
1536 $this->trxProfiler
->setSilenced( $old );
1539 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1543 public function allowLagged( $mode = null ) {
1544 if ( $mode === null ) {
1545 return $this->mAllowLagged
;
1547 $this->mAllowLagged
= $mode;
1549 return $this->mAllowLagged
;
1552 public function pingAll() {
1554 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1555 if ( !$conn->ping() ) {
1563 public function forEachOpenConnection( $callback, array $params = [] ) {
1564 foreach ( $this->mConns
as $connsByServer ) {
1565 foreach ( $connsByServer as $serverConns ) {
1566 foreach ( $serverConns as $conn ) {
1567 $mergedParams = array_merge( [ $conn ], $params );
1568 call_user_func_array( $callback, $mergedParams );
1574 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1575 $masterIndex = $this->getWriterIndex();
1576 foreach ( $this->mConns
as $connsByServer ) {
1577 if ( isset( $connsByServer[$masterIndex] ) ) {
1578 /** @var IDatabase $conn */
1579 foreach ( $connsByServer[$masterIndex] as $conn ) {
1580 $mergedParams = array_merge( [ $conn ], $params );
1581 call_user_func_array( $callback, $mergedParams );
1587 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1588 foreach ( $this->mConns
as $connsByServer ) {
1589 foreach ( $connsByServer as $i => $serverConns ) {
1590 if ( $i === $this->getWriterIndex() ) {
1591 continue; // skip master
1593 foreach ( $serverConns as $conn ) {
1594 $mergedParams = array_merge( [ $conn ], $params );
1595 call_user_func_array( $callback, $mergedParams );
1601 public function getMaxLag( $domain = false ) {
1606 if ( $this->getServerCount() <= 1 ) {
1607 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1610 $lagTimes = $this->getLagTimes( $domain );
1611 foreach ( $lagTimes as $i => $lag ) {
1612 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1614 $host = $this->mServers
[$i]['host'];
1619 return [ $host, $maxLag, $maxIndex ];
1622 public function getLagTimes( $domain = false ) {
1623 if ( $this->getServerCount() <= 1 ) {
1624 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1627 $knownLagTimes = []; // map of (server index => 0 seconds)
1628 $indexesWithLag = [];
1629 foreach ( $this->mServers
as $i => $server ) {
1630 if ( empty( $server['is static'] ) ) {
1631 $indexesWithLag[] = $i; // DB server might have replication lag
1633 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1637 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1640 public function safeGetLag( IDatabase
$conn ) {
1641 if ( $this->getServerCount() <= 1 ) {
1644 return $conn->getLag();
1649 * @param IDatabase $conn
1650 * @param DBMasterPos|bool $pos
1651 * @param int $timeout
1654 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1655 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1656 return true; // server is not a replica DB
1660 // Get the current master position, opening a connection if needed
1661 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1662 if ( $masterConn ) {
1663 $pos = $masterConn->getMasterPos();
1665 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1666 $pos = $masterConn->getMasterPos();
1667 $this->closeConnection( $masterConn );
1671 if ( $pos instanceof DBMasterPos
) {
1672 $result = $conn->masterPosWait( $pos, $timeout );
1673 if ( $result == -1 ||
is_null( $result ) ) {
1674 $msg = __METHOD__
. ': Timed out waiting on {host} pos {pos}';
1675 $this->replLogger
->warning( $msg, [
1676 'host' => $conn->getServer(),
1678 'trace' => ( new RuntimeException() )->getTraceAsString()
1682 $this->replLogger
->info( __METHOD__
. ': Done' );
1686 $ok = false; // something is misconfigured
1687 $this->replLogger
->error(
1688 __METHOD__
. ': could not get master pos for {host}',
1690 'host' => $conn->getServer(),
1691 'trace' => ( new RuntimeException() )->getTraceAsString()
1699 public function setTransactionListener( $name, callable
$callback = null ) {
1701 $this->trxRecurringCallbacks
[$name] = $callback;
1703 unset( $this->trxRecurringCallbacks
[$name] );
1705 $this->forEachOpenMasterConnection(
1706 function ( IDatabase
$conn ) use ( $name, $callback ) {
1707 $conn->setTransactionListener( $name, $callback );
1712 public function setTableAliases( array $aliases ) {
1713 $this->tableAliases
= $aliases;
1716 public function setDomainPrefix( $prefix ) {
1717 // Find connections to explicit foreign domains still marked as in-use...
1719 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1720 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1721 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1722 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1723 $domainsInUse[] = $conn->getDomainID();
1727 // Do not switch connections to explicit foreign domains unless marked as safe
1728 if ( $domainsInUse ) {
1729 $domains = implode( ', ', $domainsInUse );
1730 throw new DBUnexpectedError( null,
1731 "Foreign domain connections are still in use ($domains)." );
1734 $oldDomain = $this->localDomain
->getId();
1735 $this->setLocalDomain( new DatabaseDomain(
1736 $this->localDomain
->getDatabase(),
1737 $this->localDomain
->getSchema(),
1741 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1742 if ( !$db->getLBInfo( 'foreign' ) ) {
1743 $db->tablePrefix( $prefix );
1749 * @param DatabaseDomain $domain
1751 private function setLocalDomain( DatabaseDomain
$domain ) {
1752 $this->localDomain
= $domain;
1753 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1754 // always true, gracefully handle the case when they fail to account for escaping.
1755 if ( $this->localDomain
->getTablePrefix() != '' ) {
1756 $this->localDomainIdAlias
=
1757 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1759 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1764 * Make PHP ignore user aborts/disconnects until the returned
1765 * value leaves scope. This returns null and does nothing in CLI mode.
1767 * @return ScopedCallback|null
1769 final protected function getScopedPHPBehaviorForCommit() {
1770 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1771 $old = ignore_user_abort( true ); // avoid half-finished operations
1772 return new ScopedCallback( function () use ( $old ) {
1773 ignore_user_abort( $old );
1780 function __destruct() {
1781 // Avoid connection leaks for sanity
1786 class_alias( LoadBalancer
::class, 'LoadBalancer' );