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 */
51 /** @var int Seconds to spend waiting on replica DB lag to resolve */
53 /** @var array The LoadMonitor configuration */
54 private $loadMonitorConfig;
55 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
56 private $tableAliases = [];
57 /** @var string[] Map of (index alias => index) */
58 private $indexAliases = [];
60 /** @var ILoadMonitor */
62 /** @var ChronologyProtector|null */
66 /** @var WANObjectCache */
68 /** @var object|string Class name or object With profileIn/profileOut methods */
70 /** @var TransactionProfiler */
71 protected $trxProfiler;
72 /** @var LoggerInterface */
73 protected $replLogger;
74 /** @var LoggerInterface */
75 protected $connLogger;
76 /** @var LoggerInterface */
77 protected $queryLogger;
78 /** @var LoggerInterface */
79 protected $perfLogger;
81 /** @var Database DB connection object that caused a problem */
82 private $errorConnection;
83 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
85 /** @var bool|DBMasterPos False if not set */
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $laggedReplicaMode = false;
89 /** @var bool Whether the generic reader fell back to a lagged replica DB */
90 private $allReplicasDownMode = false;
91 /** @var string The last DB selection or connection error */
92 private $lastError = 'Unknown error';
93 /** @var string|bool Reason the LB is read-only or false if not */
94 private $readOnlyReason = false;
95 /** @var int Total connections opened */
96 private $connsOpened = 0;
97 /** @var string|bool String if a requested DBO_TRX transaction round is active */
98 private $trxRoundId = false;
99 /** @var array[] Map of (name => callable) */
100 private $trxRecurringCallbacks = [];
101 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
102 private $localDomain;
103 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
104 private $localDomainIdAlias;
105 /** @var string Current server name */
107 /** @var bool Whether this PHP instance is for a CLI script */
109 /** @var string Agent name for query profiling */
112 /** @var callable Exception logger */
113 private $errorLogger;
114 /** @var callable Deprecation logger */
115 private $deprecationLogger;
118 private $disabled = false;
120 private $chronProtInitialized = false;
122 private $maxLag = self
::MAX_LAG_DEFAULT
;
124 /** @var int Warn when this many connection are held */
125 const CONN_HELD_WARN_THRESHOLD
= 10;
127 /** @var int Default 'maxLag' when unspecified */
128 const MAX_LAG_DEFAULT
= 10;
129 /** @var int Default 'waitTimeout' when unspecified */
130 const MAX_WAIT_DEFAULT
= 10;
131 /** @var int Seconds to cache master server read-only status */
132 const TTL_CACHE_READONLY
= 5;
134 const KEY_LOCAL
= 'local';
135 const KEY_FOREIGN_FREE
= 'foreignFree';
136 const KEY_FOREIGN_INUSE
= 'foreignInUse';
138 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
139 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
140 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
142 public function __construct( array $params ) {
143 if ( !isset( $params['servers'] ) ) {
144 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
146 $this->servers
= $params['servers'];
147 foreach ( $this->servers
as $i => $server ) {
149 $this->servers
[$i]['master'] = true;
151 $this->servers
[$i]['replica'] = true;
155 $localDomain = isset( $params['localDomain'] )
156 ? DatabaseDomain
::newFromId( $params['localDomain'] )
157 : DatabaseDomain
::newUnspecified();
158 $this->setLocalDomain( $localDomain );
160 $this->waitTimeout
= isset( $params['waitTimeout'] )
161 ?
$params['waitTimeout']
162 : self
::MAX_WAIT_DEFAULT
;
164 $this->readIndex
= -1;
166 // Connection were transaction rounds may be applied
167 self
::KEY_LOCAL
=> [],
168 self
::KEY_FOREIGN_INUSE
=> [],
169 self
::KEY_FOREIGN_FREE
=> [],
170 // Auto-committing counterpart connections that ignore transaction rounds
171 self
::KEY_LOCAL_NOROUND
=> [],
172 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
173 self
::KEY_FOREIGN_FREE_NOROUND
=> []
176 $this->waitForPos
= false;
177 $this->allowLagged
= false;
179 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
180 $this->readOnlyReason
= $params['readOnlyReason'];
183 if ( isset( $params['maxLag'] ) ) {
184 $this->maxLag
= $params['maxLag'];
187 if ( isset( $params['loadMonitor'] ) ) {
188 $this->loadMonitorConfig
= $params['loadMonitor'];
190 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
192 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
194 foreach ( $params['servers'] as $i => $server ) {
195 $this->loads
[$i] = $server['load'];
196 if ( isset( $server['groupLoads'] ) ) {
197 foreach ( $server['groupLoads'] as $group => $ratio ) {
198 if ( !isset( $this->groupLoads
[$group] ) ) {
199 $this->groupLoads
[$group] = [];
201 $this->groupLoads
[$group][$i] = $ratio;
206 if ( isset( $params['srvCache'] ) ) {
207 $this->srvCache
= $params['srvCache'];
209 $this->srvCache
= new EmptyBagOStuff();
211 if ( isset( $params['wanCache'] ) ) {
212 $this->wanCache
= $params['wanCache'];
214 $this->wanCache
= WANObjectCache
::newEmpty();
216 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
217 if ( isset( $params['trxProfiler'] ) ) {
218 $this->trxProfiler
= $params['trxProfiler'];
220 $this->trxProfiler
= new TransactionProfiler();
223 $this->errorLogger
= isset( $params['errorLogger'] )
224 ?
$params['errorLogger']
225 : function ( Exception
$e ) {
226 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
228 $this->deprecationLogger
= isset( $params['deprecationLogger'] )
229 ?
$params['deprecationLogger']
230 : function ( $msg ) {
231 trigger_error( $msg, E_USER_DEPRECATED
);
234 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
235 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
238 $this->host
= isset( $params['hostname'] )
239 ?
$params['hostname']
240 : ( gethostname() ?
: 'unknown' );
241 $this->cliMode
= isset( $params['cliMode'] )
243 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
244 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
246 if ( isset( $params['chronologyProtector'] ) ) {
247 $this->chronProt
= $params['chronologyProtector'];
252 * Get the local (and default) database domain ID of connection handles
254 * @see DatabaseDomain
255 * @return string Database domain ID; this specifies DB name, schema, and table prefix
258 public function getLocalDomainID() {
259 return $this->localDomain
->getId();
263 * Get a LoadMonitor instance
265 * @return ILoadMonitor
267 private function getLoadMonitor() {
268 if ( !isset( $this->loadMonitor
) ) {
270 'LoadMonitor' => LoadMonitor
::class,
271 'LoadMonitorNull' => LoadMonitorNull
::class,
272 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
275 $class = $this->loadMonitorConfig
['class'];
276 if ( isset( $compat[$class] ) ) {
277 $class = $compat[$class];
280 $this->loadMonitor
= new $class(
281 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
282 $this->loadMonitor
->setLogger( $this->replLogger
);
285 return $this->loadMonitor
;
289 * @param array $loads
290 * @param bool|string $domain Domain to get non-lagged for
291 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
292 * @return bool|int|string
294 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
295 $lags = $this->getLagTimes( $domain );
297 # Unset excessively lagged servers
298 foreach ( $lags as $i => $lag ) {
300 # How much lag this server nominally is allowed to have
301 $maxServerLag = isset( $this->servers
[$i]['max lag'] )
302 ?
$this->servers
[$i]['max lag']
303 : $this->maxLag
; // default
304 # Constrain that futher by $maxLag argument
305 $maxServerLag = min( $maxServerLag, $maxLag );
307 $host = $this->getServerName( $i );
308 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
309 $this->replLogger
->error(
311 ": server {host} is not replicating?", [ 'host' => $host ] );
313 } elseif ( $lag > $maxServerLag ) {
314 $this->replLogger
->info(
316 ": server {host} has {lag} seconds of lag (>= {maxlag})",
317 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
324 # Find out if all the replica DBs with non-zero load are lagged
326 foreach ( $loads as $load ) {
330 # No appropriate DB servers except maybe the master and some replica DBs with zero load
331 # Do NOT use the master
332 # Instead, this function will return false, triggering read-only mode,
333 # and a lagged replica DB will be used instead.
337 if ( count( $loads ) == 0 ) {
341 # Return a random representative of the remainder
342 return ArrayUtils
::pickRandom( $loads );
345 public function getReaderIndex( $group = false, $domain = false ) {
346 if ( count( $this->servers
) == 1 ) {
347 // Skip the load balancing if there's only one server
348 return $this->getWriterIndex();
349 } elseif ( $group === false && $this->readIndex
>= 0 ) {
350 // Shortcut if the generic reader index was already cached
351 return $this->readIndex
;
354 if ( $group !== false ) {
355 // Use the server weight array for this load group
356 if ( isset( $this->groupLoads
[$group] ) ) {
357 $loads = $this->groupLoads
[$group];
359 // No loads for this group, return false and the caller can use some other group
360 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
365 // Use the generic load group
366 $loads = $this->loads
;
369 // Scale the configured load ratios according to each server's load and state
370 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
372 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
373 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
374 if ( $i === false ) {
375 // Replica DB connection unsuccessful
379 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
380 // Before any data queries are run, wait for the server to catch up to the
381 // specified position. This is used to improve session consistency. Note that
382 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
383 // so update laggedReplicaMode as needed for consistency.
384 if ( !$this->doWait( $i ) ) {
385 $laggedReplicaMode = true;
389 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
390 // Cache the generic reader index for future ungrouped DB_REPLICA handles
391 $this->readIndex
= $i;
392 // Record if the generic reader index is in "lagged replica DB" mode
393 if ( $laggedReplicaMode ) {
394 $this->laggedReplicaMode
= true;
398 $serverName = $this->getServerName( $i );
399 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
405 * @param array $loads List of server weights
406 * @param string|bool $domain
407 * @return array (reader index, lagged replica mode) or false on failure
409 private function pickReaderIndex( array $loads, $domain = false ) {
410 if ( !count( $loads ) ) {
411 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
414 /** @var int|bool $i Index of selected server */
416 /** @var bool $laggedReplicaMode Whether server is considered lagged */
417 $laggedReplicaMode = false;
419 // Quickly look through the available servers for a server that meets criteria...
420 $currentLoads = $loads;
421 while ( count( $currentLoads ) ) {
422 if ( $this->allowLagged ||
$laggedReplicaMode ) {
423 $i = ArrayUtils
::pickRandom( $currentLoads );
426 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
427 // ChronologyProtecter sets "waitForPos" for session consistency.
428 // This triggers doWait() after connect, so it's especially good to
429 // avoid lagged servers so as to avoid excessive delay in that method.
430 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
431 // Aim for <= 1 second of waiting (being too picky can backfire)
432 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
434 if ( $i === false ) {
435 // Any server with less lag than it's 'max lag' param is preferable
436 $i = $this->getRandomNonLagged( $currentLoads, $domain );
438 if ( $i === false && count( $currentLoads ) != 0 ) {
439 // All replica DBs lagged. Switch to read-only mode
440 $this->replLogger
->error(
441 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
442 $i = ArrayUtils
::pickRandom( $currentLoads );
443 $laggedReplicaMode = true;
447 if ( $i === false ) {
448 // pickRandom() returned false.
449 // This is permanent and means the configuration or the load monitor
450 // wants us to return false.
451 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
453 return [ false, false ];
456 $serverName = $this->getServerName( $i );
457 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
459 $conn = $this->openConnection( $i, $domain );
461 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
462 unset( $currentLoads[$i] ); // avoid this server next iteration
467 // Decrement reference counter, we are finished with this connection.
468 // It will be incremented for the caller later.
469 if ( $domain !== false ) {
470 $this->reuseConnection( $conn );
473 // Return this server
477 // If all servers were down, quit now
478 if ( !count( $currentLoads ) ) {
479 $this->connLogger
->error( __METHOD__
. ": all servers down" );
482 return [ $i, $laggedReplicaMode ];
485 public function waitFor( $pos ) {
486 $oldPos = $this->waitForPos
;
488 $this->waitForPos
= $pos;
489 // If a generic reader connection was already established, then wait now
490 $i = $this->readIndex
;
492 if ( !$this->doWait( $i ) ) {
493 $this->laggedReplicaMode
= true;
497 // Restore the older position if it was higher since this is used for lag-protection
498 $this->setWaitForPositionIfHigher( $oldPos );
502 public function waitForOne( $pos, $timeout = null ) {
503 $oldPos = $this->waitForPos
;
505 $this->waitForPos
= $pos;
507 $i = $this->readIndex
;
509 // Pick a generic replica DB if there isn't one yet
510 $readLoads = $this->loads
;
511 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
512 $readLoads = array_filter( $readLoads ); // with non-zero load
513 $i = ArrayUtils
::pickRandom( $readLoads );
517 $ok = $this->doWait( $i, true, $timeout );
519 $ok = true; // no applicable loads
522 # Restore the old position, as this is not used for lag-protection but for throttling
523 $this->waitForPos
= $oldPos;
529 public function waitForAll( $pos, $timeout = null ) {
530 $timeout = $timeout ?
: $this->waitTimeout
;
532 $oldPos = $this->waitForPos
;
534 $this->waitForPos
= $pos;
535 $serverCount = count( $this->servers
);
538 for ( $i = 1; $i < $serverCount; $i++
) {
539 if ( $this->loads
[$i] > 0 ) {
540 $start = microtime( true );
541 $ok = $this->doWait( $i, true, $timeout ) && $ok;
542 $timeout -= intval( microtime( true ) - $start );
543 if ( $timeout <= 0 ) {
544 break; // timeout reached
549 # Restore the old position, as this is not used for lag-protection but for throttling
550 $this->waitForPos
= $oldPos;
557 * @param DBMasterPos|bool $pos
559 private function setWaitForPositionIfHigher( $pos ) {
564 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
565 $this->waitForPos
= $pos;
569 public function getAnyOpenConnection( $i, $flags = 0 ) {
570 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
571 foreach ( $this->conns
as $connsByServer ) {
572 if ( !isset( $connsByServer[$i] ) ) {
576 foreach ( $connsByServer[$i] as $conn ) {
577 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
587 * Wait for a given replica DB to catch up to the master pos stored in $this
588 * @param int $index Server index
589 * @param bool $open Check the server even if a new connection has to be made
590 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
593 protected function doWait( $index, $open = false, $timeout = null ) {
594 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
596 // Check if we already know that the DB has reached this point
597 $server = $this->getServerName( $index );
598 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
599 /** @var DBMasterPos $knownReachedPos */
600 $knownReachedPos = $this->srvCache
->get( $key );
602 $knownReachedPos instanceof DBMasterPos
&&
603 $knownReachedPos->hasReached( $this->waitForPos
)
605 $this->replLogger
->debug(
607 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
608 [ 'dbserver' => $server ]
613 // Find a connection to wait on, creating one if needed and allowed
614 $close = false; // close the connection afterwards
615 $conn = $this->getAnyOpenConnection( $index );
618 $this->replLogger
->debug(
619 __METHOD__
. ': no connection open for {dbserver}',
620 [ 'dbserver' => $server ]
625 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
627 $this->replLogger
->warning(
628 __METHOD__
. ': failed to connect to {dbserver}',
629 [ 'dbserver' => $server ]
634 // Avoid connection spam in waitForAll() when connections
635 // are made just for the sake of doing this lag check.
640 $this->replLogger
->info(
642 ': waiting for replica DB {dbserver} to catch up...',
643 [ 'dbserver' => $server ]
646 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
648 if ( $result === null ) {
649 $this->replLogger
->warning(
650 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
653 'pos' => $this->waitForPos
,
654 'trace' => ( new RuntimeException() )->getTraceAsString()
658 } elseif ( $result == -1 ) {
659 $this->replLogger
->warning(
660 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
663 'pos' => $this->waitForPos
,
664 'trace' => ( new RuntimeException() )->getTraceAsString()
669 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
671 // Remember that the DB reached this point
672 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
676 $this->closeConnection( $conn );
682 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
683 if ( $i === null ||
$i === false ) {
684 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
685 ' with invalid server index' );
688 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
689 $domain = false; // local connection requested
692 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
693 // Assuming all servers are of the same type (or similar), which is overwhelmingly
694 // the case, use the master server information to get the attributes. The information
695 // for $i cannot be used since it might be DB_REPLICA, which might require connection
696 // attempts in order to be resolved into a real server index.
697 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
698 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
699 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
700 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
701 // to reduce lock contention. None of these apply for sqlite and using separate
702 // connections just causes self-deadlocks.
703 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
704 $this->connLogger
->info( __METHOD__
.
705 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
709 $groups = ( $groups === false ||
$groups === [] )
710 ?
[ false ] // check one "group": the generic pool
713 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
714 $oldConnsOpened = $this->connsOpened
; // connections open now
716 if ( $i == self
::DB_MASTER
) {
717 $i = $this->getWriterIndex();
718 } elseif ( $i == self
::DB_REPLICA
) {
719 # Try to find an available server in any the query groups (in order)
720 foreach ( $groups as $group ) {
721 $groupIndex = $this->getReaderIndex( $group, $domain );
722 if ( $groupIndex !== false ) {
729 # Operation-based index
730 if ( $i == self
::DB_REPLICA
) {
731 $this->lastError
= 'Unknown error'; // reset error string
732 # Try the general server pool if $groups are unavailable.
733 $i = ( $groups === [ false ] )
734 ?
false // don't bother with this if that is what was tried above
735 : $this->getReaderIndex( false, $domain );
736 # Couldn't find a working server in getReaderIndex()?
737 if ( $i === false ) {
738 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
739 // Throw an exception
740 $this->reportConnectionError();
741 return null; // not reached
745 # Now we have an explicit index into the servers array
746 $conn = $this->openConnection( $i, $domain, $flags );
748 // Throw an exception
749 $this->reportConnectionError();
750 return null; // not reached
753 # Profile any new connections that happen
754 if ( $this->connsOpened
> $oldConnsOpened ) {
755 $host = $conn->getServer();
756 $dbname = $conn->getDBname();
757 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
761 # Make master-requested DB handles inherit any read-only mode setting
762 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
768 public function reuseConnection( IDatabase
$conn ) {
769 $serverIndex = $conn->getLBInfo( 'serverIndex' );
770 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
771 if ( $serverIndex === null ||
$refCount === null ) {
773 * This can happen in code like:
774 * foreach ( $dbs as $db ) {
775 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
777 * $lb->reuseConnection( $conn );
779 * When a connection to the local DB is opened in this way, reuseConnection()
783 } elseif ( $conn instanceof DBConnRef
) {
784 // DBConnRef already handles calling reuseConnection() and only passes the live
785 // Database instance to this method. Any caller passing in a DBConnRef is broken.
786 $this->connLogger
->error(
787 __METHOD__
. ": got DBConnRef instance.\n" .
788 ( new RuntimeException() )->getTraceAsString() );
793 if ( $this->disabled
) {
794 return; // DBConnRef handle probably survived longer than the LoadBalancer
797 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
798 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
799 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
801 $connFreeKey = self
::KEY_FOREIGN_FREE
;
802 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
805 $domain = $conn->getDomainID();
806 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
807 throw new InvalidArgumentException( __METHOD__
.
808 ": connection $serverIndex/$domain not found; it may have already been freed." );
809 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
810 throw new InvalidArgumentException( __METHOD__
.
811 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
814 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
815 if ( $refCount <= 0 ) {
816 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
817 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
818 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
819 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
821 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
823 $this->connLogger
->debug( __METHOD__
.
824 ": reference count for $serverIndex/$domain reduced to $refCount" );
828 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
829 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
831 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
834 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
835 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
837 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
840 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
841 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
843 return new MaintainableDBConnRef(
844 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
847 public function openConnection( $i, $domain = false, $flags = 0 ) {
848 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
849 $domain = false; // local connection requested
852 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
853 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
854 // Load CP positions before connecting so that doWait() triggers later if needed
855 $this->chronProtInitialized
= true;
856 $this->chronProt
->initLB( $this );
859 // Check if an auto-commit connection is being requested. If so, it will not reuse the
860 // main set of DB connections but rather its own pool since:
861 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
862 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
863 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
865 if ( $domain !== false ) {
866 // Connection is to a foreign domain
867 $conn = $this->openForeignConnection( $i, $domain, $flags );
869 // Connection is to the local domain
870 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
871 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
872 $conn = $this->conns
[$connKey][$i][0];
874 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
875 throw new InvalidArgumentException( "No server with index '$i'." );
877 // Open a new connection
878 $server = $this->servers
[$i];
879 $server['serverIndex'] = $i;
880 $server['autoCommitOnly'] = $autoCommit;
881 if ( $this->localDomain
->getDatabase() !== null ) {
882 // Use the local domain table prefix if the local domain is specified
883 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
885 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
886 $host = $this->getServerName( $i );
887 if ( $conn->isOpen() ) {
888 $this->connLogger
->debug(
889 __METHOD__
. ": connected to database $i at '$host'." );
890 $this->conns
[$connKey][$i][0] = $conn;
892 $this->connLogger
->warning(
893 __METHOD__
. ": failed to connect to database $i at '$host'." );
894 $this->errorConnection
= $conn;
900 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
901 // Connection was made but later unrecoverably lost for some reason.
902 // Do not return a handle that will just throw exceptions on use,
903 // but let the calling code (e.g. getReaderIndex) try another server.
904 // See DatabaseMyslBase::ping() for how this can happen.
905 $this->errorConnection
= $conn;
909 if ( $autoCommit && $conn instanceof IDatabase
) {
910 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
917 * Open a connection to a foreign DB, or return one if it is already open.
919 * Increments a reference count on the returned connection which locks the
920 * connection to the requested domain. This reference count can be
921 * decremented by calling reuseConnection().
923 * If a connection is open to the appropriate server already, but with the wrong
924 * database, it will be switched to the right database and returned, as long as
925 * it has been freed first with reuseConnection().
927 * On error, returns false, and the connection which caused the
928 * error will be available via $this->errorConnection.
930 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
932 * @param int $i Server index
933 * @param string $domain Domain ID to open
934 * @param int $flags Class CONN_* constant bitfield
937 private function openForeignConnection( $i, $domain, $flags = 0 ) {
938 $domainInstance = DatabaseDomain
::newFromId( $domain );
939 $dbName = $domainInstance->getDatabase();
940 $prefix = $domainInstance->getTablePrefix();
941 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
944 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
945 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
947 $connFreeKey = self
::KEY_FOREIGN_FREE
;
948 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
951 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
952 // Reuse an in-use connection for the same domain
953 $conn = $this->conns
[$connInUseKey][$i][$domain];
954 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
955 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
956 // Reuse a free connection for the same domain
957 $conn = $this->conns
[$connFreeKey][$i][$domain];
958 unset( $this->conns
[$connFreeKey][$i][$domain] );
959 $this->conns
[$connInUseKey][$i][$domain] = $conn;
960 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
961 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
962 // Reuse a free connection from another domain
963 $conn = reset( $this->conns
[$connFreeKey][$i] );
964 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
965 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
966 $this->lastError
= "Error selecting database '$dbName' on server " .
967 $conn->getServer() . " from client host {$this->host}";
968 $this->errorConnection
= $conn;
971 $conn->tablePrefix( $prefix );
972 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
973 // Note that if $domain is an empty string, getDomainID() might not match it
974 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
975 $this->connLogger
->debug( __METHOD__
.
976 ": reusing free connection from $oldDomain for $domain" );
979 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
980 throw new InvalidArgumentException( "No server with index '$i'." );
982 // Open a new connection
983 $server = $this->servers
[$i];
984 $server['serverIndex'] = $i;
985 $server['foreignPoolRefCount'] = 0;
986 $server['foreign'] = true;
987 $server['autoCommitOnly'] = $autoCommit;
988 $conn = $this->reallyOpenConnection( $server, $domainInstance );
989 if ( !$conn->isOpen() ) {
990 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
991 $this->errorConnection
= $conn;
994 $conn->tablePrefix( $prefix ); // as specified
995 // Note that if $domain is an empty string, getDomainID() might not match it
996 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
997 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1001 // Increment reference count
1002 if ( $conn instanceof IDatabase
) {
1003 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1004 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1010 public function getServerAttributes( $i ) {
1011 return Database
::attributesFromType(
1012 $this->getServerType( $i ),
1013 isset( $this->servers
[$i]['driver'] ) ?
$this->servers
[$i]['driver'] : null
1018 * Test if the specified index represents an open connection
1020 * @param int $index Server index
1024 private function isOpen( $index ) {
1025 if ( !is_int( $index ) ) {
1029 return (bool)$this->getAnyOpenConnection( $index );
1033 * Open a new network connection to a server (uncached)
1035 * Returns a Database object whether or not the connection was successful.
1037 * @param array $server
1038 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1040 * @throws DBAccessError
1041 * @throws InvalidArgumentException
1043 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1044 if ( $this->disabled
) {
1045 throw new DBAccessError();
1048 // Handle $domainOverride being a specified or an unspecified domain
1049 if ( $domainOverride->getDatabase() === null ) {
1050 // Normally, an RDBMS requires a DB name specified on connection and the $server
1051 // configuration array is assumed to already specify an appropriate DB name.
1052 if ( $server['type'] === 'mysql' ) {
1053 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1054 // and the DB name in $server might not exist due to legacy reasons (the default
1055 // domain used to ignore the local LB domain, even when mismatched).
1056 $server['dbname'] = null;
1059 $server['dbname'] = $domainOverride->getDatabase();
1060 $server['schema'] = $domainOverride->getSchema();
1063 // Let the handle know what the cluster master is (e.g. "db1052")
1064 $masterName = $this->getServerName( $this->getWriterIndex() );
1065 $server['clusterMasterHost'] = $masterName;
1067 // Log when many connection are made on requests
1068 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1069 $this->perfLogger
->warning( __METHOD__
. ": " .
1070 "{$this->connsOpened}+ connections made (master=$masterName)" );
1073 $server['srvCache'] = $this->srvCache
;
1074 // Set loggers and profilers
1075 $server['connLogger'] = $this->connLogger
;
1076 $server['queryLogger'] = $this->queryLogger
;
1077 $server['errorLogger'] = $this->errorLogger
;
1078 $server['deprecationLogger'] = $this->deprecationLogger
;
1079 $server['profiler'] = $this->profiler
;
1080 $server['trxProfiler'] = $this->trxProfiler
;
1081 // Use the same agent and PHP mode for all DB handles
1082 $server['cliMode'] = $this->cliMode
;
1083 $server['agent'] = $this->agent
;
1084 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1085 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1086 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1088 // Create a live connection object
1090 $db = Database
::factory( $server['type'], $server );
1091 } catch ( DBConnectionError
$e ) {
1092 // FIXME: This is probably the ugliest thing I have ever done to
1093 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1097 $db->setLBInfo( $server );
1098 $db->setLazyMasterHandle(
1099 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1101 $db->setTableAliases( $this->tableAliases
);
1102 $db->setIndexAliases( $this->indexAliases
);
1104 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1105 if ( $this->trxRoundId
!== false ) {
1106 $this->applyTransactionRoundFlags( $db );
1108 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1109 $db->setTransactionListener( $name, $callback );
1117 * @throws DBConnectionError
1119 private function reportConnectionError() {
1120 $conn = $this->errorConnection
; // the connection which caused the error
1122 'method' => __METHOD__
,
1123 'last_error' => $this->lastError
,
1126 if ( $conn instanceof IDatabase
) {
1127 $context['db_server'] = $conn->getServer();
1128 $this->connLogger
->warning(
1129 __METHOD__
. ": connection error: {last_error} ({db_server})",
1133 // throws DBConnectionError
1134 $conn->reportConnectionError( "{$this->lastError} ({$context['db_server']})" );
1136 // No last connection, probably due to all servers being too busy
1137 $this->connLogger
->error(
1139 ": LB failure with no last connection. Connection error: {last_error}",
1143 // If all servers were busy, "lastError" will contain something sensible
1144 throw new DBConnectionError( null, $this->lastError
);
1148 public function getWriterIndex() {
1152 public function haveIndex( $i ) {
1153 return array_key_exists( $i, $this->servers
);
1156 public function isNonZeroLoad( $i ) {
1157 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1160 public function getServerCount() {
1161 return count( $this->servers
);
1164 public function getServerName( $i ) {
1165 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1166 $name = $this->servers
[$i]['hostName'];
1167 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1168 $name = $this->servers
[$i]['host'];
1173 return ( $name != '' ) ?
$name : 'localhost';
1176 public function getServerType( $i ) {
1177 return isset( $this->servers
[$i]['type'] ) ?
$this->servers
[$i]['type'] : 'unknown';
1180 public function getMasterPos() {
1181 # If this entire request was served from a replica DB without opening a connection to the
1182 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1183 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1184 if ( !$masterConn ) {
1185 $serverCount = count( $this->servers
);
1186 for ( $i = 1; $i < $serverCount; $i++
) {
1187 $conn = $this->getAnyOpenConnection( $i );
1189 return $conn->getReplicaPos();
1193 return $masterConn->getMasterPos();
1199 public function disable() {
1201 $this->disabled
= true;
1204 public function closeAll() {
1205 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1206 $host = $conn->getServer();
1207 $this->connLogger
->debug(
1208 __METHOD__
. ": closing connection to database '$host'." );
1213 self
::KEY_LOCAL
=> [],
1214 self
::KEY_FOREIGN_INUSE
=> [],
1215 self
::KEY_FOREIGN_FREE
=> [],
1216 self
::KEY_LOCAL_NOROUND
=> [],
1217 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1218 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1220 $this->connsOpened
= 0;
1223 public function closeConnection( IDatabase
$conn ) {
1224 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1225 foreach ( $this->conns
as $type => $connsByServer ) {
1226 if ( !isset( $connsByServer[$serverIndex] ) ) {
1230 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1231 if ( $conn === $trackedConn ) {
1232 $host = $this->getServerName( $i );
1233 $this->connLogger
->debug(
1234 __METHOD__
. ": closing connection to database $i at '$host'." );
1235 unset( $this->conns
[$type][$serverIndex][$i] );
1236 --$this->connsOpened
;
1245 public function commitAll( $fname = __METHOD__
) {
1248 $restore = ( $this->trxRoundId
!== false );
1249 $this->trxRoundId
= false;
1250 $this->forEachOpenConnection(
1251 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1253 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1254 } catch ( DBError
$e ) {
1255 call_user_func( $this->errorLogger
, $e );
1256 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1258 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1259 $this->undoTransactionRoundFlags( $conn );
1265 throw new DBExpectedError(
1267 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1272 public function finalizeMasterChanges() {
1273 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1274 // Any error should cause all DB transactions to be rolled back together
1275 $conn->setTrxEndCallbackSuppression( false );
1276 $conn->runOnTransactionPreCommitCallbacks();
1277 // Defer post-commit callbacks until COMMIT finishes for all DBs
1278 $conn->setTrxEndCallbackSuppression( true );
1282 public function approveMasterChanges( array $options ) {
1283 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1284 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1285 // If atomic sections or explicit transactions are still open, some caller must have
1286 // caught an exception but failed to properly rollback any changes. Detect that and
1287 // throw and error (causing rollback).
1288 if ( $conn->explicitTrxActive() ) {
1289 throw new DBTransactionError(
1291 "Explicit transaction still active. A caller may have caught an error."
1294 // Assert that the time to replicate the transaction will be sane.
1295 // If this fails, then all DB transactions will be rollback back together.
1296 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1297 if ( $limit > 0 && $time > $limit ) {
1298 throw new DBTransactionSizeError(
1300 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1304 // If a connection sits idle while slow queries execute on another, that connection
1305 // may end up dropped before the commit round is reached. Ping servers to detect this.
1306 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1307 throw new DBTransactionError(
1309 "A connection to the {$conn->getDBname()} database was lost before commit."
1315 public function beginMasterChanges( $fname = __METHOD__
) {
1316 if ( $this->trxRoundId
!== false ) {
1317 throw new DBTransactionError(
1319 "$fname: Transaction round '{$this->trxRoundId}' already started."
1322 $this->trxRoundId
= $fname;
1325 $this->forEachOpenMasterConnection(
1326 function ( Database
$conn ) use ( $fname, &$failures ) {
1327 $conn->setTrxEndCallbackSuppression( true );
1329 $conn->flushSnapshot( $fname );
1330 } catch ( DBError
$e ) {
1331 call_user_func( $this->errorLogger
, $e );
1332 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1334 $conn->setTrxEndCallbackSuppression( false );
1335 $this->applyTransactionRoundFlags( $conn );
1340 throw new DBExpectedError(
1342 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1347 public function commitMasterChanges( $fname = __METHOD__
) {
1350 /** @noinspection PhpUnusedLocalVariableInspection */
1351 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1353 $restore = ( $this->trxRoundId
!== false );
1354 $this->trxRoundId
= false;
1355 $this->forEachOpenMasterConnection(
1356 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1358 if ( $conn->writesOrCallbacksPending() ) {
1359 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1360 } elseif ( $restore ) {
1361 $conn->flushSnapshot( $fname );
1363 } catch ( DBError
$e ) {
1364 call_user_func( $this->errorLogger
, $e );
1365 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1368 $this->undoTransactionRoundFlags( $conn );
1374 throw new DBExpectedError(
1376 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1381 public function runMasterPostTrxCallbacks( $type ) {
1382 $e = null; // first exception
1383 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1384 $conn->setTrxEndCallbackSuppression( false );
1385 // Callbacks run in AUTO-COMMIT mode, so make sure no transactions are pending...
1386 if ( $conn->writesPending() ) {
1387 // This happens if onTransactionIdle() callbacks write to *other* handles
1388 // (which already finished their callbacks). Let any callbacks run in the final
1389 // commitMasterChanges() in LBFactory::shutdown(), when the transaction is gone.
1390 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1392 } elseif ( $conn->trxLevel() ) {
1393 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1394 // thus leaving an implicit read-only transaction open at this point. It
1395 // also happens if onTransactionIdle() callbacks leave implicit transactions
1396 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1397 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1401 $conn->runOnTransactionIdleCallbacks( $type );
1402 } catch ( Exception
$ex ) {
1406 $conn->runTransactionListenerCallbacks( $type );
1407 } catch ( Exception
$ex ) {
1415 public function rollbackMasterChanges( $fname = __METHOD__
) {
1416 $restore = ( $this->trxRoundId
!== false );
1417 $this->trxRoundId
= false;
1418 $this->forEachOpenMasterConnection(
1419 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1420 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1422 $this->undoTransactionRoundFlags( $conn );
1428 public function suppressTransactionEndCallbacks() {
1429 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1430 $conn->setTrxEndCallbackSuppression( true );
1435 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1437 * Some servers may have neither flag enabled, meaning that they opt out of such
1438 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1439 * when a DB server is used for something like simple key/value storage.
1441 * @param IDatabase $conn
1443 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1444 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1445 return; // transaction rounds do not apply to these connections
1448 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1449 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1450 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1451 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1454 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1455 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1460 * @param IDatabase $conn
1462 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1463 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1464 return; // transaction rounds do not apply to these connections
1467 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1468 $conn->setLBInfo( 'trxRoundId', false );
1471 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1472 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1476 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1477 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1478 $conn->flushSnapshot( __METHOD__
);
1482 public function hasMasterConnection() {
1483 return $this->isOpen( $this->getWriterIndex() );
1486 public function hasMasterChanges() {
1488 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1489 $pending |
= $conn->writesOrCallbacksPending();
1492 return (bool)$pending;
1495 public function lastMasterChangeTimestamp() {
1497 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1498 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1504 public function hasOrMadeRecentMasterChanges( $age = null ) {
1505 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1507 return ( $this->hasMasterChanges()
1508 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1511 public function pendingMasterChangeCallers() {
1513 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1514 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1520 public function getLaggedReplicaMode( $domain = false ) {
1521 // No-op if there is only one DB (also avoids recursion)
1522 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1524 // See if laggedReplicaMode gets set
1525 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1526 $this->reuseConnection( $conn );
1527 } catch ( DBConnectionError
$e ) {
1528 // Avoid expensive re-connect attempts and failures
1529 $this->allReplicasDownMode
= true;
1530 $this->laggedReplicaMode
= true;
1534 return $this->laggedReplicaMode
;
1538 * @param bool $domain
1540 * @deprecated 1.28; use getLaggedReplicaMode()
1542 public function getLaggedSlaveMode( $domain = false ) {
1543 return $this->getLaggedReplicaMode( $domain );
1546 public function laggedReplicaUsed() {
1547 return $this->laggedReplicaMode
;
1553 * @deprecated Since 1.28; use laggedReplicaUsed()
1555 public function laggedSlaveUsed() {
1556 return $this->laggedReplicaUsed();
1559 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1560 if ( $this->readOnlyReason
!== false ) {
1561 return $this->readOnlyReason
;
1562 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1563 if ( $this->allReplicasDownMode
) {
1564 return 'The database has been automatically locked ' .
1565 'until the replica database servers become available';
1567 return 'The database has been automatically locked ' .
1568 'while the replica database servers catch up to the master.';
1570 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1571 return 'The database master is running in read-only mode.';
1578 * @param string $domain Domain ID, or false for the current domain
1579 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1582 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1583 $cache = $this->wanCache
;
1584 $masterServer = $this->getServerName( $this->getWriterIndex() );
1586 return (bool)$cache->getWithSetCallback(
1587 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1588 self
::TTL_CACHE_READONLY
,
1589 function () use ( $domain, $conn ) {
1590 $old = $this->trxProfiler
->setSilenced( true );
1592 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1593 $readOnly = (int)$dbw->serverIsReadOnly();
1595 $this->reuseConnection( $dbw );
1597 } catch ( DBError
$e ) {
1600 $this->trxProfiler
->setSilenced( $old );
1603 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1607 public function allowLagged( $mode = null ) {
1608 if ( $mode === null ) {
1609 return $this->allowLagged
;
1611 $this->allowLagged
= $mode;
1613 return $this->allowLagged
;
1616 public function pingAll() {
1618 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1619 if ( !$conn->ping() ) {
1627 public function forEachOpenConnection( $callback, array $params = [] ) {
1628 foreach ( $this->conns
as $connsByServer ) {
1629 foreach ( $connsByServer as $serverConns ) {
1630 foreach ( $serverConns as $conn ) {
1631 $mergedParams = array_merge( [ $conn ], $params );
1632 call_user_func_array( $callback, $mergedParams );
1638 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1639 $masterIndex = $this->getWriterIndex();
1640 foreach ( $this->conns
as $connsByServer ) {
1641 if ( isset( $connsByServer[$masterIndex] ) ) {
1642 /** @var IDatabase $conn */
1643 foreach ( $connsByServer[$masterIndex] as $conn ) {
1644 $mergedParams = array_merge( [ $conn ], $params );
1645 call_user_func_array( $callback, $mergedParams );
1651 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1652 foreach ( $this->conns
as $connsByServer ) {
1653 foreach ( $connsByServer as $i => $serverConns ) {
1654 if ( $i === $this->getWriterIndex() ) {
1655 continue; // skip master
1657 foreach ( $serverConns as $conn ) {
1658 $mergedParams = array_merge( [ $conn ], $params );
1659 call_user_func_array( $callback, $mergedParams );
1665 public function getMaxLag( $domain = false ) {
1670 if ( $this->getServerCount() <= 1 ) {
1671 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1674 $lagTimes = $this->getLagTimes( $domain );
1675 foreach ( $lagTimes as $i => $lag ) {
1676 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1678 $host = $this->servers
[$i]['host'];
1683 return [ $host, $maxLag, $maxIndex ];
1686 public function getLagTimes( $domain = false ) {
1687 if ( $this->getServerCount() <= 1 ) {
1688 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1691 $knownLagTimes = []; // map of (server index => 0 seconds)
1692 $indexesWithLag = [];
1693 foreach ( $this->servers
as $i => $server ) {
1694 if ( empty( $server['is static'] ) ) {
1695 $indexesWithLag[] = $i; // DB server might have replication lag
1697 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1701 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1704 public function safeGetLag( IDatabase
$conn ) {
1705 if ( $this->getServerCount() <= 1 ) {
1708 return $conn->getLag();
1713 * @param IDatabase $conn
1714 * @param DBMasterPos|bool $pos
1715 * @param int|null $timeout
1718 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1719 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1721 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1722 return true; // server is not a replica DB
1726 // Get the current master position, opening a connection if needed
1727 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1728 if ( $masterConn ) {
1729 $pos = $masterConn->getMasterPos();
1731 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1732 $pos = $masterConn->getMasterPos();
1733 $this->closeConnection( $masterConn );
1737 if ( $pos instanceof DBMasterPos
) {
1738 $result = $conn->masterPosWait( $pos, $timeout );
1739 if ( $result == -1 ||
is_null( $result ) ) {
1740 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1741 $this->replLogger
->warning( $msg, [
1742 'host' => $conn->getServer(),
1744 'trace' => ( new RuntimeException() )->getTraceAsString()
1748 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1752 $ok = false; // something is misconfigured
1753 $this->replLogger
->error(
1754 __METHOD__
. ': could not get master pos for {host}',
1756 'host' => $conn->getServer(),
1757 'trace' => ( new RuntimeException() )->getTraceAsString()
1765 public function setTransactionListener( $name, callable
$callback = null ) {
1767 $this->trxRecurringCallbacks
[$name] = $callback;
1769 unset( $this->trxRecurringCallbacks
[$name] );
1771 $this->forEachOpenMasterConnection(
1772 function ( IDatabase
$conn ) use ( $name, $callback ) {
1773 $conn->setTransactionListener( $name, $callback );
1778 public function setTableAliases( array $aliases ) {
1779 $this->tableAliases
= $aliases;
1782 public function setIndexAliases( array $aliases ) {
1783 $this->indexAliases
= $aliases;
1786 public function setDomainPrefix( $prefix ) {
1787 // Find connections to explicit foreign domains still marked as in-use...
1789 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1790 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1791 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1792 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1793 $domainsInUse[] = $conn->getDomainID();
1797 // Do not switch connections to explicit foreign domains unless marked as safe
1798 if ( $domainsInUse ) {
1799 $domains = implode( ', ', $domainsInUse );
1800 throw new DBUnexpectedError( null,
1801 "Foreign domain connections are still in use ($domains)." );
1804 $oldDomain = $this->localDomain
->getId();
1805 $this->setLocalDomain( new DatabaseDomain(
1806 $this->localDomain
->getDatabase(),
1807 $this->localDomain
->getSchema(),
1811 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1812 if ( !$db->getLBInfo( 'foreign' ) ) {
1813 $db->tablePrefix( $prefix );
1819 * @param DatabaseDomain $domain
1821 private function setLocalDomain( DatabaseDomain
$domain ) {
1822 $this->localDomain
= $domain;
1823 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1824 // always true, gracefully handle the case when they fail to account for escaping.
1825 if ( $this->localDomain
->getTablePrefix() != '' ) {
1826 $this->localDomainIdAlias
=
1827 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1829 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1834 * Make PHP ignore user aborts/disconnects until the returned
1835 * value leaves scope. This returns null and does nothing in CLI mode.
1837 * @return ScopedCallback|null
1839 final protected function getScopedPHPBehaviorForCommit() {
1840 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1841 $old = ignore_user_abort( true ); // avoid half-finished operations
1842 return new ScopedCallback( function () use ( $old ) {
1843 ignore_user_abort( $old );
1850 function __destruct() {
1851 // Avoid connection leaks for sanity
1856 class_alias( LoadBalancer
::class, 'LoadBalancer' );