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 = [];
58 /** @var ILoadMonitor */
60 /** @var ChronologyProtector|null */
64 /** @var WANObjectCache */
66 /** @var object|string Class name or object With profileIn/profileOut methods */
68 /** @var TransactionProfiler */
69 protected $trxProfiler;
70 /** @var LoggerInterface */
71 protected $replLogger;
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var LoggerInterface */
77 protected $perfLogger;
79 /** @var Database DB connection object that caused a problem */
80 private $errorConnection;
81 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
83 /** @var bool|DBMasterPos False if not set */
85 /** @var bool Whether the generic reader fell back to a lagged replica DB */
86 private $laggedReplicaMode = false;
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $allReplicasDownMode = false;
89 /** @var string The last DB selection or connection error */
90 private $lastError = 'Unknown error';
91 /** @var string|bool Reason the LB is read-only or false if not */
92 private $readOnlyReason = false;
93 /** @var int Total connections opened */
94 private $connsOpened = 0;
95 /** @var string|bool String if a requested DBO_TRX transaction round is active */
96 private $trxRoundId = false;
97 /** @var array[] Map of (name => callable) */
98 private $trxRecurringCallbacks = [];
99 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
100 private $localDomain;
101 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
102 private $localDomainIdAlias;
103 /** @var string Current server name */
105 /** @var bool Whether this PHP instance is for a CLI script */
107 /** @var string Agent name for query profiling */
110 /** @var callable Exception logger */
111 private $errorLogger;
114 private $disabled = false;
116 private $chronProtInitialized = false;
118 private $maxLag = self
::MAX_LAG_DEFAULT
;
120 /** @var int Warn when this many connection are held */
121 const CONN_HELD_WARN_THRESHOLD
= 10;
123 /** @var int Default 'maxLag' when unspecified */
124 const MAX_LAG_DEFAULT
= 10;
125 /** @var int Default 'waitTimeout' when unspecified */
126 const MAX_WAIT_DEFAULT
= 10;
127 /** @var int Seconds to cache master server read-only status */
128 const TTL_CACHE_READONLY
= 5;
130 const KEY_LOCAL
= 'local';
131 const KEY_FOREIGN_FREE
= 'foreignFree';
132 const KEY_FOREIGN_INUSE
= 'foreignInUse';
134 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
135 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
136 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
138 public function __construct( array $params ) {
139 if ( !isset( $params['servers'] ) ) {
140 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
142 $this->servers
= $params['servers'];
143 foreach ( $this->servers
as $i => $server ) {
145 $this->servers
[$i]['master'] = true;
147 $this->servers
[$i]['replica'] = true;
151 $localDomain = isset( $params['localDomain'] )
152 ? DatabaseDomain
::newFromId( $params['localDomain'] )
153 : DatabaseDomain
::newUnspecified();
154 $this->setLocalDomain( $localDomain );
156 $this->waitTimeout
= isset( $params['waitTimeout'] )
157 ?
$params['waitTimeout']
158 : self
::MAX_WAIT_DEFAULT
;
160 $this->readIndex
= -1;
162 // Connection were transaction rounds may be applied
163 self
::KEY_LOCAL
=> [],
164 self
::KEY_FOREIGN_INUSE
=> [],
165 self
::KEY_FOREIGN_FREE
=> [],
166 // Auto-committing counterpart connections that ignore transaction rounds
167 self
::KEY_LOCAL_NOROUND
=> [],
168 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
169 self
::KEY_FOREIGN_FREE_NOROUND
=> []
172 $this->waitForPos
= false;
173 $this->allowLagged
= false;
175 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
176 $this->readOnlyReason
= $params['readOnlyReason'];
179 if ( isset( $params['maxLag'] ) ) {
180 $this->maxLag
= $params['maxLag'];
183 if ( isset( $params['loadMonitor'] ) ) {
184 $this->loadMonitorConfig
= $params['loadMonitor'];
186 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
188 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
190 foreach ( $params['servers'] as $i => $server ) {
191 $this->loads
[$i] = $server['load'];
192 if ( isset( $server['groupLoads'] ) ) {
193 foreach ( $server['groupLoads'] as $group => $ratio ) {
194 if ( !isset( $this->groupLoads
[$group] ) ) {
195 $this->groupLoads
[$group] = [];
197 $this->groupLoads
[$group][$i] = $ratio;
202 if ( isset( $params['srvCache'] ) ) {
203 $this->srvCache
= $params['srvCache'];
205 $this->srvCache
= new EmptyBagOStuff();
207 if ( isset( $params['wanCache'] ) ) {
208 $this->wanCache
= $params['wanCache'];
210 $this->wanCache
= WANObjectCache
::newEmpty();
212 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
213 if ( isset( $params['trxProfiler'] ) ) {
214 $this->trxProfiler
= $params['trxProfiler'];
216 $this->trxProfiler
= new TransactionProfiler();
219 $this->errorLogger
= isset( $params['errorLogger'] )
220 ?
$params['errorLogger']
221 : function ( Exception
$e ) {
222 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
225 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
226 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
229 $this->host
= isset( $params['hostname'] )
230 ?
$params['hostname']
231 : ( gethostname() ?
: 'unknown' );
232 $this->cliMode
= isset( $params['cliMode'] )
234 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
235 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
237 if ( isset( $params['chronologyProtector'] ) ) {
238 $this->chronProt
= $params['chronologyProtector'];
243 * Get the local (and default) database domain ID of connection handles
245 * @see DatabaseDomain
246 * @return string Database domain ID; this specifies DB name, schema, and table prefix
249 public function getLocalDomainID() {
250 return $this->localDomain
->getId();
254 * Get a LoadMonitor instance
256 * @return ILoadMonitor
258 private function getLoadMonitor() {
259 if ( !isset( $this->loadMonitor
) ) {
261 'LoadMonitor' => LoadMonitor
::class,
262 'LoadMonitorNull' => LoadMonitorNull
::class,
263 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
266 $class = $this->loadMonitorConfig
['class'];
267 if ( isset( $compat[$class] ) ) {
268 $class = $compat[$class];
271 $this->loadMonitor
= new $class(
272 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
273 $this->loadMonitor
->setLogger( $this->replLogger
);
276 return $this->loadMonitor
;
280 * @param array $loads
281 * @param bool|string $domain Domain to get non-lagged for
282 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
283 * @return bool|int|string
285 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
286 $lags = $this->getLagTimes( $domain );
288 # Unset excessively lagged servers
289 foreach ( $lags as $i => $lag ) {
291 # How much lag this server nominally is allowed to have
292 $maxServerLag = isset( $this->servers
[$i]['max lag'] )
293 ?
$this->servers
[$i]['max lag']
294 : $this->maxLag
; // default
295 # Constrain that futher by $maxLag argument
296 $maxServerLag = min( $maxServerLag, $maxLag );
298 $host = $this->getServerName( $i );
299 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
300 $this->replLogger
->error(
302 ": server {host} is not replicating?", [ 'host' => $host ] );
304 } elseif ( $lag > $maxServerLag ) {
305 $this->replLogger
->info(
307 ": server {host} has {lag} seconds of lag (>= {maxlag})",
308 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
315 # Find out if all the replica DBs with non-zero load are lagged
317 foreach ( $loads as $load ) {
321 # No appropriate DB servers except maybe the master and some replica DBs with zero load
322 # Do NOT use the master
323 # Instead, this function will return false, triggering read-only mode,
324 # and a lagged replica DB will be used instead.
328 if ( count( $loads ) == 0 ) {
332 # Return a random representative of the remainder
333 return ArrayUtils
::pickRandom( $loads );
336 public function getReaderIndex( $group = false, $domain = false ) {
337 if ( count( $this->servers
) == 1 ) {
338 // Skip the load balancing if there's only one server
339 return $this->getWriterIndex();
340 } elseif ( $group === false && $this->readIndex
>= 0 ) {
341 // Shortcut if the generic reader index was already cached
342 return $this->readIndex
;
345 if ( $group !== false ) {
346 // Use the server weight array for this load group
347 if ( isset( $this->groupLoads
[$group] ) ) {
348 $loads = $this->groupLoads
[$group];
350 // No loads for this group, return false and the caller can use some other group
351 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
356 // Use the generic load group
357 $loads = $this->loads
;
360 // Scale the configured load ratios according to each server's load and state
361 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
363 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
364 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
365 if ( $i === false ) {
366 // Replica DB connection unsuccessful
370 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
371 // Before any data queries are run, wait for the server to catch up to the
372 // specified position. This is used to improve session consistency. Note that
373 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
374 // so update laggedReplicaMode as needed for consistency.
375 if ( !$this->doWait( $i ) ) {
376 $laggedReplicaMode = true;
380 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
381 // Cache the generic reader index for future ungrouped DB_REPLICA handles
382 $this->readIndex
= $i;
383 // Record if the generic reader index is in "lagged replica DB" mode
384 if ( $laggedReplicaMode ) {
385 $this->laggedReplicaMode
= true;
389 $serverName = $this->getServerName( $i );
390 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
396 * @param array $loads List of server weights
397 * @param string|bool $domain
398 * @return array (reader index, lagged replica mode) or false on failure
400 private function pickReaderIndex( array $loads, $domain = false ) {
401 if ( !count( $loads ) ) {
402 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
405 /** @var int|bool $i Index of selected server */
407 /** @var bool $laggedReplicaMode Whether server is considered lagged */
408 $laggedReplicaMode = false;
410 // Quickly look through the available servers for a server that meets criteria...
411 $currentLoads = $loads;
412 while ( count( $currentLoads ) ) {
413 if ( $this->allowLagged ||
$laggedReplicaMode ) {
414 $i = ArrayUtils
::pickRandom( $currentLoads );
417 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
418 // ChronologyProtecter sets mWaitForPos for session consistency.
419 // This triggers doWait() after connect, so it's especially good to
420 // avoid lagged servers so as to avoid excessive delay in that method.
421 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
422 // Aim for <= 1 second of waiting (being too picky can backfire)
423 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
425 if ( $i === false ) {
426 // Any server with less lag than it's 'max lag' param is preferable
427 $i = $this->getRandomNonLagged( $currentLoads, $domain );
429 if ( $i === false && count( $currentLoads ) != 0 ) {
430 // All replica DBs lagged. Switch to read-only mode
431 $this->replLogger
->error(
432 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
433 $i = ArrayUtils
::pickRandom( $currentLoads );
434 $laggedReplicaMode = true;
438 if ( $i === false ) {
439 // pickRandom() returned false.
440 // This is permanent and means the configuration or the load monitor
441 // wants us to return false.
442 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
444 return [ false, false ];
447 $serverName = $this->getServerName( $i );
448 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
450 $conn = $this->openConnection( $i, $domain );
452 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
453 unset( $currentLoads[$i] ); // avoid this server next iteration
458 // Decrement reference counter, we are finished with this connection.
459 // It will be incremented for the caller later.
460 if ( $domain !== false ) {
461 $this->reuseConnection( $conn );
464 // Return this server
468 // If all servers were down, quit now
469 if ( !count( $currentLoads ) ) {
470 $this->connLogger
->error( __METHOD__
. ": all servers down" );
473 return [ $i, $laggedReplicaMode ];
476 public function waitFor( $pos ) {
477 $oldPos = $this->waitForPos
;
479 $this->waitForPos
= $pos;
480 // If a generic reader connection was already established, then wait now
481 $i = $this->readIndex
;
483 if ( !$this->doWait( $i ) ) {
484 $this->laggedReplicaMode
= true;
488 // Restore the older position if it was higher since this is used for lag-protection
489 $this->setWaitForPositionIfHigher( $oldPos );
493 public function waitForOne( $pos, $timeout = null ) {
494 $oldPos = $this->waitForPos
;
496 $this->waitForPos
= $pos;
498 $i = $this->readIndex
;
500 // Pick a generic replica DB if there isn't one yet
501 $readLoads = $this->loads
;
502 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
503 $readLoads = array_filter( $readLoads ); // with non-zero load
504 $i = ArrayUtils
::pickRandom( $readLoads );
508 $ok = $this->doWait( $i, true, $timeout );
510 $ok = true; // no applicable loads
513 # Restore the old position, as this is not used for lag-protection but for throttling
514 $this->waitForPos
= $oldPos;
520 public function waitForAll( $pos, $timeout = null ) {
521 $timeout = $timeout ?
: $this->waitTimeout
;
523 $oldPos = $this->waitForPos
;
525 $this->waitForPos
= $pos;
526 $serverCount = count( $this->servers
);
529 for ( $i = 1; $i < $serverCount; $i++
) {
530 if ( $this->loads
[$i] > 0 ) {
531 $start = microtime( true );
532 $ok = $this->doWait( $i, true, $timeout ) && $ok;
533 $timeout -= ( microtime( true ) - $start );
534 if ( $timeout <= 0 ) {
535 break; // timeout reached
540 # Restore the old position, as this is not used for lag-protection but for throttling
541 $this->waitForPos
= $oldPos;
548 * @param DBMasterPos|bool $pos
550 private function setWaitForPositionIfHigher( $pos ) {
555 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
556 $this->waitForPos
= $pos;
562 * @return IDatabase|bool
564 public function getAnyOpenConnection( $i ) {
565 foreach ( $this->conns
as $connsByServer ) {
566 if ( !empty( $connsByServer[$i] ) ) {
567 /** @var IDatabase[] $serverConns */
568 $serverConns = $connsByServer[$i];
570 return reset( $serverConns );
578 * Wait for a given replica DB to catch up to the master pos stored in $this
579 * @param int $index Server index
580 * @param bool $open Check the server even if a new connection has to be made
581 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
584 protected function doWait( $index, $open = false, $timeout = null ) {
585 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
587 // Check if we already know that the DB has reached this point
588 $server = $this->getServerName( $index );
589 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
590 /** @var DBMasterPos $knownReachedPos */
591 $knownReachedPos = $this->srvCache
->get( $key );
593 $knownReachedPos instanceof DBMasterPos
&&
594 $knownReachedPos->hasReached( $this->waitForPos
)
596 $this->replLogger
->debug(
598 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
599 [ 'dbserver' => $server ]
604 // Find a connection to wait on, creating one if needed and allowed
605 $close = false; // close the connection afterwards
606 $conn = $this->getAnyOpenConnection( $index );
609 $this->replLogger
->debug(
610 __METHOD__
. ': no connection open for {dbserver}',
611 [ 'dbserver' => $server ]
616 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
618 $this->replLogger
->warning(
619 __METHOD__
. ': failed to connect to {dbserver}',
620 [ 'dbserver' => $server ]
625 // Avoid connection spam in waitForAll() when connections
626 // are made just for the sake of doing this lag check.
631 $this->replLogger
->info(
633 ': waiting for replica DB {dbserver} to catch up...',
634 [ 'dbserver' => $server ]
637 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
639 if ( $result === null ) {
640 $this->replLogger
->warning(
641 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
644 'pos' => $this->waitForPos
,
645 'trace' => ( new RuntimeException() )->getTraceAsString()
649 } elseif ( $result == -1 ) {
650 $this->replLogger
->warning(
651 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
654 'pos' => $this->waitForPos
,
655 'trace' => ( new RuntimeException() )->getTraceAsString()
660 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
662 // Remember that the DB reached this point
663 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
667 $this->closeConnection( $conn );
673 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
674 if ( $i === null ||
$i === false ) {
675 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
676 ' with invalid server index' );
679 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
680 $domain = false; // local connection requested
683 if ( ( $flags & self
::CONN_TRX_AUTO
) === self
::CONN_TRX_AUTO
) {
684 // Assuming all servers are of the same type (or similar), which is overwhelmingly
685 // the case, use the master server information to get the attributes. The information
686 // for $i cannot be used since it might be DB_REPLICA, which might require connection
687 // attempts in order to be resolved into a real server index.
688 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
689 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
690 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
691 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
692 // to reduce lock contention. None of these apply for sqlite and using separate
693 // connections just causes self-deadlocks.
694 $flags &= ~self
::CONN_TRX_AUTO
;
695 $this->connLogger
->info( __METHOD__
. ': ignoring CONN_TRX_AUTO to avoid deadlocks.' );
699 $groups = ( $groups === false ||
$groups === [] )
700 ?
[ false ] // check one "group": the generic pool
703 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
704 $oldConnsOpened = $this->connsOpened
; // connections open now
706 if ( $i == self
::DB_MASTER
) {
707 $i = $this->getWriterIndex();
709 # Try to find an available server in any the query groups (in order)
710 foreach ( $groups as $group ) {
711 $groupIndex = $this->getReaderIndex( $group, $domain );
712 if ( $groupIndex !== false ) {
719 # Operation-based index
720 if ( $i == self
::DB_REPLICA
) {
721 $this->lastError
= 'Unknown error'; // reset error string
722 # Try the general server pool if $groups are unavailable.
723 $i = ( $groups === [ false ] )
724 ?
false // don't bother with this if that is what was tried above
725 : $this->getReaderIndex( false, $domain );
726 # Couldn't find a working server in getReaderIndex()?
727 if ( $i === false ) {
728 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
729 // Throw an exception
730 $this->reportConnectionError();
731 return null; // not reached
735 # Now we have an explicit index into the servers array
736 $conn = $this->openConnection( $i, $domain, $flags );
738 // Throw an exception
739 $this->reportConnectionError();
740 return null; // not reached
743 # Profile any new connections that happen
744 if ( $this->connsOpened
> $oldConnsOpened ) {
745 $host = $conn->getServer();
746 $dbname = $conn->getDBname();
747 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
751 # Make master-requested DB handles inherit any read-only mode setting
752 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
758 public function reuseConnection( IDatabase
$conn ) {
759 $serverIndex = $conn->getLBInfo( 'serverIndex' );
760 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
761 if ( $serverIndex === null ||
$refCount === null ) {
763 * This can happen in code like:
764 * foreach ( $dbs as $db ) {
765 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
767 * $lb->reuseConnection( $conn );
769 * When a connection to the local DB is opened in this way, reuseConnection()
773 } elseif ( $conn instanceof DBConnRef
) {
774 // DBConnRef already handles calling reuseConnection() and only passes the live
775 // Database instance to this method. Any caller passing in a DBConnRef is broken.
776 $this->connLogger
->error(
777 __METHOD__
. ": got DBConnRef instance.\n" .
778 ( new RuntimeException() )->getTraceAsString() );
783 if ( $this->disabled
) {
784 return; // DBConnRef handle probably survived longer than the LoadBalancer
787 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
788 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
789 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
791 $connFreeKey = self
::KEY_FOREIGN_FREE
;
792 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
795 $domain = $conn->getDomainID();
796 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
797 throw new InvalidArgumentException( __METHOD__
.
798 ": connection $serverIndex/$domain not found; it may have already been freed." );
799 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
800 throw new InvalidArgumentException( __METHOD__
.
801 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
804 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
805 if ( $refCount <= 0 ) {
806 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
807 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
808 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
809 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
811 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
813 $this->connLogger
->debug( __METHOD__
.
814 ": reference count for $serverIndex/$domain reduced to $refCount" );
818 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
819 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
821 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
824 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
825 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
827 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
830 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
831 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
833 return new MaintainableDBConnRef(
834 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
837 public function openConnection( $i, $domain = false, $flags = 0 ) {
838 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
839 $domain = false; // local connection requested
842 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
843 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
844 // Load CP positions before connecting so that doWait() triggers later if needed
845 $this->chronProtInitialized
= true;
846 $this->chronProt
->initLB( $this );
849 // Check if an auto-commit connection is being requested. If so, it will not reuse the
850 // main set of DB connections but rather its own pool since:
851 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
852 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
853 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
855 if ( $domain !== false ) {
856 // Connection is to a foreign domain
857 $conn = $this->openForeignConnection( $i, $domain, $flags );
859 // Connection is to the local domain
860 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
861 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
862 $conn = $this->conns
[$connKey][$i][0];
864 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
865 throw new InvalidArgumentException( "No server with index '$i'." );
867 // Open a new connection
868 $server = $this->servers
[$i];
869 $server['serverIndex'] = $i;
870 $server['autoCommitOnly'] = $autoCommit;
871 if ( $this->localDomain
->getDatabase() !== null ) {
872 // Use the local domain table prefix if the local domain is specified
873 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
875 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
876 $host = $this->getServerName( $i );
877 if ( $conn->isOpen() ) {
878 $this->connLogger
->debug(
879 __METHOD__
. ": connected to database $i at '$host'." );
880 $this->conns
[$connKey][$i][0] = $conn;
882 $this->connLogger
->warning(
883 __METHOD__
. ": failed to connect to database $i at '$host'." );
884 $this->errorConnection
= $conn;
890 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
891 // Connection was made but later unrecoverably lost for some reason.
892 // Do not return a handle that will just throw exceptions on use,
893 // but let the calling code (e.g. getReaderIndex) try another server.
894 // See DatabaseMyslBase::ping() for how this can happen.
895 $this->errorConnection
= $conn;
899 if ( $autoCommit && $conn instanceof IDatabase
) {
900 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
907 * Open a connection to a foreign DB, or return one if it is already open.
909 * Increments a reference count on the returned connection which locks the
910 * connection to the requested domain. This reference count can be
911 * decremented by calling reuseConnection().
913 * If a connection is open to the appropriate server already, but with the wrong
914 * database, it will be switched to the right database and returned, as long as
915 * it has been freed first with reuseConnection().
917 * On error, returns false, and the connection which caused the
918 * error will be available via $this->errorConnection.
920 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
922 * @param int $i Server index
923 * @param string $domain Domain ID to open
924 * @param int $flags Class CONN_* constant bitfield
927 private function openForeignConnection( $i, $domain, $flags = 0 ) {
928 $domainInstance = DatabaseDomain
::newFromId( $domain );
929 $dbName = $domainInstance->getDatabase();
930 $prefix = $domainInstance->getTablePrefix();
931 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTO
) == self
::CONN_TRX_AUTO
);
934 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
935 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
937 $connFreeKey = self
::KEY_FOREIGN_FREE
;
938 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
941 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
942 // Reuse an in-use connection for the same domain
943 $conn = $this->conns
[$connInUseKey][$i][$domain];
944 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
945 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
946 // Reuse a free connection for the same domain
947 $conn = $this->conns
[$connFreeKey][$i][$domain];
948 unset( $this->conns
[$connFreeKey][$i][$domain] );
949 $this->conns
[$connInUseKey][$i][$domain] = $conn;
950 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
951 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
952 // Reuse a free connection from another domain
953 $conn = reset( $this->conns
[$connFreeKey][$i] );
954 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
955 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
956 $this->lastError
= "Error selecting database '$dbName' on server " .
957 $conn->getServer() . " from client host {$this->host}";
958 $this->errorConnection
= $conn;
961 $conn->tablePrefix( $prefix );
962 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
963 // Note that if $domain is an empty string, getDomainID() might not match it
964 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
965 $this->connLogger
->debug( __METHOD__
.
966 ": reusing free connection from $oldDomain for $domain" );
969 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
970 throw new InvalidArgumentException( "No server with index '$i'." );
972 // Open a new connection
973 $server = $this->servers
[$i];
974 $server['serverIndex'] = $i;
975 $server['foreignPoolRefCount'] = 0;
976 $server['foreign'] = true;
977 $server['autoCommitOnly'] = $autoCommit;
978 $conn = $this->reallyOpenConnection( $server, $domainInstance );
979 if ( !$conn->isOpen() ) {
980 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
981 $this->errorConnection
= $conn;
984 $conn->tablePrefix( $prefix ); // as specified
985 // Note that if $domain is an empty string, getDomainID() might not match it
986 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
987 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
991 // Increment reference count
992 if ( $conn instanceof IDatabase
) {
993 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
994 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1000 public function getServerAttributes( $i ) {
1001 return Database
::attributesFromType(
1002 $this->getServerType( $i ),
1003 isset( $this->servers
[$i]['driver'] ) ?
$this->servers
[$i]['driver'] : null
1008 * Test if the specified index represents an open connection
1010 * @param int $index Server index
1014 private function isOpen( $index ) {
1015 if ( !is_int( $index ) ) {
1019 return (bool)$this->getAnyOpenConnection( $index );
1023 * Open a new network connection to a server (uncached)
1025 * Returns a Database object whether or not the connection was successful.
1027 * @param array $server
1028 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1030 * @throws DBAccessError
1031 * @throws InvalidArgumentException
1033 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1034 if ( $this->disabled
) {
1035 throw new DBAccessError();
1038 // Handle $domainOverride being a specified or an unspecified domain
1039 if ( $domainOverride->getDatabase() === null ) {
1040 // Normally, an RDBMS requires a DB name specified on connection and the $server
1041 // configuration array is assumed to already specify an appropriate DB name.
1042 if ( $server['type'] === 'mysql' ) {
1043 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1044 // and the DB name in $server might not exist due to legacy reasons (the default
1045 // domain used to ignore the local LB domain, even when mismatched).
1046 $server['dbname'] = null;
1049 $server['dbname'] = $domainOverride->getDatabase();
1050 $server['schema'] = $domainOverride->getSchema();
1053 // Let the handle know what the cluster master is (e.g. "db1052")
1054 $masterName = $this->getServerName( $this->getWriterIndex() );
1055 $server['clusterMasterHost'] = $masterName;
1057 // Log when many connection are made on requests
1058 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1059 $this->perfLogger
->warning( __METHOD__
. ": " .
1060 "{$this->connsOpened}+ connections made (master=$masterName)" );
1063 $server['srvCache'] = $this->srvCache
;
1064 // Set loggers and profilers
1065 $server['connLogger'] = $this->connLogger
;
1066 $server['queryLogger'] = $this->queryLogger
;
1067 $server['errorLogger'] = $this->errorLogger
;
1068 $server['profiler'] = $this->profiler
;
1069 $server['trxProfiler'] = $this->trxProfiler
;
1070 // Use the same agent and PHP mode for all DB handles
1071 $server['cliMode'] = $this->cliMode
;
1072 $server['agent'] = $this->agent
;
1073 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1074 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1075 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1077 // Create a live connection object
1079 $db = Database
::factory( $server['type'], $server );
1080 } catch ( DBConnectionError
$e ) {
1081 // FIXME: This is probably the ugliest thing I have ever done to
1082 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1086 $db->setLBInfo( $server );
1087 $db->setLazyMasterHandle(
1088 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1090 $db->setTableAliases( $this->tableAliases
);
1092 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1093 if ( $this->trxRoundId
!== false ) {
1094 $this->applyTransactionRoundFlags( $db );
1096 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1097 $db->setTransactionListener( $name, $callback );
1105 * @throws DBConnectionError
1107 private function reportConnectionError() {
1108 $conn = $this->errorConnection
; // the connection which caused the error
1110 'method' => __METHOD__
,
1111 'last_error' => $this->lastError
,
1114 if ( $conn instanceof IDatabase
) {
1115 $context['db_server'] = $conn->getServer();
1116 $this->connLogger
->warning(
1117 __METHOD__
. ": connection error: {last_error} ({db_server})",
1121 // throws DBConnectionError
1122 $conn->reportConnectionError( "{$this->lastError} ({$context['db_server']})" );
1124 // No last connection, probably due to all servers being too busy
1125 $this->connLogger
->error(
1127 ": LB failure with no last connection. Connection error: {last_error}",
1131 // If all servers were busy, mLastError will contain something sensible
1132 throw new DBConnectionError( null, $this->lastError
);
1136 public function getWriterIndex() {
1140 public function haveIndex( $i ) {
1141 return array_key_exists( $i, $this->servers
);
1144 public function isNonZeroLoad( $i ) {
1145 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1148 public function getServerCount() {
1149 return count( $this->servers
);
1152 public function getServerName( $i ) {
1153 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1154 $name = $this->servers
[$i]['hostName'];
1155 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1156 $name = $this->servers
[$i]['host'];
1161 return ( $name != '' ) ?
$name : 'localhost';
1164 public function getServerType( $i ) {
1165 return isset( $this->servers
[$i]['type'] ) ?
$this->servers
[$i]['type'] : 'unknown';
1168 public function getMasterPos() {
1169 # If this entire request was served from a replica DB without opening a connection to the
1170 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1171 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1172 if ( !$masterConn ) {
1173 $serverCount = count( $this->servers
);
1174 for ( $i = 1; $i < $serverCount; $i++
) {
1175 $conn = $this->getAnyOpenConnection( $i );
1177 return $conn->getReplicaPos();
1181 return $masterConn->getMasterPos();
1187 public function disable() {
1189 $this->disabled
= true;
1192 public function closeAll() {
1193 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1194 $host = $conn->getServer();
1195 $this->connLogger
->debug(
1196 __METHOD__
. ": closing connection to database '$host'." );
1201 self
::KEY_LOCAL
=> [],
1202 self
::KEY_FOREIGN_INUSE
=> [],
1203 self
::KEY_FOREIGN_FREE
=> [],
1204 self
::KEY_LOCAL_NOROUND
=> [],
1205 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1206 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1208 $this->connsOpened
= 0;
1211 public function closeConnection( IDatabase
$conn ) {
1212 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1213 foreach ( $this->conns
as $type => $connsByServer ) {
1214 if ( !isset( $connsByServer[$serverIndex] ) ) {
1218 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1219 if ( $conn === $trackedConn ) {
1220 $host = $this->getServerName( $i );
1221 $this->connLogger
->debug(
1222 __METHOD__
. ": closing connection to database $i at '$host'." );
1223 unset( $this->conns
[$type][$serverIndex][$i] );
1224 --$this->connsOpened
;
1233 public function commitAll( $fname = __METHOD__
) {
1236 $restore = ( $this->trxRoundId
!== false );
1237 $this->trxRoundId
= false;
1238 $this->forEachOpenConnection(
1239 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1241 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1242 } catch ( DBError
$e ) {
1243 call_user_func( $this->errorLogger
, $e );
1244 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1246 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1247 $this->undoTransactionRoundFlags( $conn );
1253 throw new DBExpectedError(
1255 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1260 public function finalizeMasterChanges() {
1261 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1262 // Any error should cause all DB transactions to be rolled back together
1263 $conn->setTrxEndCallbackSuppression( false );
1264 $conn->runOnTransactionPreCommitCallbacks();
1265 // Defer post-commit callbacks until COMMIT finishes for all DBs
1266 $conn->setTrxEndCallbackSuppression( true );
1270 public function approveMasterChanges( array $options ) {
1271 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1272 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1273 // If atomic sections or explicit transactions are still open, some caller must have
1274 // caught an exception but failed to properly rollback any changes. Detect that and
1275 // throw and error (causing rollback).
1276 if ( $conn->explicitTrxActive() ) {
1277 throw new DBTransactionError(
1279 "Explicit transaction still active. A caller may have caught an error."
1282 // Assert that the time to replicate the transaction will be sane.
1283 // If this fails, then all DB transactions will be rollback back together.
1284 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1285 if ( $limit > 0 && $time > $limit ) {
1286 throw new DBTransactionSizeError(
1288 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1292 // If a connection sits idle while slow queries execute on another, that connection
1293 // may end up dropped before the commit round is reached. Ping servers to detect this.
1294 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1295 throw new DBTransactionError(
1297 "A connection to the {$conn->getDBname()} database was lost before commit."
1303 public function beginMasterChanges( $fname = __METHOD__
) {
1304 if ( $this->trxRoundId
!== false ) {
1305 throw new DBTransactionError(
1307 "$fname: Transaction round '{$this->trxRoundId}' already started."
1310 $this->trxRoundId
= $fname;
1313 $this->forEachOpenMasterConnection(
1314 function ( Database
$conn ) use ( $fname, &$failures ) {
1315 $conn->setTrxEndCallbackSuppression( true );
1317 $conn->flushSnapshot( $fname );
1318 } catch ( DBError
$e ) {
1319 call_user_func( $this->errorLogger
, $e );
1320 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1322 $conn->setTrxEndCallbackSuppression( false );
1323 $this->applyTransactionRoundFlags( $conn );
1328 throw new DBExpectedError(
1330 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1335 public function commitMasterChanges( $fname = __METHOD__
) {
1338 /** @noinspection PhpUnusedLocalVariableInspection */
1339 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1341 $restore = ( $this->trxRoundId
!== false );
1342 $this->trxRoundId
= false;
1343 $this->forEachOpenMasterConnection(
1344 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1346 if ( $conn->writesOrCallbacksPending() ) {
1347 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1348 } elseif ( $restore ) {
1349 $conn->flushSnapshot( $fname );
1351 } catch ( DBError
$e ) {
1352 call_user_func( $this->errorLogger
, $e );
1353 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1356 $this->undoTransactionRoundFlags( $conn );
1362 throw new DBExpectedError(
1364 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1369 public function runMasterPostTrxCallbacks( $type ) {
1370 $e = null; // first exception
1371 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1372 $conn->setTrxEndCallbackSuppression( false );
1373 if ( $conn->writesOrCallbacksPending() ) {
1374 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1375 // (which finished its callbacks already). Warn and recover in this case. Let the
1376 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1377 $this->queryLogger
->info( __METHOD__
. ": found writes/callbacks pending." );
1379 } elseif ( $conn->trxLevel() ) {
1380 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1381 // thus leaving an implicit read-only transaction open at this point. It
1382 // also happens if onTransactionIdle() callbacks leave implicit transactions
1383 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1384 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1388 $conn->runOnTransactionIdleCallbacks( $type );
1389 } catch ( Exception
$ex ) {
1393 $conn->runTransactionListenerCallbacks( $type );
1394 } catch ( Exception
$ex ) {
1402 public function rollbackMasterChanges( $fname = __METHOD__
) {
1403 $restore = ( $this->trxRoundId
!== false );
1404 $this->trxRoundId
= false;
1405 $this->forEachOpenMasterConnection(
1406 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1407 if ( $conn->writesOrCallbacksPending() ||
$conn->explicitTrxActive() ) {
1408 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1411 $this->undoTransactionRoundFlags( $conn );
1417 public function suppressTransactionEndCallbacks() {
1418 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1419 $conn->setTrxEndCallbackSuppression( true );
1424 * @param IDatabase $conn
1426 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1427 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1428 return; // transaction rounds do not apply to these connections
1431 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1432 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1433 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1434 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1435 // If config has explicitly requested DBO_TRX be either on or off by not
1436 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1437 // for things like blob stores (ExternalStore) which want auto-commit mode.
1442 * @param IDatabase $conn
1444 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1445 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1446 return; // transaction rounds do not apply to these connections
1449 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1450 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1454 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1455 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1456 $conn->flushSnapshot( __METHOD__
);
1460 public function hasMasterConnection() {
1461 return $this->isOpen( $this->getWriterIndex() );
1464 public function hasMasterChanges() {
1466 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1467 $pending |
= $conn->writesOrCallbacksPending();
1470 return (bool)$pending;
1473 public function lastMasterChangeTimestamp() {
1475 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1476 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1482 public function hasOrMadeRecentMasterChanges( $age = null ) {
1483 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1485 return ( $this->hasMasterChanges()
1486 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1489 public function pendingMasterChangeCallers() {
1491 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1492 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1498 public function getLaggedReplicaMode( $domain = false ) {
1499 // No-op if there is only one DB (also avoids recursion)
1500 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1502 // See if laggedReplicaMode gets set
1503 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1504 $this->reuseConnection( $conn );
1505 } catch ( DBConnectionError
$e ) {
1506 // Avoid expensive re-connect attempts and failures
1507 $this->allReplicasDownMode
= true;
1508 $this->laggedReplicaMode
= true;
1512 return $this->laggedReplicaMode
;
1516 * @param bool $domain
1518 * @deprecated 1.28; use getLaggedReplicaMode()
1520 public function getLaggedSlaveMode( $domain = false ) {
1521 return $this->getLaggedReplicaMode( $domain );
1524 public function laggedReplicaUsed() {
1525 return $this->laggedReplicaMode
;
1531 * @deprecated Since 1.28; use laggedReplicaUsed()
1533 public function laggedSlaveUsed() {
1534 return $this->laggedReplicaUsed();
1537 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1538 if ( $this->readOnlyReason
!== false ) {
1539 return $this->readOnlyReason
;
1540 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1541 if ( $this->allReplicasDownMode
) {
1542 return 'The database has been automatically locked ' .
1543 'until the replica database servers become available';
1545 return 'The database has been automatically locked ' .
1546 'while the replica database servers catch up to the master.';
1548 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1549 return 'The database master is running in read-only mode.';
1556 * @param string $domain Domain ID, or false for the current domain
1557 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1560 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1561 $cache = $this->wanCache
;
1562 $masterServer = $this->getServerName( $this->getWriterIndex() );
1564 return (bool)$cache->getWithSetCallback(
1565 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1566 self
::TTL_CACHE_READONLY
,
1567 function () use ( $domain, $conn ) {
1568 $old = $this->trxProfiler
->setSilenced( true );
1570 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1571 $readOnly = (int)$dbw->serverIsReadOnly();
1573 $this->reuseConnection( $dbw );
1575 } catch ( DBError
$e ) {
1578 $this->trxProfiler
->setSilenced( $old );
1581 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1585 public function allowLagged( $mode = null ) {
1586 if ( $mode === null ) {
1587 return $this->allowLagged
;
1589 $this->allowLagged
= $mode;
1591 return $this->allowLagged
;
1594 public function pingAll() {
1596 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1597 if ( !$conn->ping() ) {
1605 public function forEachOpenConnection( $callback, array $params = [] ) {
1606 foreach ( $this->conns
as $connsByServer ) {
1607 foreach ( $connsByServer as $serverConns ) {
1608 foreach ( $serverConns as $conn ) {
1609 $mergedParams = array_merge( [ $conn ], $params );
1610 call_user_func_array( $callback, $mergedParams );
1616 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1617 $masterIndex = $this->getWriterIndex();
1618 foreach ( $this->conns
as $connsByServer ) {
1619 if ( isset( $connsByServer[$masterIndex] ) ) {
1620 /** @var IDatabase $conn */
1621 foreach ( $connsByServer[$masterIndex] as $conn ) {
1622 $mergedParams = array_merge( [ $conn ], $params );
1623 call_user_func_array( $callback, $mergedParams );
1629 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1630 foreach ( $this->conns
as $connsByServer ) {
1631 foreach ( $connsByServer as $i => $serverConns ) {
1632 if ( $i === $this->getWriterIndex() ) {
1633 continue; // skip master
1635 foreach ( $serverConns as $conn ) {
1636 $mergedParams = array_merge( [ $conn ], $params );
1637 call_user_func_array( $callback, $mergedParams );
1643 public function getMaxLag( $domain = false ) {
1648 if ( $this->getServerCount() <= 1 ) {
1649 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1652 $lagTimes = $this->getLagTimes( $domain );
1653 foreach ( $lagTimes as $i => $lag ) {
1654 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1656 $host = $this->servers
[$i]['host'];
1661 return [ $host, $maxLag, $maxIndex ];
1664 public function getLagTimes( $domain = false ) {
1665 if ( $this->getServerCount() <= 1 ) {
1666 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1669 $knownLagTimes = []; // map of (server index => 0 seconds)
1670 $indexesWithLag = [];
1671 foreach ( $this->servers
as $i => $server ) {
1672 if ( empty( $server['is static'] ) ) {
1673 $indexesWithLag[] = $i; // DB server might have replication lag
1675 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1679 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1682 public function safeGetLag( IDatabase
$conn ) {
1683 if ( $this->getServerCount() <= 1 ) {
1686 return $conn->getLag();
1691 * @param IDatabase $conn
1692 * @param DBMasterPos|bool $pos
1693 * @param int|null $timeout
1696 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1697 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1699 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1700 return true; // server is not a replica DB
1704 // Get the current master position, opening a connection if needed
1705 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1706 if ( $masterConn ) {
1707 $pos = $masterConn->getMasterPos();
1709 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1710 $pos = $masterConn->getMasterPos();
1711 $this->closeConnection( $masterConn );
1715 if ( $pos instanceof DBMasterPos
) {
1716 $result = $conn->masterPosWait( $pos, $timeout );
1717 if ( $result == -1 ||
is_null( $result ) ) {
1718 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1719 $this->replLogger
->warning( $msg, [
1720 'host' => $conn->getServer(),
1722 'trace' => ( new RuntimeException() )->getTraceAsString()
1726 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1730 $ok = false; // something is misconfigured
1731 $this->replLogger
->error(
1732 __METHOD__
. ': could not get master pos for {host}',
1734 'host' => $conn->getServer(),
1735 'trace' => ( new RuntimeException() )->getTraceAsString()
1743 public function setTransactionListener( $name, callable
$callback = null ) {
1745 $this->trxRecurringCallbacks
[$name] = $callback;
1747 unset( $this->trxRecurringCallbacks
[$name] );
1749 $this->forEachOpenMasterConnection(
1750 function ( IDatabase
$conn ) use ( $name, $callback ) {
1751 $conn->setTransactionListener( $name, $callback );
1756 public function setTableAliases( array $aliases ) {
1757 $this->tableAliases
= $aliases;
1760 public function setDomainPrefix( $prefix ) {
1761 // Find connections to explicit foreign domains still marked as in-use...
1763 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1764 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1765 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1766 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1767 $domainsInUse[] = $conn->getDomainID();
1771 // Do not switch connections to explicit foreign domains unless marked as safe
1772 if ( $domainsInUse ) {
1773 $domains = implode( ', ', $domainsInUse );
1774 throw new DBUnexpectedError( null,
1775 "Foreign domain connections are still in use ($domains)." );
1778 $oldDomain = $this->localDomain
->getId();
1779 $this->setLocalDomain( new DatabaseDomain(
1780 $this->localDomain
->getDatabase(),
1781 $this->localDomain
->getSchema(),
1785 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1786 if ( !$db->getLBInfo( 'foreign' ) ) {
1787 $db->tablePrefix( $prefix );
1793 * @param DatabaseDomain $domain
1795 private function setLocalDomain( DatabaseDomain
$domain ) {
1796 $this->localDomain
= $domain;
1797 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1798 // always true, gracefully handle the case when they fail to account for escaping.
1799 if ( $this->localDomain
->getTablePrefix() != '' ) {
1800 $this->localDomainIdAlias
=
1801 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1803 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1808 * Make PHP ignore user aborts/disconnects until the returned
1809 * value leaves scope. This returns null and does nothing in CLI mode.
1811 * @return ScopedCallback|null
1813 final protected function getScopedPHPBehaviorForCommit() {
1814 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1815 $old = ignore_user_abort( true ); // avoid half-finished operations
1816 return new ScopedCallback( function () use ( $old ) {
1817 ignore_user_abort( $old );
1824 function __destruct() {
1825 // Avoid connection leaks for sanity
1830 class_alias( LoadBalancer
::class, 'LoadBalancer' );