Special case opus mime detction
[mediawiki.git] / includes / libs / rdbms / loadbalancer / LoadBalancer.php
blob95f55b6a86d7bcad6f9c7ec92fb7355046f126ed
1 <?php
2 /**
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
20 * @file
21 * @ingroup Database
23 use Psr\Log\LoggerInterface;
24 use Wikimedia\ScopedCallback;
26 /**
27 * Database connection, tracking, load balancing, and transaction manager for a cluster
29 * @ingroup Database
31 class LoadBalancer implements ILoadBalancer {
32 /** @var array[] Map of (server index => server config array) */
33 private $mServers;
34 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
35 private $mConns;
36 /** @var float[] Map of (server index => weight) */
37 private $mLoads;
38 /** @var array[] Map of (group => server index => weight) */
39 private $mGroupLoads;
40 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
41 private $mAllowLagged;
42 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
43 private $mWaitTimeout;
44 /** @var array The LoadMonitor configuration */
45 private $loadMonitorConfig;
46 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
47 private $tableAliases = [];
49 /** @var ILoadMonitor */
50 private $loadMonitor;
51 /** @var BagOStuff */
52 private $srvCache;
53 /** @var BagOStuff */
54 private $memCache;
55 /** @var WANObjectCache */
56 private $wanCache;
57 /** @var object|string Class name or object With profileIn/profileOut methods */
58 protected $profiler;
59 /** @var TransactionProfiler */
60 protected $trxProfiler;
61 /** @var LoggerInterface */
62 protected $replLogger;
63 /** @var LoggerInterface */
64 protected $connLogger;
65 /** @var LoggerInterface */
66 protected $queryLogger;
67 /** @var LoggerInterface */
68 protected $perfLogger;
70 /** @var bool|IDatabase Database connection that caused a problem */
71 private $mErrorConnection;
72 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
73 private $mReadIndex;
74 /** @var bool|DBMasterPos False if not set */
75 private $mWaitForPos;
76 /** @var bool Whether the generic reader fell back to a lagged replica DB */
77 private $laggedReplicaMode = false;
78 /** @var bool Whether the generic reader fell back to a lagged replica DB */
79 private $allReplicasDownMode = false;
80 /** @var string The last DB selection or connection error */
81 private $mLastError = 'Unknown error';
82 /** @var string|bool Reason the LB is read-only or false if not */
83 private $readOnlyReason = false;
84 /** @var integer Total connections opened */
85 private $connsOpened = 0;
86 /** @var string|bool String if a requested DBO_TRX transaction round is active */
87 private $trxRoundId = false;
88 /** @var array[] Map of (name => callable) */
89 private $trxRecurringCallbacks = [];
90 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
91 private $localDomain;
92 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
93 private $localDomainIdAlias;
94 /** @var string Current server name */
95 private $host;
96 /** @var bool Whether this PHP instance is for a CLI script */
97 protected $cliMode;
98 /** @var string Agent name for query profiling */
99 protected $agent;
101 /** @var callable Exception logger */
102 private $errorLogger;
104 /** @var boolean */
105 private $disabled = false;
107 /** @var integer Warn when this many connection are held */
108 const CONN_HELD_WARN_THRESHOLD = 10;
110 /** @var integer Default 'max lag' when unspecified */
111 const MAX_LAG_DEFAULT = 10;
112 /** @var integer Seconds to cache master server read-only status */
113 const TTL_CACHE_READONLY = 5;
115 public function __construct( array $params ) {
116 if ( !isset( $params['servers'] ) ) {
117 throw new InvalidArgumentException( __CLASS__ . ': missing servers parameter' );
119 $this->mServers = $params['servers'];
121 $this->localDomain = isset( $params['localDomain'] )
122 ? DatabaseDomain::newFromId( $params['localDomain'] )
123 : DatabaseDomain::newUnspecified();
124 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
125 // always true, gracefully handle the case when they fail to account for escaping.
126 if ( $this->localDomain->getTablePrefix() != '' ) {
127 $this->localDomainIdAlias =
128 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
129 } else {
130 $this->localDomainIdAlias = $this->localDomain->getDatabase();
133 $this->mWaitTimeout = isset( $params['waitTimeout'] ) ? $params['waitTimeout'] : 10;
135 $this->mReadIndex = -1;
136 $this->mConns = [
137 'local' => [],
138 'foreignUsed' => [],
139 'foreignFree' => []
141 $this->mLoads = [];
142 $this->mWaitForPos = false;
143 $this->mErrorConnection = false;
144 $this->mAllowLagged = false;
146 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
147 $this->readOnlyReason = $params['readOnlyReason'];
150 if ( isset( $params['loadMonitor'] ) ) {
151 $this->loadMonitorConfig = $params['loadMonitor'];
152 } else {
153 $this->loadMonitorConfig = [ 'class' => 'LoadMonitorNull' ];
156 foreach ( $params['servers'] as $i => $server ) {
157 $this->mLoads[$i] = $server['load'];
158 if ( isset( $server['groupLoads'] ) ) {
159 foreach ( $server['groupLoads'] as $group => $ratio ) {
160 if ( !isset( $this->mGroupLoads[$group] ) ) {
161 $this->mGroupLoads[$group] = [];
163 $this->mGroupLoads[$group][$i] = $ratio;
168 if ( isset( $params['srvCache'] ) ) {
169 $this->srvCache = $params['srvCache'];
170 } else {
171 $this->srvCache = new EmptyBagOStuff();
173 if ( isset( $params['memCache'] ) ) {
174 $this->memCache = $params['memCache'];
175 } else {
176 $this->memCache = new EmptyBagOStuff();
178 if ( isset( $params['wanCache'] ) ) {
179 $this->wanCache = $params['wanCache'];
180 } else {
181 $this->wanCache = WANObjectCache::newEmpty();
183 $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null;
184 if ( isset( $params['trxProfiler'] ) ) {
185 $this->trxProfiler = $params['trxProfiler'];
186 } else {
187 $this->trxProfiler = new TransactionProfiler();
190 $this->errorLogger = isset( $params['errorLogger'] )
191 ? $params['errorLogger']
192 : function ( Exception $e ) {
193 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
196 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
197 $this->$key = isset( $params[$key] ) ? $params[$key] : new \Psr\Log\NullLogger();
200 $this->host = isset( $params['hostname'] )
201 ? $params['hostname']
202 : ( gethostname() ?: 'unknown' );
203 $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
204 $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
208 * Get a LoadMonitor instance
210 * @return ILoadMonitor
212 private function getLoadMonitor() {
213 if ( !isset( $this->loadMonitor ) ) {
214 $class = $this->loadMonitorConfig['class'];
215 $this->loadMonitor = new $class(
216 $this, $this->srvCache, $this->memCache, $this->loadMonitorConfig );
217 $this->loadMonitor->setLogger( $this->replLogger );
220 return $this->loadMonitor;
224 * @param array $loads
225 * @param bool|string $domain Domain to get non-lagged for
226 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
227 * @return bool|int|string
229 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
230 $lags = $this->getLagTimes( $domain );
232 # Unset excessively lagged servers
233 foreach ( $lags as $i => $lag ) {
234 if ( $i != 0 ) {
235 # How much lag this server nominally is allowed to have
236 $maxServerLag = isset( $this->mServers[$i]['max lag'] )
237 ? $this->mServers[$i]['max lag']
238 : self::MAX_LAG_DEFAULT; // default
239 # Constrain that futher by $maxLag argument
240 $maxServerLag = min( $maxServerLag, $maxLag );
242 $host = $this->getServerName( $i );
243 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
244 $this->replLogger->error(
245 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
246 unset( $loads[$i] );
247 } elseif ( $lag > $maxServerLag ) {
248 $this->replLogger->warning(
249 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
250 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
252 unset( $loads[$i] );
257 # Find out if all the replica DBs with non-zero load are lagged
258 $sum = 0;
259 foreach ( $loads as $load ) {
260 $sum += $load;
262 if ( $sum == 0 ) {
263 # No appropriate DB servers except maybe the master and some replica DBs with zero load
264 # Do NOT use the master
265 # Instead, this function will return false, triggering read-only mode,
266 # and a lagged replica DB will be used instead.
267 return false;
270 if ( count( $loads ) == 0 ) {
271 return false;
274 # Return a random representative of the remainder
275 return ArrayUtils::pickRandom( $loads );
278 public function getReaderIndex( $group = false, $domain = false ) {
279 if ( count( $this->mServers ) == 1 ) {
280 # Skip the load balancing if there's only one server
281 return $this->getWriterIndex();
282 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
283 # Shortcut if generic reader exists already
284 return $this->mReadIndex;
287 # Find the relevant load array
288 if ( $group !== false ) {
289 if ( isset( $this->mGroupLoads[$group] ) ) {
290 $nonErrorLoads = $this->mGroupLoads[$group];
291 } else {
292 # No loads for this group, return false and the caller can use some other group
293 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
295 return false;
297 } else {
298 $nonErrorLoads = $this->mLoads;
301 if ( !count( $nonErrorLoads ) ) {
302 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
305 # Scale the configured load ratios according to the dynamic load if supported
306 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
308 $laggedReplicaMode = false;
310 # No server found yet
311 $i = false;
312 # First try quickly looking through the available servers for a server that
313 # meets our criteria
314 $currentLoads = $nonErrorLoads;
315 while ( count( $currentLoads ) ) {
316 if ( $this->mAllowLagged || $laggedReplicaMode ) {
317 $i = ArrayUtils::pickRandom( $currentLoads );
318 } else {
319 $i = false;
320 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
321 # ChronologyProtecter causes mWaitForPos to be set via sessions.
322 # This triggers doWait() after connect, so it's especially good to
323 # avoid lagged servers so as to avoid just blocking in that method.
324 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
325 # Aim for <= 1 second of waiting (being too picky can backfire)
326 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
328 if ( $i === false ) {
329 # Any server with less lag than it's 'max lag' param is preferable
330 $i = $this->getRandomNonLagged( $currentLoads, $domain );
332 if ( $i === false && count( $currentLoads ) != 0 ) {
333 # All replica DBs lagged. Switch to read-only mode
334 $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
335 $i = ArrayUtils::pickRandom( $currentLoads );
336 $laggedReplicaMode = true;
340 if ( $i === false ) {
341 # pickRandom() returned false
342 # This is permanent and means the configuration or the load monitor
343 # wants us to return false.
344 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
346 return false;
349 $serverName = $this->getServerName( $i );
350 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
352 $conn = $this->openConnection( $i, $domain );
353 if ( !$conn ) {
354 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
355 unset( $nonErrorLoads[$i] );
356 unset( $currentLoads[$i] );
357 $i = false;
358 continue;
361 // Decrement reference counter, we are finished with this connection.
362 // It will be incremented for the caller later.
363 if ( $domain !== false ) {
364 $this->reuseConnection( $conn );
367 # Return this server
368 break;
371 # If all servers were down, quit now
372 if ( !count( $nonErrorLoads ) ) {
373 $this->connLogger->error( "All servers down" );
376 if ( $i !== false ) {
377 # Replica DB connection successful.
378 # Wait for the session master pos for a short time.
379 if ( $this->mWaitForPos && $i > 0 ) {
380 $this->doWait( $i );
382 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
383 $this->mReadIndex = $i;
384 # Record if the generic reader index is in "lagged replica DB" mode
385 if ( $laggedReplicaMode ) {
386 $this->laggedReplicaMode = true;
389 $serverName = $this->getServerName( $i );
390 $this->connLogger->debug(
391 __METHOD__ . ": using server $serverName for group '$group'" );
394 return $i;
398 * @param DBMasterPos|false $pos
400 public function waitFor( $pos ) {
401 $this->mWaitForPos = $pos;
402 $i = $this->mReadIndex;
404 if ( $i > 0 ) {
405 if ( !$this->doWait( $i ) ) {
406 $this->laggedReplicaMode = true;
411 public function waitForOne( $pos, $timeout = null ) {
412 $this->mWaitForPos = $pos;
414 $i = $this->mReadIndex;
415 if ( $i <= 0 ) {
416 // Pick a generic replica DB if there isn't one yet
417 $readLoads = $this->mLoads;
418 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
419 $readLoads = array_filter( $readLoads ); // with non-zero load
420 $i = ArrayUtils::pickRandom( $readLoads );
423 if ( $i > 0 ) {
424 $ok = $this->doWait( $i, true, $timeout );
425 } else {
426 $ok = true; // no applicable loads
429 return $ok;
432 public function waitForAll( $pos, $timeout = null ) {
433 $this->mWaitForPos = $pos;
434 $serverCount = count( $this->mServers );
436 $ok = true;
437 for ( $i = 1; $i < $serverCount; $i++ ) {
438 if ( $this->mLoads[$i] > 0 ) {
439 $ok = $this->doWait( $i, true, $timeout ) && $ok;
443 return $ok;
447 * @param int $i
448 * @return IDatabase|bool
450 public function getAnyOpenConnection( $i ) {
451 foreach ( $this->mConns as $connsByServer ) {
452 if ( !empty( $connsByServer[$i] ) ) {
453 /** @var $serverConns IDatabase[] */
454 $serverConns = $connsByServer[$i];
456 return reset( $serverConns );
460 return false;
464 * Wait for a given replica DB to catch up to the master pos stored in $this
465 * @param int $index Server index
466 * @param bool $open Check the server even if a new connection has to be made
467 * @param int $timeout Max seconds to wait; default is mWaitTimeout
468 * @return bool
470 protected function doWait( $index, $open = false, $timeout = null ) {
471 $close = false; // close the connection afterwards
473 // Check if we already know that the DB has reached this point
474 $server = $this->getServerName( $index );
475 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
476 /** @var DBMasterPos $knownReachedPos */
477 $knownReachedPos = $this->srvCache->get( $key );
478 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
479 $this->replLogger->debug( __METHOD__ .
480 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
481 return true;
484 // Find a connection to wait on, creating one if needed and allowed
485 $conn = $this->getAnyOpenConnection( $index );
486 if ( !$conn ) {
487 if ( !$open ) {
488 $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
490 return false;
491 } else {
492 $conn = $this->openConnection( $index, self::DOMAIN_ANY );
493 if ( !$conn ) {
494 $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
496 return false;
498 // Avoid connection spam in waitForAll() when connections
499 // are made just for the sake of doing this lag check.
500 $close = true;
504 $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
505 $timeout = $timeout ?: $this->mWaitTimeout;
506 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
508 if ( $result == -1 || is_null( $result ) ) {
509 // Timed out waiting for replica DB, use master instead
510 $this->replLogger->warning(
511 __METHOD__ . ": Timed out waiting on {host} pos {$this->mWaitForPos}",
512 [ 'host' => $server ]
514 $ok = false;
515 } else {
516 $this->replLogger->info( __METHOD__ . ": Done" );
517 $ok = true;
518 // Remember that the DB reached this point
519 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
522 if ( $close ) {
523 $this->closeConnection( $conn );
526 return $ok;
530 * @see ILoadBalancer::getConnection()
532 * @param int $i
533 * @param array $groups
534 * @param bool $domain
535 * @return Database
536 * @throws DBConnectionError
538 public function getConnection( $i, $groups = [], $domain = false ) {
539 if ( $i === null || $i === false ) {
540 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
541 ' with invalid server index' );
544 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
545 $domain = false; // local connection requested
548 $groups = ( $groups === false || $groups === [] )
549 ? [ false ] // check one "group": the generic pool
550 : (array)$groups;
552 $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
553 $oldConnsOpened = $this->connsOpened; // connections open now
555 if ( $i == self::DB_MASTER ) {
556 $i = $this->getWriterIndex();
557 } else {
558 # Try to find an available server in any the query groups (in order)
559 foreach ( $groups as $group ) {
560 $groupIndex = $this->getReaderIndex( $group, $domain );
561 if ( $groupIndex !== false ) {
562 $i = $groupIndex;
563 break;
568 # Operation-based index
569 if ( $i == self::DB_REPLICA ) {
570 $this->mLastError = 'Unknown error'; // reset error string
571 # Try the general server pool if $groups are unavailable.
572 $i = ( $groups === [ false ] )
573 ? false // don't bother with this if that is what was tried above
574 : $this->getReaderIndex( false, $domain );
575 # Couldn't find a working server in getReaderIndex()?
576 if ( $i === false ) {
577 $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
578 // Throw an exception
579 $this->reportConnectionError();
580 return null; // not reached
584 # Now we have an explicit index into the servers array
585 $conn = $this->openConnection( $i, $domain );
586 if ( !$conn ) {
587 // Throw an exception
588 $this->reportConnectionError();
589 return null; // not reached
592 # Profile any new connections that happen
593 if ( $this->connsOpened > $oldConnsOpened ) {
594 $host = $conn->getServer();
595 $dbname = $conn->getDBname();
596 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
599 if ( $masterOnly ) {
600 # Make master-requested DB handles inherit any read-only mode setting
601 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
604 return $conn;
607 public function reuseConnection( $conn ) {
608 $serverIndex = $conn->getLBInfo( 'serverIndex' );
609 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
610 if ( $serverIndex === null || $refCount === null ) {
612 * This can happen in code like:
613 * foreach ( $dbs as $db ) {
614 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
615 * ...
616 * $lb->reuseConnection( $conn );
618 * When a connection to the local DB is opened in this way, reuseConnection()
619 * should be ignored
621 return;
622 } elseif ( $conn instanceof DBConnRef ) {
623 // DBConnRef already handles calling reuseConnection() and only passes the live
624 // Database instance to this method. Any caller passing in a DBConnRef is broken.
625 $this->connLogger->error( __METHOD__ . ": got DBConnRef instance.\n" .
626 ( new RuntimeException() )->getTraceAsString() );
628 return;
631 if ( $this->disabled ) {
632 return; // DBConnRef handle probably survived longer than the LoadBalancer
635 $domain = $conn->getDomainID();
636 if ( !isset( $this->mConns['foreignUsed'][$serverIndex][$domain] ) ) {
637 throw new InvalidArgumentException( __METHOD__ .
638 ": connection $serverIndex/$domain not found; it may have already been freed." );
639 } elseif ( $this->mConns['foreignUsed'][$serverIndex][$domain] !== $conn ) {
640 throw new InvalidArgumentException( __METHOD__ .
641 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
643 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
644 if ( $refCount <= 0 ) {
645 $this->mConns['foreignFree'][$serverIndex][$domain] = $conn;
646 unset( $this->mConns['foreignUsed'][$serverIndex][$domain] );
647 if ( !$this->mConns['foreignUsed'][$serverIndex] ) {
648 unset( $this->mConns[ 'foreignUsed' ][$serverIndex] ); // clean up
650 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
651 } else {
652 $this->connLogger->debug( __METHOD__ .
653 ": reference count for $serverIndex/$domain reduced to $refCount" );
657 public function getConnectionRef( $db, $groups = [], $domain = false ) {
658 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
660 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
663 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
664 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
666 return new DBConnRef( $this, [ $db, $groups, $domain ] );
669 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
670 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
672 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
676 * @see ILoadBalancer::openConnection()
678 * @param int $i
679 * @param bool $domain
680 * @return bool|Database
681 * @throws DBAccessError
683 public function openConnection( $i, $domain = false ) {
684 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
685 $domain = false; // local connection requested
688 if ( $domain !== false ) {
689 $conn = $this->openForeignConnection( $i, $domain );
690 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
691 $conn = $this->mConns['local'][$i][0];
692 } else {
693 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
694 throw new InvalidArgumentException( "No server with index '$i'." );
696 // Open a new connection
697 $server = $this->mServers[$i];
698 $server['serverIndex'] = $i;
699 $conn = $this->reallyOpenConnection( $server, false );
700 $serverName = $this->getServerName( $i );
701 if ( $conn->isOpen() ) {
702 $this->connLogger->debug( "Connected to database $i at '$serverName'." );
703 $this->mConns['local'][$i][0] = $conn;
704 } else {
705 $this->connLogger->warning( "Failed to connect to database $i at '$serverName'." );
706 $this->mErrorConnection = $conn;
707 $conn = false;
711 if ( $conn && !$conn->isOpen() ) {
712 // Connection was made but later unrecoverably lost for some reason.
713 // Do not return a handle that will just throw exceptions on use,
714 // but let the calling code (e.g. getReaderIndex) try another server.
715 // See DatabaseMyslBase::ping() for how this can happen.
716 $this->mErrorConnection = $conn;
717 $conn = false;
720 return $conn;
724 * Open a connection to a foreign DB, or return one if it is already open.
726 * Increments a reference count on the returned connection which locks the
727 * connection to the requested domain. This reference count can be
728 * decremented by calling reuseConnection().
730 * If a connection is open to the appropriate server already, but with the wrong
731 * database, it will be switched to the right database and returned, as long as
732 * it has been freed first with reuseConnection().
734 * On error, returns false, and the connection which caused the
735 * error will be available via $this->mErrorConnection.
737 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
739 * @param int $i Server index
740 * @param string $domain Domain ID to open
741 * @return Database
743 private function openForeignConnection( $i, $domain ) {
744 $domainInstance = DatabaseDomain::newFromId( $domain );
745 $dbName = $domainInstance->getDatabase();
746 $prefix = $domainInstance->getTablePrefix();
748 if ( isset( $this->mConns['foreignUsed'][$i][$domain] ) ) {
749 // Reuse an already-used connection
750 $conn = $this->mConns['foreignUsed'][$i][$domain];
751 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
752 } elseif ( isset( $this->mConns['foreignFree'][$i][$domain] ) ) {
753 // Reuse a free connection for the same domain
754 $conn = $this->mConns['foreignFree'][$i][$domain];
755 unset( $this->mConns['foreignFree'][$i][$domain] );
756 $this->mConns['foreignUsed'][$i][$domain] = $conn;
757 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
758 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
759 // Reuse a connection from another domain
760 $conn = reset( $this->mConns['foreignFree'][$i] );
761 $oldDomain = key( $this->mConns['foreignFree'][$i] );
762 // The empty string as a DB name means "don't care".
763 // DatabaseMysqlBase::open() already handle this on connection.
764 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
765 $this->mLastError = "Error selecting database '$dbName' on server " .
766 $conn->getServer() . " from client host {$this->host}";
767 $this->mErrorConnection = $conn;
768 $conn = false;
769 } else {
770 $conn->tablePrefix( $prefix );
771 unset( $this->mConns['foreignFree'][$i][$oldDomain] );
772 $this->mConns['foreignUsed'][$i][$domain] = $conn;
773 $this->connLogger->debug( __METHOD__ .
774 ": reusing free connection from $oldDomain for $domain" );
776 } else {
777 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
778 throw new InvalidArgumentException( "No server with index '$i'." );
780 // Open a new connection
781 $server = $this->mServers[$i];
782 $server['serverIndex'] = $i;
783 $server['foreignPoolRefCount'] = 0;
784 $server['foreign'] = true;
785 $conn = $this->reallyOpenConnection( $server, $dbName );
786 if ( !$conn->isOpen() ) {
787 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
788 $this->mErrorConnection = $conn;
789 $conn = false;
790 } else {
791 $conn->tablePrefix( $prefix );
792 $this->mConns['foreignUsed'][$i][$domain] = $conn;
793 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
797 // Increment reference count
798 if ( $conn ) {
799 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
800 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
803 return $conn;
807 * Test if the specified index represents an open connection
809 * @param int $index Server index
810 * @access private
811 * @return bool
813 private function isOpen( $index ) {
814 if ( !is_integer( $index ) ) {
815 return false;
818 return (bool)$this->getAnyOpenConnection( $index );
822 * Really opens a connection. Uncached.
823 * Returns a Database object whether or not the connection was successful.
824 * @access private
826 * @param array $server
827 * @param string|bool $dbNameOverride Use "" to not select any database
828 * @return Database
829 * @throws DBAccessError
830 * @throws InvalidArgumentException
832 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
833 if ( $this->disabled ) {
834 throw new DBAccessError();
837 if ( $dbNameOverride !== false ) {
838 $server['dbname'] = $dbNameOverride;
841 // Let the handle know what the cluster master is (e.g. "db1052")
842 $masterName = $this->getServerName( $this->getWriterIndex() );
843 $server['clusterMasterHost'] = $masterName;
845 // Log when many connection are made on requests
846 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
847 $this->perfLogger->warning( __METHOD__ . ": " .
848 "{$this->connsOpened}+ connections made (master=$masterName)" );
851 $server['srvCache'] = $this->srvCache;
852 // Set loggers and profilers
853 $server['connLogger'] = $this->connLogger;
854 $server['queryLogger'] = $this->queryLogger;
855 $server['errorLogger'] = $this->errorLogger;
856 $server['profiler'] = $this->profiler;
857 $server['trxProfiler'] = $this->trxProfiler;
858 // Use the same agent and PHP mode for all DB handles
859 $server['cliMode'] = $this->cliMode;
860 $server['agent'] = $this->agent;
861 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
862 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
863 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
865 // Create a live connection object
866 try {
867 $db = Database::factory( $server['type'], $server );
868 } catch ( DBConnectionError $e ) {
869 // FIXME: This is probably the ugliest thing I have ever done to
870 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
871 $db = $e->db;
874 $db->setLBInfo( $server );
875 $db->setLazyMasterHandle(
876 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
878 $db->setTableAliases( $this->tableAliases );
880 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
881 if ( $this->trxRoundId !== false ) {
882 $this->applyTransactionRoundFlags( $db );
884 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
885 $db->setTransactionListener( $name, $callback );
889 return $db;
893 * @throws DBConnectionError
895 private function reportConnectionError() {
896 $conn = $this->mErrorConnection; // the connection which caused the error
897 $context = [
898 'method' => __METHOD__,
899 'last_error' => $this->mLastError,
902 if ( !is_object( $conn ) ) {
903 // No last connection, probably due to all servers being too busy
904 $this->connLogger->error(
905 "LB failure with no last connection. Connection error: {last_error}",
906 $context
909 // If all servers were busy, mLastError will contain something sensible
910 throw new DBConnectionError( null, $this->mLastError );
911 } else {
912 $context['db_server'] = $conn->getServer();
913 $this->connLogger->warning(
914 "Connection error: {last_error} ({db_server})",
915 $context
918 // throws DBConnectionError
919 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
923 public function getWriterIndex() {
924 return 0;
927 public function haveIndex( $i ) {
928 return array_key_exists( $i, $this->mServers );
931 public function isNonZeroLoad( $i ) {
932 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
935 public function getServerCount() {
936 return count( $this->mServers );
939 public function getServerName( $i ) {
940 if ( isset( $this->mServers[$i]['hostName'] ) ) {
941 $name = $this->mServers[$i]['hostName'];
942 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
943 $name = $this->mServers[$i]['host'];
944 } else {
945 $name = '';
948 return ( $name != '' ) ? $name : 'localhost';
951 public function getServerInfo( $i ) {
952 if ( isset( $this->mServers[$i] ) ) {
953 return $this->mServers[$i];
954 } else {
955 return false;
959 public function setServerInfo( $i, array $serverInfo ) {
960 $this->mServers[$i] = $serverInfo;
963 public function getMasterPos() {
964 # If this entire request was served from a replica DB without opening a connection to the
965 # master (however unlikely that may be), then we can fetch the position from the replica DB.
966 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
967 if ( !$masterConn ) {
968 $serverCount = count( $this->mServers );
969 for ( $i = 1; $i < $serverCount; $i++ ) {
970 $conn = $this->getAnyOpenConnection( $i );
971 if ( $conn ) {
972 return $conn->getReplicaPos();
975 } else {
976 return $masterConn->getMasterPos();
979 return false;
982 public function disable() {
983 $this->closeAll();
984 $this->disabled = true;
987 public function closeAll() {
988 $this->forEachOpenConnection( function ( IDatabase $conn ) {
989 $host = $conn->getServer();
990 $this->connLogger->debug( "Closing connection to database '$host'." );
991 $conn->close();
992 } );
994 $this->mConns = [
995 'local' => [],
996 'foreignFree' => [],
997 'foreignUsed' => [],
999 $this->connsOpened = 0;
1002 public function closeConnection( IDatabase $conn ) {
1003 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1004 foreach ( $this->mConns as $type => $connsByServer ) {
1005 if ( !isset( $connsByServer[$serverIndex] ) ) {
1006 continue;
1009 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1010 if ( $conn === $trackedConn ) {
1011 $host = $this->getServerName( $i );
1012 $this->connLogger->debug( "Closing connection to database $i at '$host'." );
1013 unset( $this->mConns[$type][$serverIndex][$i] );
1014 --$this->connsOpened;
1015 break 2;
1020 $conn->close();
1023 public function commitAll( $fname = __METHOD__ ) {
1024 $failures = [];
1026 $restore = ( $this->trxRoundId !== false );
1027 $this->trxRoundId = false;
1028 $this->forEachOpenConnection(
1029 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1030 try {
1031 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1032 } catch ( DBError $e ) {
1033 call_user_func( $this->errorLogger, $e );
1034 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1036 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1037 $this->undoTransactionRoundFlags( $conn );
1042 if ( $failures ) {
1043 throw new DBExpectedError(
1044 null,
1045 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1050 public function finalizeMasterChanges() {
1051 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1052 // Any error should cause all DB transactions to be rolled back together
1053 $conn->setTrxEndCallbackSuppression( false );
1054 $conn->runOnTransactionPreCommitCallbacks();
1055 // Defer post-commit callbacks until COMMIT finishes for all DBs
1056 $conn->setTrxEndCallbackSuppression( true );
1057 } );
1060 public function approveMasterChanges( array $options ) {
1061 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1062 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1063 // If atomic sections or explicit transactions are still open, some caller must have
1064 // caught an exception but failed to properly rollback any changes. Detect that and
1065 // throw and error (causing rollback).
1066 if ( $conn->explicitTrxActive() ) {
1067 throw new DBTransactionError(
1068 $conn,
1069 "Explicit transaction still active. A caller may have caught an error."
1072 // Assert that the time to replicate the transaction will be sane.
1073 // If this fails, then all DB transactions will be rollback back together.
1074 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1075 if ( $limit > 0 && $time > $limit ) {
1076 throw new DBTransactionSizeError(
1077 $conn,
1078 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1079 [ $time, $limit ]
1082 // If a connection sits idle while slow queries execute on another, that connection
1083 // may end up dropped before the commit round is reached. Ping servers to detect this.
1084 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1085 throw new DBTransactionError(
1086 $conn,
1087 "A connection to the {$conn->getDBname()} database was lost before commit."
1090 } );
1093 public function beginMasterChanges( $fname = __METHOD__ ) {
1094 if ( $this->trxRoundId !== false ) {
1095 throw new DBTransactionError(
1096 null,
1097 "$fname: Transaction round '{$this->trxRoundId}' already started."
1100 $this->trxRoundId = $fname;
1102 $failures = [];
1103 $this->forEachOpenMasterConnection(
1104 function ( Database $conn ) use ( $fname, &$failures ) {
1105 $conn->setTrxEndCallbackSuppression( true );
1106 try {
1107 $conn->flushSnapshot( $fname );
1108 } catch ( DBError $e ) {
1109 call_user_func( $this->errorLogger, $e );
1110 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1112 $conn->setTrxEndCallbackSuppression( false );
1113 $this->applyTransactionRoundFlags( $conn );
1117 if ( $failures ) {
1118 throw new DBExpectedError(
1119 null,
1120 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1125 public function commitMasterChanges( $fname = __METHOD__ ) {
1126 $failures = [];
1128 /** @noinspection PhpUnusedLocalVariableInspection */
1129 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1131 $restore = ( $this->trxRoundId !== false );
1132 $this->trxRoundId = false;
1133 $this->forEachOpenMasterConnection(
1134 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1135 try {
1136 if ( $conn->writesOrCallbacksPending() ) {
1137 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1138 } elseif ( $restore ) {
1139 $conn->flushSnapshot( $fname );
1141 } catch ( DBError $e ) {
1142 call_user_func( $this->errorLogger, $e );
1143 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1145 if ( $restore ) {
1146 $this->undoTransactionRoundFlags( $conn );
1151 if ( $failures ) {
1152 throw new DBExpectedError(
1153 null,
1154 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1159 public function runMasterPostTrxCallbacks( $type ) {
1160 $e = null; // first exception
1161 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1162 $conn->setTrxEndCallbackSuppression( false );
1163 if ( $conn->writesOrCallbacksPending() ) {
1164 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1165 // (which finished its callbacks already). Warn and recover in this case. Let the
1166 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1167 $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
1168 return;
1169 } elseif ( $conn->trxLevel() ) {
1170 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1171 // thus leaving an implicit read-only transaction open at this point. It
1172 // also happens if onTransactionIdle() callbacks leave implicit transactions
1173 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1174 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1175 return;
1177 try {
1178 $conn->runOnTransactionIdleCallbacks( $type );
1179 } catch ( Exception $ex ) {
1180 $e = $e ?: $ex;
1182 try {
1183 $conn->runTransactionListenerCallbacks( $type );
1184 } catch ( Exception $ex ) {
1185 $e = $e ?: $ex;
1187 } );
1189 return $e;
1192 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1193 $restore = ( $this->trxRoundId !== false );
1194 $this->trxRoundId = false;
1195 $this->forEachOpenMasterConnection(
1196 function ( IDatabase $conn ) use ( $fname, $restore ) {
1197 if ( $conn->writesOrCallbacksPending() ) {
1198 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1200 if ( $restore ) {
1201 $this->undoTransactionRoundFlags( $conn );
1207 public function suppressTransactionEndCallbacks() {
1208 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1209 $conn->setTrxEndCallbackSuppression( true );
1210 } );
1214 * @param IDatabase $conn
1216 private function applyTransactionRoundFlags( IDatabase $conn ) {
1217 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1218 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1219 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1220 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1221 // If config has explicitly requested DBO_TRX be either on or off by not
1222 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1223 // for things like blob stores (ExternalStore) which want auto-commit mode.
1228 * @param IDatabase $conn
1230 private function undoTransactionRoundFlags( IDatabase $conn ) {
1231 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1232 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1236 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1237 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1238 $conn->flushSnapshot( __METHOD__ );
1239 } );
1242 public function hasMasterConnection() {
1243 return $this->isOpen( $this->getWriterIndex() );
1246 public function hasMasterChanges() {
1247 $pending = 0;
1248 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1249 $pending |= $conn->writesOrCallbacksPending();
1250 } );
1252 return (bool)$pending;
1255 public function lastMasterChangeTimestamp() {
1256 $lastTime = false;
1257 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1258 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1259 } );
1261 return $lastTime;
1264 public function hasOrMadeRecentMasterChanges( $age = null ) {
1265 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1267 return ( $this->hasMasterChanges()
1268 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1271 public function pendingMasterChangeCallers() {
1272 $fnames = [];
1273 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1274 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1275 } );
1277 return $fnames;
1280 public function getLaggedReplicaMode( $domain = false ) {
1281 // No-op if there is only one DB (also avoids recursion)
1282 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1283 try {
1284 // See if laggedReplicaMode gets set
1285 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1286 $this->reuseConnection( $conn );
1287 } catch ( DBConnectionError $e ) {
1288 // Avoid expensive re-connect attempts and failures
1289 $this->allReplicasDownMode = true;
1290 $this->laggedReplicaMode = true;
1294 return $this->laggedReplicaMode;
1298 * @param bool $domain
1299 * @return bool
1300 * @deprecated 1.28; use getLaggedReplicaMode()
1302 public function getLaggedSlaveMode( $domain = false ) {
1303 return $this->getLaggedReplicaMode( $domain );
1306 public function laggedReplicaUsed() {
1307 return $this->laggedReplicaMode;
1311 * @return bool
1312 * @since 1.27
1313 * @deprecated Since 1.28; use laggedReplicaUsed()
1315 public function laggedSlaveUsed() {
1316 return $this->laggedReplicaUsed();
1319 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1320 if ( $this->readOnlyReason !== false ) {
1321 return $this->readOnlyReason;
1322 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1323 if ( $this->allReplicasDownMode ) {
1324 return 'The database has been automatically locked ' .
1325 'until the replica database servers become available';
1326 } else {
1327 return 'The database has been automatically locked ' .
1328 'while the replica database servers catch up to the master.';
1330 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1331 return 'The database master is running in read-only mode.';
1334 return false;
1338 * @param string $domain Domain ID, or false for the current domain
1339 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1340 * @return bool
1342 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1343 $cache = $this->wanCache;
1344 $masterServer = $this->getServerName( $this->getWriterIndex() );
1346 return (bool)$cache->getWithSetCallback(
1347 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1348 self::TTL_CACHE_READONLY,
1349 function () use ( $domain, $conn ) {
1350 $old = $this->trxProfiler->setSilenced( true );
1351 try {
1352 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1353 $readOnly = (int)$dbw->serverIsReadOnly();
1354 if ( !$conn ) {
1355 $this->reuseConnection( $dbw );
1357 } catch ( DBError $e ) {
1358 $readOnly = 0;
1360 $this->trxProfiler->setSilenced( $old );
1361 return $readOnly;
1363 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1367 public function allowLagged( $mode = null ) {
1368 if ( $mode === null ) {
1369 return $this->mAllowLagged;
1371 $this->mAllowLagged = $mode;
1373 return $this->mAllowLagged;
1376 public function pingAll() {
1377 $success = true;
1378 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1379 if ( !$conn->ping() ) {
1380 $success = false;
1382 } );
1384 return $success;
1387 public function forEachOpenConnection( $callback, array $params = [] ) {
1388 foreach ( $this->mConns as $connsByServer ) {
1389 foreach ( $connsByServer as $serverConns ) {
1390 foreach ( $serverConns as $conn ) {
1391 $mergedParams = array_merge( [ $conn ], $params );
1392 call_user_func_array( $callback, $mergedParams );
1398 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1399 $masterIndex = $this->getWriterIndex();
1400 foreach ( $this->mConns as $connsByServer ) {
1401 if ( isset( $connsByServer[$masterIndex] ) ) {
1402 /** @var IDatabase $conn */
1403 foreach ( $connsByServer[$masterIndex] as $conn ) {
1404 $mergedParams = array_merge( [ $conn ], $params );
1405 call_user_func_array( $callback, $mergedParams );
1411 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1412 foreach ( $this->mConns as $connsByServer ) {
1413 foreach ( $connsByServer as $i => $serverConns ) {
1414 if ( $i === $this->getWriterIndex() ) {
1415 continue; // skip master
1417 foreach ( $serverConns as $conn ) {
1418 $mergedParams = array_merge( [ $conn ], $params );
1419 call_user_func_array( $callback, $mergedParams );
1425 public function getMaxLag( $domain = false ) {
1426 $maxLag = -1;
1427 $host = '';
1428 $maxIndex = 0;
1430 if ( $this->getServerCount() <= 1 ) {
1431 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1434 $lagTimes = $this->getLagTimes( $domain );
1435 foreach ( $lagTimes as $i => $lag ) {
1436 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1437 $maxLag = $lag;
1438 $host = $this->mServers[$i]['host'];
1439 $maxIndex = $i;
1443 return [ $host, $maxLag, $maxIndex ];
1446 public function getLagTimes( $domain = false ) {
1447 if ( $this->getServerCount() <= 1 ) {
1448 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1451 $knownLagTimes = []; // map of (server index => 0 seconds)
1452 $indexesWithLag = [];
1453 foreach ( $this->mServers as $i => $server ) {
1454 if ( empty( $server['is static'] ) ) {
1455 $indexesWithLag[] = $i; // DB server might have replication lag
1456 } else {
1457 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1461 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1464 public function safeGetLag( IDatabase $conn ) {
1465 if ( $this->getServerCount() <= 1 ) {
1466 return 0;
1467 } else {
1468 return $conn->getLag();
1473 * @param IDatabase $conn
1474 * @param DBMasterPos|false $pos
1475 * @param int $timeout
1477 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1478 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1479 return true; // server is not a replica DB
1482 if ( !$pos ) {
1483 // Get the current master position, opening a connection if needed
1484 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1485 if ( $masterConn ) {
1486 $pos = $masterConn->getMasterPos();
1487 } else {
1488 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1489 $pos = $masterConn->getMasterPos();
1490 $this->closeConnection( $masterConn );
1494 if ( $pos instanceof DBMasterPos ) {
1495 $result = $conn->masterPosWait( $pos, $timeout );
1496 if ( $result == -1 || is_null( $result ) ) {
1497 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1498 $this->replLogger->warning( "$msg" );
1499 $ok = false;
1500 } else {
1501 $this->replLogger->info( __METHOD__ . ": Done" );
1502 $ok = true;
1504 } else {
1505 $ok = false; // something is misconfigured
1506 $this->replLogger->error( "Could not get master pos for {$conn->getServer()}." );
1509 return $ok;
1512 public function setTransactionListener( $name, callable $callback = null ) {
1513 if ( $callback ) {
1514 $this->trxRecurringCallbacks[$name] = $callback;
1515 } else {
1516 unset( $this->trxRecurringCallbacks[$name] );
1518 $this->forEachOpenMasterConnection(
1519 function ( IDatabase $conn ) use ( $name, $callback ) {
1520 $conn->setTransactionListener( $name, $callback );
1525 public function setTableAliases( array $aliases ) {
1526 $this->tableAliases = $aliases;
1529 public function setDomainPrefix( $prefix ) {
1530 if ( $this->mConns['foreignUsed'] ) {
1531 // Do not switch connections to explicit foreign domains unless marked as free
1532 $domains = [];
1533 foreach ( $this->mConns['foreignUsed'] as $i => $connsByDomain ) {
1534 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1536 $domains = implode( ', ', $domains );
1537 throw new DBUnexpectedError( null,
1538 "Foreign domain connections are still in use ($domains)." );
1541 $this->localDomain = new DatabaseDomain(
1542 $this->localDomain->getDatabase(),
1543 null,
1544 $prefix
1547 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1548 $db->tablePrefix( $prefix );
1549 } );
1553 * Make PHP ignore user aborts/disconnects until the returned
1554 * value leaves scope. This returns null and does nothing in CLI mode.
1556 * @return ScopedCallback|null
1558 final protected function getScopedPHPBehaviorForCommit() {
1559 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1560 $old = ignore_user_abort( true ); // avoid half-finished operations
1561 return new ScopedCallback( function () use ( $old ) {
1562 ignore_user_abort( $old );
1563 } );
1566 return null;
1569 function __destruct() {
1570 // Avoid connection leaks for sanity
1571 $this->disable();