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 UnexpectedValueException
;
32 use InvalidArgumentException
;
37 * Database connection, tracking, load balancing, and transaction manager for a cluster
41 class LoadBalancer
implements ILoadBalancer
{
42 /** @var array[] Map of (server index => server config array) */
44 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
46 /** @var float[] Map of (server index => weight) */
48 /** @var array[] Map of (group => server index => weight) */
50 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
52 /** @var int Seconds to spend waiting on replica DB lag to resolve */
54 /** @var array The LoadMonitor configuration */
55 private $loadMonitorConfig;
56 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
57 private $tableAliases = [];
58 /** @var string[] Map of (index alias => index) */
59 private $indexAliases = [];
61 /** @var ILoadMonitor */
63 /** @var callable|null Callback to run before the first connection attempt */
64 private $chronologyCallback;
67 /** @var WANObjectCache */
69 /** @var object|string Class name or object With profileIn/profileOut methods */
71 /** @var TransactionProfiler */
72 protected $trxProfiler;
73 /** @var LoggerInterface */
74 protected $replLogger;
75 /** @var LoggerInterface */
76 protected $connLogger;
77 /** @var LoggerInterface */
78 protected $queryLogger;
79 /** @var LoggerInterface */
80 protected $perfLogger;
82 /** @var Database DB connection object that caused a problem */
83 private $errorConnection;
84 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
86 /** @var bool|DBMasterPos False if not set */
88 /** @var bool Whether the generic reader fell back to a lagged replica DB */
89 private $laggedReplicaMode = false;
90 /** @var bool Whether the generic reader fell back to a lagged replica DB */
91 private $allReplicasDownMode = false;
92 /** @var string The last DB selection or connection error */
93 private $lastError = 'Unknown error';
94 /** @var string|bool Reason the LB is read-only or false if not */
95 private $readOnlyReason = false;
96 /** @var int Total connections opened */
97 private $connsOpened = 0;
98 /** @var string|bool String if a requested DBO_TRX transaction round is active */
99 private $trxRoundId = false;
100 /** @var array[] Map of (name => callable) */
101 private $trxRecurringCallbacks = [];
102 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
103 private $localDomain;
104 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
105 private $localDomainIdAlias;
106 /** @var string Current server name */
108 /** @var bool Whether this PHP instance is for a CLI script */
110 /** @var string Agent name for query profiling */
113 /** @var callable Exception logger */
114 private $errorLogger;
115 /** @var callable Deprecation logger */
116 private $deprecationLogger;
119 private $disabled = false;
120 /** @var bool Whether any connection has been attempted yet */
121 private $connectionAttempted = false;
123 private $maxLag = self
::MAX_LAG_DEFAULT
;
125 /** @var int Warn when this many connection are held */
126 const CONN_HELD_WARN_THRESHOLD
= 10;
128 /** @var int Default 'maxLag' when unspecified */
129 const MAX_LAG_DEFAULT
= 10;
130 /** @var int Default 'waitTimeout' when unspecified */
131 const MAX_WAIT_DEFAULT
= 10;
132 /** @var int Seconds to cache master server read-only status */
133 const TTL_CACHE_READONLY
= 5;
135 const KEY_LOCAL
= 'local';
136 const KEY_FOREIGN_FREE
= 'foreignFree';
137 const KEY_FOREIGN_INUSE
= 'foreignInUse';
139 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
140 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
141 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
143 public function __construct( array $params ) {
144 if ( !isset( $params['servers'] ) ) {
145 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
147 $this->servers
= $params['servers'];
148 foreach ( $this->servers
as $i => $server ) {
150 $this->servers
[$i]['master'] = true;
152 $this->servers
[$i]['replica'] = true;
156 $localDomain = isset( $params['localDomain'] )
157 ? DatabaseDomain
::newFromId( $params['localDomain'] )
158 : DatabaseDomain
::newUnspecified();
159 $this->setLocalDomain( $localDomain );
161 $this->waitTimeout
= isset( $params['waitTimeout'] )
162 ?
$params['waitTimeout']
163 : self
::MAX_WAIT_DEFAULT
;
165 $this->readIndex
= -1;
167 // Connection were transaction rounds may be applied
168 self
::KEY_LOCAL
=> [],
169 self
::KEY_FOREIGN_INUSE
=> [],
170 self
::KEY_FOREIGN_FREE
=> [],
171 // Auto-committing counterpart connections that ignore transaction rounds
172 self
::KEY_LOCAL_NOROUND
=> [],
173 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
174 self
::KEY_FOREIGN_FREE_NOROUND
=> []
177 $this->waitForPos
= false;
178 $this->allowLagged
= false;
180 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
181 $this->readOnlyReason
= $params['readOnlyReason'];
184 if ( isset( $params['maxLag'] ) ) {
185 $this->maxLag
= $params['maxLag'];
188 if ( isset( $params['loadMonitor'] ) ) {
189 $this->loadMonitorConfig
= $params['loadMonitor'];
191 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
193 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
195 foreach ( $params['servers'] as $i => $server ) {
196 $this->loads
[$i] = $server['load'];
197 if ( isset( $server['groupLoads'] ) ) {
198 foreach ( $server['groupLoads'] as $group => $ratio ) {
199 if ( !isset( $this->groupLoads
[$group] ) ) {
200 $this->groupLoads
[$group] = [];
202 $this->groupLoads
[$group][$i] = $ratio;
207 if ( isset( $params['srvCache'] ) ) {
208 $this->srvCache
= $params['srvCache'];
210 $this->srvCache
= new EmptyBagOStuff();
212 if ( isset( $params['wanCache'] ) ) {
213 $this->wanCache
= $params['wanCache'];
215 $this->wanCache
= WANObjectCache
::newEmpty();
217 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
218 if ( isset( $params['trxProfiler'] ) ) {
219 $this->trxProfiler
= $params['trxProfiler'];
221 $this->trxProfiler
= new TransactionProfiler();
224 $this->errorLogger
= isset( $params['errorLogger'] )
225 ?
$params['errorLogger']
226 : function ( Exception
$e ) {
227 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
229 $this->deprecationLogger
= isset( $params['deprecationLogger'] )
230 ?
$params['deprecationLogger']
231 : function ( $msg ) {
232 trigger_error( $msg, E_USER_DEPRECATED
);
235 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
236 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
239 $this->host
= isset( $params['hostname'] )
240 ?
$params['hostname']
241 : ( gethostname() ?
: 'unknown' );
242 $this->cliMode
= isset( $params['cliMode'] )
244 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
245 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
247 if ( isset( $params['chronologyCallback'] ) ) {
248 $this->chronologyCallback
= $params['chronologyCallback'];
253 * Get the local (and default) database domain ID of connection handles
255 * @see DatabaseDomain
256 * @return string Database domain ID; this specifies DB name, schema, and table prefix
259 public function getLocalDomainID() {
260 return $this->localDomain
->getId();
264 * Get a LoadMonitor instance
266 * @return ILoadMonitor
268 private function getLoadMonitor() {
269 if ( !isset( $this->loadMonitor
) ) {
271 'LoadMonitor' => LoadMonitor
::class,
272 'LoadMonitorNull' => LoadMonitorNull
::class,
273 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
276 $class = $this->loadMonitorConfig
['class'];
277 if ( isset( $compat[$class] ) ) {
278 $class = $compat[$class];
281 $this->loadMonitor
= new $class(
282 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
283 $this->loadMonitor
->setLogger( $this->replLogger
);
286 return $this->loadMonitor
;
290 * @param array $loads
291 * @param bool|string $domain Domain to get non-lagged for
292 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
293 * @return bool|int|string
295 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
296 $lags = $this->getLagTimes( $domain );
298 # Unset excessively lagged servers
299 foreach ( $lags as $i => $lag ) {
301 # How much lag this server nominally is allowed to have
302 $maxServerLag = isset( $this->servers
[$i]['max lag'] )
303 ?
$this->servers
[$i]['max lag']
304 : $this->maxLag
; // default
305 # Constrain that futher by $maxLag argument
306 $maxServerLag = min( $maxServerLag, $maxLag );
308 $host = $this->getServerName( $i );
309 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
310 $this->replLogger
->error(
312 ": server {host} is not replicating?", [ 'host' => $host ] );
314 } elseif ( $lag > $maxServerLag ) {
315 $this->replLogger
->debug(
317 ": server {host} has {lag} seconds of lag (>= {maxlag})",
318 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
325 # Find out if all the replica DBs with non-zero load are lagged
327 foreach ( $loads as $load ) {
331 # No appropriate DB servers except maybe the master and some replica DBs with zero load
332 # Do NOT use the master
333 # Instead, this function will return false, triggering read-only mode,
334 # and a lagged replica DB will be used instead.
338 if ( count( $loads ) == 0 ) {
342 # Return a random representative of the remainder
343 return ArrayUtils
::pickRandom( $loads );
346 public function getReaderIndex( $group = false, $domain = false ) {
347 if ( count( $this->servers
) == 1 ) {
348 // Skip the load balancing if there's only one server
349 return $this->getWriterIndex();
350 } elseif ( $group === false && $this->readIndex
>= 0 ) {
351 // Shortcut if the generic reader index was already cached
352 return $this->readIndex
;
355 if ( $group !== false ) {
356 // Use the server weight array for this load group
357 if ( isset( $this->groupLoads
[$group] ) ) {
358 $loads = $this->groupLoads
[$group];
360 // No loads for this group, return false and the caller can use some other group
361 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
366 // Use the generic load group
367 $loads = $this->loads
;
370 // Scale the configured load ratios according to each server's load and state
371 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
373 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
374 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
375 if ( $i === false ) {
376 // Replica DB connection unsuccessful
380 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
381 // Before any data queries are run, wait for the server to catch up to the
382 // specified position. This is used to improve session consistency. Note that
383 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
384 // so update laggedReplicaMode as needed for consistency.
385 if ( !$this->doWait( $i ) ) {
386 $laggedReplicaMode = true;
390 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
391 // Cache the generic reader index for future ungrouped DB_REPLICA handles
392 $this->readIndex
= $i;
393 // Record if the generic reader index is in "lagged replica DB" mode
394 if ( $laggedReplicaMode ) {
395 $this->laggedReplicaMode
= true;
399 $serverName = $this->getServerName( $i );
400 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
406 * @param array $loads List of server weights
407 * @param string|bool $domain
408 * @return array (reader index, lagged replica mode) or false on failure
410 private function pickReaderIndex( array $loads, $domain = false ) {
411 if ( !count( $loads ) ) {
412 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
415 /** @var int|bool $i Index of selected server */
417 /** @var bool $laggedReplicaMode Whether server is considered lagged */
418 $laggedReplicaMode = false;
420 // Quickly look through the available servers for a server that meets criteria...
421 $currentLoads = $loads;
422 while ( count( $currentLoads ) ) {
423 if ( $this->allowLagged ||
$laggedReplicaMode ) {
424 $i = ArrayUtils
::pickRandom( $currentLoads );
427 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
428 // "chronologyCallback" sets "waitForPos" for session consistency.
429 // This triggers doWait() after connect, so it's especially good to
430 // avoid lagged servers so as to avoid excessive delay in that method.
431 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
432 // Aim for <= 1 second of waiting (being too picky can backfire)
433 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
435 if ( $i === false ) {
436 // Any server with less lag than it's 'max lag' param is preferable
437 $i = $this->getRandomNonLagged( $currentLoads, $domain );
439 if ( $i === false && count( $currentLoads ) != 0 ) {
440 // All replica DBs lagged. Switch to read-only mode
441 $this->replLogger
->error(
442 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
443 $i = ArrayUtils
::pickRandom( $currentLoads );
444 $laggedReplicaMode = true;
448 if ( $i === false ) {
449 // pickRandom() returned false.
450 // This is permanent and means the configuration or the load monitor
451 // wants us to return false.
452 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
454 return [ false, false ];
457 $serverName = $this->getServerName( $i );
458 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
460 $conn = $this->openConnection( $i, $domain );
462 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
463 unset( $currentLoads[$i] ); // avoid this server next iteration
468 // Decrement reference counter, we are finished with this connection.
469 // It will be incremented for the caller later.
470 if ( $domain !== false ) {
471 $this->reuseConnection( $conn );
474 // Return this server
478 // If all servers were down, quit now
479 if ( !count( $currentLoads ) ) {
480 $this->connLogger
->error( __METHOD__
. ": all servers down" );
483 return [ $i, $laggedReplicaMode ];
486 public function waitFor( $pos ) {
487 $oldPos = $this->waitForPos
;
489 $this->waitForPos
= $pos;
490 // If a generic reader connection was already established, then wait now
491 $i = $this->readIndex
;
493 if ( !$this->doWait( $i ) ) {
494 $this->laggedReplicaMode
= true;
498 // Restore the older position if it was higher since this is used for lag-protection
499 $this->setWaitForPositionIfHigher( $oldPos );
503 public function waitForOne( $pos, $timeout = null ) {
504 $oldPos = $this->waitForPos
;
506 $this->waitForPos
= $pos;
508 $i = $this->readIndex
;
510 // Pick a generic replica DB if there isn't one yet
511 $readLoads = $this->loads
;
512 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
513 $readLoads = array_filter( $readLoads ); // with non-zero load
514 $i = ArrayUtils
::pickRandom( $readLoads );
518 $ok = $this->doWait( $i, true, $timeout );
520 $ok = true; // no applicable loads
523 # Restore the old position, as this is not used for lag-protection but for throttling
524 $this->waitForPos
= $oldPos;
530 public function waitForAll( $pos, $timeout = null ) {
531 $timeout = $timeout ?
: $this->waitTimeout
;
533 $oldPos = $this->waitForPos
;
535 $this->waitForPos
= $pos;
536 $serverCount = count( $this->servers
);
539 for ( $i = 1; $i < $serverCount; $i++
) {
540 if ( $this->loads
[$i] > 0 ) {
541 $start = microtime( true );
542 $ok = $this->doWait( $i, true, $timeout ) && $ok;
543 $timeout -= intval( microtime( true ) - $start );
544 if ( $timeout <= 0 ) {
545 break; // timeout reached
550 # Restore the old position, as this is not used for lag-protection but for throttling
551 $this->waitForPos
= $oldPos;
558 * @param DBMasterPos|bool $pos
560 private function setWaitForPositionIfHigher( $pos ) {
565 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
566 $this->waitForPos
= $pos;
570 public function getAnyOpenConnection( $i, $flags = 0 ) {
571 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
572 foreach ( $this->conns
as $connsByServer ) {
573 if ( !isset( $connsByServer[$i] ) ) {
577 foreach ( $connsByServer[$i] as $conn ) {
578 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
588 * Wait for a given replica DB to catch up to the master pos stored in $this
589 * @param int $index Server index
590 * @param bool $open Check the server even if a new connection has to be made
591 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
594 protected function doWait( $index, $open = false, $timeout = null ) {
595 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
597 // Check if we already know that the DB has reached this point
598 $server = $this->getServerName( $index );
599 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
600 /** @var DBMasterPos $knownReachedPos */
601 $knownReachedPos = $this->srvCache
->get( $key );
603 $knownReachedPos instanceof DBMasterPos
&&
604 $knownReachedPos->hasReached( $this->waitForPos
)
606 $this->replLogger
->debug(
608 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
609 [ 'dbserver' => $server ]
614 // Find a connection to wait on, creating one if needed and allowed
615 $close = false; // close the connection afterwards
616 $conn = $this->getAnyOpenConnection( $index );
619 $this->replLogger
->debug(
620 __METHOD__
. ': no connection open for {dbserver}',
621 [ 'dbserver' => $server ]
626 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
628 $this->replLogger
->warning(
629 __METHOD__
. ': failed to connect to {dbserver}',
630 [ 'dbserver' => $server ]
635 // Avoid connection spam in waitForAll() when connections
636 // are made just for the sake of doing this lag check.
641 $this->replLogger
->info(
643 ': waiting for replica DB {dbserver} to catch up...',
644 [ 'dbserver' => $server ]
647 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
649 if ( $result === null ) {
650 $this->replLogger
->warning(
651 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
654 'pos' => $this->waitForPos
,
655 'trace' => ( new RuntimeException() )->getTraceAsString()
659 } elseif ( $result == -1 ) {
660 $this->replLogger
->warning(
661 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
664 'pos' => $this->waitForPos
,
665 'trace' => ( new RuntimeException() )->getTraceAsString()
670 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
672 // Remember that the DB reached this point
673 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
677 $this->closeConnection( $conn );
683 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
684 if ( $i === null ||
$i === false ) {
685 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
686 ' with invalid server index' );
689 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
690 $domain = false; // local connection requested
693 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
694 // Assuming all servers are of the same type (or similar), which is overwhelmingly
695 // the case, use the master server information to get the attributes. The information
696 // for $i cannot be used since it might be DB_REPLICA, which might require connection
697 // attempts in order to be resolved into a real server index.
698 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
699 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
700 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
701 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
702 // to reduce lock contention. None of these apply for sqlite and using separate
703 // connections just causes self-deadlocks.
704 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
705 $this->connLogger
->info( __METHOD__
.
706 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
710 $groups = ( $groups === false ||
$groups === [] )
711 ?
[ false ] // check one "group": the generic pool
714 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
715 $oldConnsOpened = $this->connsOpened
; // connections open now
717 if ( $i == self
::DB_MASTER
) {
718 $i = $this->getWriterIndex();
719 } elseif ( $i == self
::DB_REPLICA
) {
720 # Try to find an available server in any the query groups (in order)
721 foreach ( $groups as $group ) {
722 $groupIndex = $this->getReaderIndex( $group, $domain );
723 if ( $groupIndex !== false ) {
730 # Operation-based index
731 if ( $i == self
::DB_REPLICA
) {
732 $this->lastError
= 'Unknown error'; // reset error string
733 # Try the general server pool if $groups are unavailable.
734 $i = ( $groups === [ false ] )
735 ?
false // don't bother with this if that is what was tried above
736 : $this->getReaderIndex( false, $domain );
737 # Couldn't find a working server in getReaderIndex()?
738 if ( $i === false ) {
739 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
740 // Throw an exception
741 $this->reportConnectionError();
742 return null; // not reached
746 # Now we have an explicit index into the servers array
747 $conn = $this->openConnection( $i, $domain, $flags );
749 // Throw an exception
750 $this->reportConnectionError();
751 return null; // not reached
754 # Profile any new connections that happen
755 if ( $this->connsOpened
> $oldConnsOpened ) {
756 $host = $conn->getServer();
757 $dbname = $conn->getDBname();
758 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
762 # Make master-requested DB handles inherit any read-only mode setting
763 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
769 public function reuseConnection( IDatabase
$conn ) {
770 $serverIndex = $conn->getLBInfo( 'serverIndex' );
771 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
772 if ( $serverIndex === null ||
$refCount === null ) {
774 * This can happen in code like:
775 * foreach ( $dbs as $db ) {
776 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
778 * $lb->reuseConnection( $conn );
780 * When a connection to the local DB is opened in this way, reuseConnection()
784 } elseif ( $conn instanceof DBConnRef
) {
785 // DBConnRef already handles calling reuseConnection() and only passes the live
786 // Database instance to this method. Any caller passing in a DBConnRef is broken.
787 $this->connLogger
->error(
788 __METHOD__
. ": got DBConnRef instance.\n" .
789 ( new RuntimeException() )->getTraceAsString() );
794 if ( $this->disabled
) {
795 return; // DBConnRef handle probably survived longer than the LoadBalancer
798 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
799 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
800 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
802 $connFreeKey = self
::KEY_FOREIGN_FREE
;
803 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
806 $domain = $conn->getDomainID();
807 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
808 throw new InvalidArgumentException( __METHOD__
.
809 ": connection $serverIndex/$domain not found; it may have already been freed." );
810 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
811 throw new InvalidArgumentException( __METHOD__
.
812 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
815 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
816 if ( $refCount <= 0 ) {
817 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
818 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
819 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
820 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
822 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
824 $this->connLogger
->debug( __METHOD__
.
825 ": reference count for $serverIndex/$domain reduced to $refCount" );
829 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
830 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
832 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
835 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
836 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
838 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
841 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
842 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
844 return new MaintainableDBConnRef(
845 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
848 public function openConnection( $i, $domain = false, $flags = 0 ) {
849 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
850 $domain = false; // local connection requested
853 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
854 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
855 // Load any "waitFor" positions before connecting so that doWait() is triggered
856 $this->connectionAttempted
= true;
857 call_user_func( $this->chronologyCallback
, $this );
860 // Check if an auto-commit connection is being requested. If so, it will not reuse the
861 // main set of DB connections but rather its own pool since:
862 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
863 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
864 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
866 if ( $domain !== false ) {
867 // Connection is to a foreign domain
868 $conn = $this->openForeignConnection( $i, $domain, $flags );
870 // Connection is to the local domain
871 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
872 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
873 $conn = $this->conns
[$connKey][$i][0];
875 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
876 throw new InvalidArgumentException( "No server with index '$i'." );
878 // Open a new connection
879 $server = $this->servers
[$i];
880 $server['serverIndex'] = $i;
881 $server['autoCommitOnly'] = $autoCommit;
882 if ( $this->localDomain
->getDatabase() !== null ) {
883 // Use the local domain table prefix if the local domain is specified
884 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
886 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
887 $host = $this->getServerName( $i );
888 if ( $conn->isOpen() ) {
889 $this->connLogger
->debug(
890 __METHOD__
. ": connected to database $i at '$host'." );
891 $this->conns
[$connKey][$i][0] = $conn;
893 $this->connLogger
->warning(
894 __METHOD__
. ": failed to connect to database $i at '$host'." );
895 $this->errorConnection
= $conn;
901 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
902 // Connection was made but later unrecoverably lost for some reason.
903 // Do not return a handle that will just throw exceptions on use,
904 // but let the calling code (e.g. getReaderIndex) try another server.
905 // See DatabaseMyslBase::ping() for how this can happen.
906 $this->errorConnection
= $conn;
910 if ( $autoCommit && $conn instanceof IDatabase
) {
911 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
918 * Open a connection to a foreign DB, or return one if it is already open.
920 * Increments a reference count on the returned connection which locks the
921 * connection to the requested domain. This reference count can be
922 * decremented by calling reuseConnection().
924 * If a connection is open to the appropriate server already, but with the wrong
925 * database, it will be switched to the right database and returned, as long as
926 * it has been freed first with reuseConnection().
928 * On error, returns false, and the connection which caused the
929 * error will be available via $this->errorConnection.
931 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
933 * @param int $i Server index
934 * @param string $domain Domain ID to open
935 * @param int $flags Class CONN_* constant bitfield
938 private function openForeignConnection( $i, $domain, $flags = 0 ) {
939 $domainInstance = DatabaseDomain
::newFromId( $domain );
940 $dbName = $domainInstance->getDatabase();
941 $prefix = $domainInstance->getTablePrefix();
942 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
945 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
946 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
948 $connFreeKey = self
::KEY_FOREIGN_FREE
;
949 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
952 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
953 // Reuse an in-use connection for the same domain
954 $conn = $this->conns
[$connInUseKey][$i][$domain];
955 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
956 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
957 // Reuse a free connection for the same domain
958 $conn = $this->conns
[$connFreeKey][$i][$domain];
959 unset( $this->conns
[$connFreeKey][$i][$domain] );
960 $this->conns
[$connInUseKey][$i][$domain] = $conn;
961 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
962 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
963 // Reuse a free connection from another domain
964 $conn = reset( $this->conns
[$connFreeKey][$i] );
965 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
966 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
967 $this->lastError
= "Error selecting database '$dbName' on server " .
968 $conn->getServer() . " from client host {$this->host}";
969 $this->errorConnection
= $conn;
972 $conn->tablePrefix( $prefix );
973 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
974 // Note that if $domain is an empty string, getDomainID() might not match it
975 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
976 $this->connLogger
->debug( __METHOD__
.
977 ": reusing free connection from $oldDomain for $domain" );
980 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
981 throw new InvalidArgumentException( "No server with index '$i'." );
983 // Open a new connection
984 $server = $this->servers
[$i];
985 $server['serverIndex'] = $i;
986 $server['foreignPoolRefCount'] = 0;
987 $server['foreign'] = true;
988 $server['autoCommitOnly'] = $autoCommit;
989 $conn = $this->reallyOpenConnection( $server, $domainInstance );
990 if ( !$conn->isOpen() ) {
991 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
992 $this->errorConnection
= $conn;
995 $conn->tablePrefix( $prefix ); // as specified
996 // Note that if $domain is an empty string, getDomainID() might not match it
997 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
998 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1002 if ( $conn instanceof IDatabase
) {
1003 // Final sanity check to make sure the right domain is selected
1004 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1005 throw new UnexpectedValueException(
1006 "Got connection to '{$conn->getDomainID()}', but expected '$domain'." );
1008 // Increment reference count
1009 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1010 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1016 public function getServerAttributes( $i ) {
1017 return Database
::attributesFromType(
1018 $this->getServerType( $i ),
1019 isset( $this->servers
[$i]['driver'] ) ?
$this->servers
[$i]['driver'] : null
1024 * Test if the specified index represents an open connection
1026 * @param int $index Server index
1030 private function isOpen( $index ) {
1031 if ( !is_int( $index ) ) {
1035 return (bool)$this->getAnyOpenConnection( $index );
1039 * Open a new network connection to a server (uncached)
1041 * Returns a Database object whether or not the connection was successful.
1043 * @param array $server
1044 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1046 * @throws DBAccessError
1047 * @throws InvalidArgumentException
1049 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1050 if ( $this->disabled
) {
1051 throw new DBAccessError();
1054 // Handle $domainOverride being a specified or an unspecified domain
1055 if ( $domainOverride->getDatabase() === null ) {
1056 // Normally, an RDBMS requires a DB name specified on connection and the $server
1057 // configuration array is assumed to already specify an appropriate DB name.
1058 if ( $server['type'] === 'mysql' ) {
1059 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1060 // and the DB name in $server might not exist due to legacy reasons (the default
1061 // domain used to ignore the local LB domain, even when mismatched).
1062 $server['dbname'] = null;
1065 $server['dbname'] = $domainOverride->getDatabase();
1066 $server['schema'] = $domainOverride->getSchema();
1069 // Let the handle know what the cluster master is (e.g. "db1052")
1070 $masterName = $this->getServerName( $this->getWriterIndex() );
1071 $server['clusterMasterHost'] = $masterName;
1073 // Log when many connection are made on requests
1074 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1075 $this->perfLogger
->warning( __METHOD__
. ": " .
1076 "{$this->connsOpened}+ connections made (master=$masterName)" );
1079 $server['srvCache'] = $this->srvCache
;
1080 // Set loggers and profilers
1081 $server['connLogger'] = $this->connLogger
;
1082 $server['queryLogger'] = $this->queryLogger
;
1083 $server['errorLogger'] = $this->errorLogger
;
1084 $server['deprecationLogger'] = $this->deprecationLogger
;
1085 $server['profiler'] = $this->profiler
;
1086 $server['trxProfiler'] = $this->trxProfiler
;
1087 // Use the same agent and PHP mode for all DB handles
1088 $server['cliMode'] = $this->cliMode
;
1089 $server['agent'] = $this->agent
;
1090 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1091 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1092 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1094 // Create a live connection object
1096 $db = Database
::factory( $server['type'], $server );
1097 } catch ( DBConnectionError
$e ) {
1098 // FIXME: This is probably the ugliest thing I have ever done to
1099 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1103 $db->setLBInfo( $server );
1104 $db->setLazyMasterHandle(
1105 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1107 $db->setTableAliases( $this->tableAliases
);
1108 $db->setIndexAliases( $this->indexAliases
);
1110 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1111 if ( $this->trxRoundId
!== false ) {
1112 $this->applyTransactionRoundFlags( $db );
1114 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1115 $db->setTransactionListener( $name, $callback );
1123 * @throws DBConnectionError
1125 private function reportConnectionError() {
1126 $conn = $this->errorConnection
; // the connection which caused the error
1128 'method' => __METHOD__
,
1129 'last_error' => $this->lastError
,
1132 if ( $conn instanceof IDatabase
) {
1133 $context['db_server'] = $conn->getServer();
1134 $this->connLogger
->warning(
1135 __METHOD__
. ": connection error: {last_error} ({db_server})",
1139 // throws DBConnectionError
1140 $conn->reportConnectionError( "{$this->lastError} ({$context['db_server']})" );
1142 // No last connection, probably due to all servers being too busy
1143 $this->connLogger
->error(
1145 ": LB failure with no last connection. Connection error: {last_error}",
1149 // If all servers were busy, "lastError" will contain something sensible
1150 throw new DBConnectionError( null, $this->lastError
);
1154 public function getWriterIndex() {
1158 public function haveIndex( $i ) {
1159 return array_key_exists( $i, $this->servers
);
1162 public function isNonZeroLoad( $i ) {
1163 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1166 public function getServerCount() {
1167 return count( $this->servers
);
1170 public function getServerName( $i ) {
1171 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1172 $name = $this->servers
[$i]['hostName'];
1173 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1174 $name = $this->servers
[$i]['host'];
1179 return ( $name != '' ) ?
$name : 'localhost';
1182 public function getServerInfo( $i ) {
1183 if ( isset( $this->servers
[$i] ) ) {
1184 return $this->servers
[$i];
1190 public function getServerType( $i ) {
1191 return isset( $this->servers
[$i]['type'] ) ?
$this->servers
[$i]['type'] : 'unknown';
1194 public function getMasterPos() {
1195 # If this entire request was served from a replica DB without opening a connection to the
1196 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1197 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1198 if ( !$masterConn ) {
1199 $serverCount = count( $this->servers
);
1200 for ( $i = 1; $i < $serverCount; $i++
) {
1201 $conn = $this->getAnyOpenConnection( $i );
1203 return $conn->getReplicaPos();
1207 return $masterConn->getMasterPos();
1213 public function disable() {
1215 $this->disabled
= true;
1218 public function closeAll() {
1219 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1220 $host = $conn->getServer();
1221 $this->connLogger
->debug(
1222 __METHOD__
. ": closing connection to database '$host'." );
1227 self
::KEY_LOCAL
=> [],
1228 self
::KEY_FOREIGN_INUSE
=> [],
1229 self
::KEY_FOREIGN_FREE
=> [],
1230 self
::KEY_LOCAL_NOROUND
=> [],
1231 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1232 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1234 $this->connsOpened
= 0;
1237 public function closeConnection( IDatabase
$conn ) {
1238 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1239 foreach ( $this->conns
as $type => $connsByServer ) {
1240 if ( !isset( $connsByServer[$serverIndex] ) ) {
1244 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1245 if ( $conn === $trackedConn ) {
1246 $host = $this->getServerName( $i );
1247 $this->connLogger
->debug(
1248 __METHOD__
. ": closing connection to database $i at '$host'." );
1249 unset( $this->conns
[$type][$serverIndex][$i] );
1250 --$this->connsOpened
;
1259 public function commitAll( $fname = __METHOD__
) {
1262 $restore = ( $this->trxRoundId
!== false );
1263 $this->trxRoundId
= false;
1264 $this->forEachOpenConnection(
1265 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1267 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1268 } catch ( DBError
$e ) {
1269 call_user_func( $this->errorLogger
, $e );
1270 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1272 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1273 $this->undoTransactionRoundFlags( $conn );
1279 throw new DBExpectedError(
1281 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1286 public function finalizeMasterChanges() {
1287 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1288 // Any error should cause all DB transactions to be rolled back together
1289 $conn->setTrxEndCallbackSuppression( false );
1290 $conn->runOnTransactionPreCommitCallbacks();
1291 // Defer post-commit callbacks until COMMIT finishes for all DBs
1292 $conn->setTrxEndCallbackSuppression( true );
1296 public function approveMasterChanges( array $options ) {
1297 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1298 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1299 // If atomic sections or explicit transactions are still open, some caller must have
1300 // caught an exception but failed to properly rollback any changes. Detect that and
1301 // throw and error (causing rollback).
1302 if ( $conn->explicitTrxActive() ) {
1303 throw new DBTransactionError(
1305 "Explicit transaction still active. A caller may have caught an error."
1308 // Assert that the time to replicate the transaction will be sane.
1309 // If this fails, then all DB transactions will be rollback back together.
1310 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1311 if ( $limit > 0 && $time > $limit ) {
1312 throw new DBTransactionSizeError(
1314 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1318 // If a connection sits idle while slow queries execute on another, that connection
1319 // may end up dropped before the commit round is reached. Ping servers to detect this.
1320 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1321 throw new DBTransactionError(
1323 "A connection to the {$conn->getDBname()} database was lost before commit."
1329 public function beginMasterChanges( $fname = __METHOD__
) {
1330 if ( $this->trxRoundId
!== false ) {
1331 throw new DBTransactionError(
1333 "$fname: Transaction round '{$this->trxRoundId}' already started."
1336 $this->trxRoundId
= $fname;
1339 $this->forEachOpenMasterConnection(
1340 function ( Database
$conn ) use ( $fname, &$failures ) {
1341 $conn->setTrxEndCallbackSuppression( true );
1343 $conn->flushSnapshot( $fname );
1344 } catch ( DBError
$e ) {
1345 call_user_func( $this->errorLogger
, $e );
1346 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1348 $conn->setTrxEndCallbackSuppression( false );
1349 $this->applyTransactionRoundFlags( $conn );
1354 throw new DBExpectedError(
1356 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1361 public function commitMasterChanges( $fname = __METHOD__
) {
1364 /** @noinspection PhpUnusedLocalVariableInspection */
1365 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1367 $restore = ( $this->trxRoundId
!== false );
1368 $this->trxRoundId
= false;
1369 $this->forEachOpenMasterConnection(
1370 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1372 if ( $conn->writesOrCallbacksPending() ) {
1373 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1374 } elseif ( $restore ) {
1375 $conn->flushSnapshot( $fname );
1377 } catch ( DBError
$e ) {
1378 call_user_func( $this->errorLogger
, $e );
1379 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1382 $this->undoTransactionRoundFlags( $conn );
1388 throw new DBExpectedError(
1390 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1395 public function runMasterPostTrxCallbacks( $type ) {
1396 $e = null; // first exception
1397 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1398 $conn->setTrxEndCallbackSuppression( false );
1399 // Callbacks run in AUTO-COMMIT mode, so make sure no transactions are pending...
1400 if ( $conn->writesPending() ) {
1401 // This happens if onTransactionIdle() callbacks write to *other* handles
1402 // (which already finished their callbacks). Let any callbacks run in the final
1403 // commitMasterChanges() in LBFactory::shutdown(), when the transaction is gone.
1404 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1406 } elseif ( $conn->trxLevel() ) {
1407 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1408 // thus leaving an implicit read-only transaction open at this point. It
1409 // also happens if onTransactionIdle() callbacks leave implicit transactions
1410 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1411 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1415 $conn->runOnTransactionIdleCallbacks( $type );
1416 } catch ( Exception
$ex ) {
1420 $conn->runTransactionListenerCallbacks( $type );
1421 } catch ( Exception
$ex ) {
1429 public function rollbackMasterChanges( $fname = __METHOD__
) {
1430 $restore = ( $this->trxRoundId
!== false );
1431 $this->trxRoundId
= false;
1432 $this->forEachOpenMasterConnection(
1433 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1434 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1436 $this->undoTransactionRoundFlags( $conn );
1442 public function suppressTransactionEndCallbacks() {
1443 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1444 $conn->setTrxEndCallbackSuppression( true );
1449 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1451 * Some servers may have neither flag enabled, meaning that they opt out of such
1452 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1453 * when a DB server is used for something like simple key/value storage.
1455 * @param IDatabase $conn
1457 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1458 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1459 return; // transaction rounds do not apply to these connections
1462 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1463 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1464 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1465 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1468 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1469 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1474 * @param IDatabase $conn
1476 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1477 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1478 return; // transaction rounds do not apply to these connections
1481 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1482 $conn->setLBInfo( 'trxRoundId', false );
1485 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1486 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1490 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1491 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1492 $conn->flushSnapshot( __METHOD__
);
1496 public function hasMasterConnection() {
1497 return $this->isOpen( $this->getWriterIndex() );
1500 public function hasMasterChanges() {
1502 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1503 $pending |
= $conn->writesOrCallbacksPending();
1506 return (bool)$pending;
1509 public function lastMasterChangeTimestamp() {
1511 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1512 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1518 public function hasOrMadeRecentMasterChanges( $age = null ) {
1519 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1521 return ( $this->hasMasterChanges()
1522 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1525 public function pendingMasterChangeCallers() {
1527 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1528 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1534 public function getLaggedReplicaMode( $domain = false ) {
1535 // No-op if there is only one DB (also avoids recursion)
1536 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1538 // See if laggedReplicaMode gets set
1539 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1540 $this->reuseConnection( $conn );
1541 } catch ( DBConnectionError
$e ) {
1542 // Avoid expensive re-connect attempts and failures
1543 $this->allReplicasDownMode
= true;
1544 $this->laggedReplicaMode
= true;
1548 return $this->laggedReplicaMode
;
1552 * @param bool $domain
1554 * @deprecated 1.28; use getLaggedReplicaMode()
1556 public function getLaggedSlaveMode( $domain = false ) {
1557 return $this->getLaggedReplicaMode( $domain );
1560 public function laggedReplicaUsed() {
1561 return $this->laggedReplicaMode
;
1567 * @deprecated Since 1.28; use laggedReplicaUsed()
1569 public function laggedSlaveUsed() {
1570 return $this->laggedReplicaUsed();
1573 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1574 if ( $this->readOnlyReason
!== false ) {
1575 return $this->readOnlyReason
;
1576 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1577 if ( $this->allReplicasDownMode
) {
1578 return 'The database has been automatically locked ' .
1579 'until the replica database servers become available';
1581 return 'The database has been automatically locked ' .
1582 'while the replica database servers catch up to the master.';
1584 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1585 return 'The database master is running in read-only mode.';
1592 * @param string $domain Domain ID, or false for the current domain
1593 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1596 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1597 $cache = $this->wanCache
;
1598 $masterServer = $this->getServerName( $this->getWriterIndex() );
1600 return (bool)$cache->getWithSetCallback(
1601 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1602 self
::TTL_CACHE_READONLY
,
1603 function () use ( $domain, $conn ) {
1604 $old = $this->trxProfiler
->setSilenced( true );
1606 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1607 $readOnly = (int)$dbw->serverIsReadOnly();
1609 $this->reuseConnection( $dbw );
1611 } catch ( DBError
$e ) {
1614 $this->trxProfiler
->setSilenced( $old );
1617 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1621 public function allowLagged( $mode = null ) {
1622 if ( $mode === null ) {
1623 return $this->allowLagged
;
1625 $this->allowLagged
= $mode;
1627 return $this->allowLagged
;
1630 public function pingAll() {
1632 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1633 if ( !$conn->ping() ) {
1641 public function forEachOpenConnection( $callback, array $params = [] ) {
1642 foreach ( $this->conns
as $connsByServer ) {
1643 foreach ( $connsByServer as $serverConns ) {
1644 foreach ( $serverConns as $conn ) {
1645 $mergedParams = array_merge( [ $conn ], $params );
1646 call_user_func_array( $callback, $mergedParams );
1652 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1653 $masterIndex = $this->getWriterIndex();
1654 foreach ( $this->conns
as $connsByServer ) {
1655 if ( isset( $connsByServer[$masterIndex] ) ) {
1656 /** @var IDatabase $conn */
1657 foreach ( $connsByServer[$masterIndex] as $conn ) {
1658 $mergedParams = array_merge( [ $conn ], $params );
1659 call_user_func_array( $callback, $mergedParams );
1665 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1666 foreach ( $this->conns
as $connsByServer ) {
1667 foreach ( $connsByServer as $i => $serverConns ) {
1668 if ( $i === $this->getWriterIndex() ) {
1669 continue; // skip master
1671 foreach ( $serverConns as $conn ) {
1672 $mergedParams = array_merge( [ $conn ], $params );
1673 call_user_func_array( $callback, $mergedParams );
1679 public function getMaxLag( $domain = false ) {
1684 if ( $this->getServerCount() <= 1 ) {
1685 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1688 $lagTimes = $this->getLagTimes( $domain );
1689 foreach ( $lagTimes as $i => $lag ) {
1690 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1692 $host = $this->servers
[$i]['host'];
1697 return [ $host, $maxLag, $maxIndex ];
1700 public function getLagTimes( $domain = false ) {
1701 if ( $this->getServerCount() <= 1 ) {
1702 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1705 $knownLagTimes = []; // map of (server index => 0 seconds)
1706 $indexesWithLag = [];
1707 foreach ( $this->servers
as $i => $server ) {
1708 if ( empty( $server['is static'] ) ) {
1709 $indexesWithLag[] = $i; // DB server might have replication lag
1711 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1715 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1718 public function safeGetLag( IDatabase
$conn ) {
1719 if ( $this->getServerCount() <= 1 ) {
1722 return $conn->getLag();
1727 * @param IDatabase $conn
1728 * @param DBMasterPos|bool $pos
1729 * @param int|null $timeout
1732 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1733 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1735 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1736 return true; // server is not a replica DB
1740 // Get the current master position, opening a connection if needed
1741 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1742 if ( $masterConn ) {
1743 $pos = $masterConn->getMasterPos();
1745 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1746 $pos = $masterConn->getMasterPos();
1747 $this->closeConnection( $masterConn );
1751 if ( $pos instanceof DBMasterPos
) {
1752 $result = $conn->masterPosWait( $pos, $timeout );
1753 if ( $result == -1 ||
is_null( $result ) ) {
1754 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1755 $this->replLogger
->warning( $msg, [
1756 'host' => $conn->getServer(),
1758 'trace' => ( new RuntimeException() )->getTraceAsString()
1762 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1766 $ok = false; // something is misconfigured
1767 $this->replLogger
->error(
1768 __METHOD__
. ': could not get master pos for {host}',
1770 'host' => $conn->getServer(),
1771 'trace' => ( new RuntimeException() )->getTraceAsString()
1779 public function setTransactionListener( $name, callable
$callback = null ) {
1781 $this->trxRecurringCallbacks
[$name] = $callback;
1783 unset( $this->trxRecurringCallbacks
[$name] );
1785 $this->forEachOpenMasterConnection(
1786 function ( IDatabase
$conn ) use ( $name, $callback ) {
1787 $conn->setTransactionListener( $name, $callback );
1792 public function setTableAliases( array $aliases ) {
1793 $this->tableAliases
= $aliases;
1796 public function setIndexAliases( array $aliases ) {
1797 $this->indexAliases
= $aliases;
1800 public function setDomainPrefix( $prefix ) {
1801 // Find connections to explicit foreign domains still marked as in-use...
1803 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1804 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1805 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1806 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1807 $domainsInUse[] = $conn->getDomainID();
1811 // Do not switch connections to explicit foreign domains unless marked as safe
1812 if ( $domainsInUse ) {
1813 $domains = implode( ', ', $domainsInUse );
1814 throw new DBUnexpectedError( null,
1815 "Foreign domain connections are still in use ($domains)." );
1818 $oldDomain = $this->localDomain
->getId();
1819 $this->setLocalDomain( new DatabaseDomain(
1820 $this->localDomain
->getDatabase(),
1821 $this->localDomain
->getSchema(),
1825 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1826 if ( !$db->getLBInfo( 'foreign' ) ) {
1827 $db->tablePrefix( $prefix );
1833 * @param DatabaseDomain $domain
1835 private function setLocalDomain( DatabaseDomain
$domain ) {
1836 $this->localDomain
= $domain;
1837 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1838 // always true, gracefully handle the case when they fail to account for escaping.
1839 if ( $this->localDomain
->getTablePrefix() != '' ) {
1840 $this->localDomainIdAlias
=
1841 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1843 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1848 * Make PHP ignore user aborts/disconnects until the returned
1849 * value leaves scope. This returns null and does nothing in CLI mode.
1851 * @return ScopedCallback|null
1853 final protected function getScopedPHPBehaviorForCommit() {
1854 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1855 $old = ignore_user_abort( true ); // avoid half-finished operations
1856 return new ScopedCallback( function () use ( $old ) {
1857 ignore_user_abort( $old );
1864 function __destruct() {
1865 // Avoid connection leaks for sanity
1870 class_alias( LoadBalancer
::class, 'LoadBalancer' );