3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 namespace Wikimedia\Rdbms
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use Wikimedia\ScopedCallback
;
31 use InvalidArgumentException
;
36 * Database connection, tracking, load balancing, and transaction manager for a cluster
40 class LoadBalancer
implements ILoadBalancer
{
41 /** @var array[] Map of (server index => server config array) */
43 /** @var Database[][][] Map of (connection category => server index => IDatabase[]) */
45 /** @var float[] Map of (server index => weight) */
47 /** @var array[] Map of (group => server index => weight) */
49 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
51 /** @var int Seconds to spend waiting on replica DB lag to resolve */
53 /** @var array The LoadMonitor configuration */
54 private $loadMonitorConfig;
55 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
56 private $tableAliases = [];
57 /** @var string[] Map of (index alias => index) */
58 private $indexAliases = [];
60 /** @var ILoadMonitor */
62 /** @var callable|null Callback to run before the first connection attempt */
63 private $chronologyCallback;
66 /** @var WANObjectCache */
68 /** @var object|string Class name or object With profileIn/profileOut methods */
70 /** @var TransactionProfiler */
71 protected $trxProfiler;
72 /** @var LoggerInterface */
73 protected $replLogger;
74 /** @var LoggerInterface */
75 protected $connLogger;
76 /** @var LoggerInterface */
77 protected $queryLogger;
78 /** @var LoggerInterface */
79 protected $perfLogger;
81 /** @var Database DB connection object that caused a problem */
82 private $errorConnection;
83 /** @var int The generic (not query grouped) replica DB index (of $mServers) */
85 /** @var bool|DBMasterPos False if not set */
87 /** @var bool Whether the generic reader fell back to a lagged replica DB */
88 private $laggedReplicaMode = false;
89 /** @var bool Whether the generic reader fell back to a lagged replica DB */
90 private $allReplicasDownMode = false;
91 /** @var string The last DB selection or connection error */
92 private $lastError = 'Unknown error';
93 /** @var string|bool Reason the LB is read-only or false if not */
94 private $readOnlyReason = false;
95 /** @var int Total connections opened */
96 private $connsOpened = 0;
97 /** @var string|bool String if a requested DBO_TRX transaction round is active */
98 private $trxRoundId = false;
99 /** @var array[] Map of (name => callable) */
100 private $trxRecurringCallbacks = [];
101 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
102 private $localDomain;
103 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
104 private $localDomainIdAlias;
105 /** @var string Current server name */
107 /** @var bool Whether this PHP instance is for a CLI script */
109 /** @var string Agent name for query profiling */
112 /** @var callable Exception logger */
113 private $errorLogger;
114 /** @var callable Deprecation logger */
115 private $deprecationLogger;
118 private $disabled = false;
119 /** @var bool Whether any connection has been attempted yet */
120 private $connectionAttempted = false;
122 private $maxLag = self
::MAX_LAG_DEFAULT
;
123 /** @var string Stage of the current transaction round in the transaction round life-cycle */
124 private $trxRoundStage = self
::ROUND_CURSORY
;
126 /** @var int Warn when this many connection are held */
127 const CONN_HELD_WARN_THRESHOLD
= 10;
129 /** @var int Default 'maxLag' when unspecified */
130 const MAX_LAG_DEFAULT
= 10;
131 /** @var int Default 'waitTimeout' when unspecified */
132 const MAX_WAIT_DEFAULT
= 10;
133 /** @var int Seconds to cache master server read-only status */
134 const TTL_CACHE_READONLY
= 5;
136 const KEY_LOCAL
= 'local';
137 const KEY_FOREIGN_FREE
= 'foreignFree';
138 const KEY_FOREIGN_INUSE
= 'foreignInUse';
140 const KEY_LOCAL_NOROUND
= 'localAutoCommit';
141 const KEY_FOREIGN_FREE_NOROUND
= 'foreignFreeAutoCommit';
142 const KEY_FOREIGN_INUSE_NOROUND
= 'foreignInUseAutoCommit';
144 /** @var string Transaction round, explicit or implicit, has not finished writing */
145 const ROUND_CURSORY
= 'cursory';
146 /** @var string Transaction round writes are complete and ready for pre-commit checks */
147 const ROUND_FINALIZED
= 'finalized';
148 /** @var string Transaction round passed final pre-commit checks */
149 const ROUND_APPROVED
= 'approved';
150 /** @var string Transaction round was committed and post-commit callbacks must be run */
151 const ROUND_COMMIT_CALLBACKS
= 'commit-callbacks';
152 /** @var string Transaction round was rolled back and post-rollback callbacks must be run */
153 const ROUND_ROLLBACK_CALLBACKS
= 'rollback-callbacks';
154 /** @var string Transaction round encountered an error */
155 const ROUND_ERROR
= 'error';
157 public function __construct( array $params ) {
158 if ( !isset( $params['servers'] ) ) {
159 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
161 $this->servers
= $params['servers'];
162 foreach ( $this->servers
as $i => $server ) {
164 $this->servers
[$i]['master'] = true;
166 $this->servers
[$i]['replica'] = true;
170 $localDomain = isset( $params['localDomain'] )
171 ? DatabaseDomain
::newFromId( $params['localDomain'] )
172 : DatabaseDomain
::newUnspecified();
173 $this->setLocalDomain( $localDomain );
175 $this->waitTimeout
= isset( $params['waitTimeout'] )
176 ?
$params['waitTimeout']
177 : self
::MAX_WAIT_DEFAULT
;
179 $this->readIndex
= -1;
181 // Connection were transaction rounds may be applied
182 self
::KEY_LOCAL
=> [],
183 self
::KEY_FOREIGN_INUSE
=> [],
184 self
::KEY_FOREIGN_FREE
=> [],
185 // Auto-committing counterpart connections that ignore transaction rounds
186 self
::KEY_LOCAL_NOROUND
=> [],
187 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
188 self
::KEY_FOREIGN_FREE_NOROUND
=> []
191 $this->waitForPos
= false;
192 $this->allowLagged
= false;
194 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
195 $this->readOnlyReason
= $params['readOnlyReason'];
198 if ( isset( $params['maxLag'] ) ) {
199 $this->maxLag
= $params['maxLag'];
202 if ( isset( $params['loadMonitor'] ) ) {
203 $this->loadMonitorConfig
= $params['loadMonitor'];
205 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
207 $this->loadMonitorConfig +
= [ 'lagWarnThreshold' => $this->maxLag
];
209 foreach ( $params['servers'] as $i => $server ) {
210 $this->loads
[$i] = $server['load'];
211 if ( isset( $server['groupLoads'] ) ) {
212 foreach ( $server['groupLoads'] as $group => $ratio ) {
213 if ( !isset( $this->groupLoads
[$group] ) ) {
214 $this->groupLoads
[$group] = [];
216 $this->groupLoads
[$group][$i] = $ratio;
221 if ( isset( $params['srvCache'] ) ) {
222 $this->srvCache
= $params['srvCache'];
224 $this->srvCache
= new EmptyBagOStuff();
226 if ( isset( $params['wanCache'] ) ) {
227 $this->wanCache
= $params['wanCache'];
229 $this->wanCache
= WANObjectCache
::newEmpty();
231 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
232 if ( isset( $params['trxProfiler'] ) ) {
233 $this->trxProfiler
= $params['trxProfiler'];
235 $this->trxProfiler
= new TransactionProfiler();
238 $this->errorLogger
= isset( $params['errorLogger'] )
239 ?
$params['errorLogger']
240 : function ( Exception
$e ) {
241 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
243 $this->deprecationLogger
= isset( $params['deprecationLogger'] )
244 ?
$params['deprecationLogger']
245 : function ( $msg ) {
246 trigger_error( $msg, E_USER_DEPRECATED
);
249 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
250 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
253 $this->host
= isset( $params['hostname'] )
254 ?
$params['hostname']
255 : ( gethostname() ?
: 'unknown' );
256 $this->cliMode
= isset( $params['cliMode'] )
258 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
259 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
261 if ( isset( $params['chronologyCallback'] ) ) {
262 $this->chronologyCallback
= $params['chronologyCallback'];
265 if ( isset( $params['roundStage'] ) ) {
266 if ( $params['roundStage'] === self
::STAGE_POSTCOMMIT_CALLBACKS
) {
267 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
268 } elseif ( $params['roundStage'] === self
::STAGE_POSTROLLBACK_CALLBACKS
) {
269 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
275 * Get the local (and default) database domain ID of connection handles
277 * @see DatabaseDomain
278 * @return string Database domain ID; this specifies DB name, schema, and table prefix
281 public function getLocalDomainID() {
282 return $this->localDomain
->getId();
286 * Get a LoadMonitor instance
288 * @return ILoadMonitor
290 private function getLoadMonitor() {
291 if ( !isset( $this->loadMonitor
) ) {
293 'LoadMonitor' => LoadMonitor
::class,
294 'LoadMonitorNull' => LoadMonitorNull
::class,
295 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
298 $class = $this->loadMonitorConfig
['class'];
299 if ( isset( $compat[$class] ) ) {
300 $class = $compat[$class];
303 $this->loadMonitor
= new $class(
304 $this, $this->srvCache
, $this->wanCache
, $this->loadMonitorConfig
);
305 $this->loadMonitor
->setLogger( $this->replLogger
);
308 return $this->loadMonitor
;
312 * @param array $loads
313 * @param bool|string $domain Domain to get non-lagged for
314 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
315 * @return bool|int|string
317 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
318 $lags = $this->getLagTimes( $domain );
320 # Unset excessively lagged servers
321 foreach ( $lags as $i => $lag ) {
323 # How much lag this server nominally is allowed to have
324 $maxServerLag = isset( $this->servers
[$i]['max lag'] )
325 ?
$this->servers
[$i]['max lag']
326 : $this->maxLag
; // default
327 # Constrain that futher by $maxLag argument
328 $maxServerLag = min( $maxServerLag, $maxLag );
330 $host = $this->getServerName( $i );
331 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
332 $this->replLogger
->error(
334 ": server {host} is not replicating?", [ 'host' => $host ] );
336 } elseif ( $lag > $maxServerLag ) {
337 $this->replLogger
->info(
339 ": server {host} has {lag} seconds of lag (>= {maxlag})",
340 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
347 # Find out if all the replica DBs with non-zero load are lagged
349 foreach ( $loads as $load ) {
353 # No appropriate DB servers except maybe the master and some replica DBs with zero load
354 # Do NOT use the master
355 # Instead, this function will return false, triggering read-only mode,
356 # and a lagged replica DB will be used instead.
360 if ( count( $loads ) == 0 ) {
364 # Return a random representative of the remainder
365 return ArrayUtils
::pickRandom( $loads );
368 public function getReaderIndex( $group = false, $domain = false ) {
369 if ( count( $this->servers
) == 1 ) {
370 // Skip the load balancing if there's only one server
371 return $this->getWriterIndex();
372 } elseif ( $group === false && $this->readIndex
>= 0 ) {
373 // Shortcut if the generic reader index was already cached
374 return $this->readIndex
;
377 if ( $group !== false ) {
378 // Use the server weight array for this load group
379 if ( isset( $this->groupLoads
[$group] ) ) {
380 $loads = $this->groupLoads
[$group];
382 // No loads for this group, return false and the caller can use some other group
383 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
388 // Use the generic load group
389 $loads = $this->loads
;
392 // Scale the configured load ratios according to each server's load and state
393 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
395 // Pick a server to use, accounting for weights, load, lag, and "waitForPos"
396 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
397 if ( $i === false ) {
398 // Replica DB connection unsuccessful
402 if ( $this->waitForPos
&& $i != $this->getWriterIndex() ) {
403 // Before any data queries are run, wait for the server to catch up to the
404 // specified position. This is used to improve session consistency. Note that
405 // when LoadBalancer::waitFor() sets "waitForPos", the waiting triggers here,
406 // so update laggedReplicaMode as needed for consistency.
407 if ( !$this->doWait( $i ) ) {
408 $laggedReplicaMode = true;
412 if ( $this->readIndex
<= 0 && $this->loads
[$i] > 0 && $group === false ) {
413 // Cache the generic reader index for future ungrouped DB_REPLICA handles
414 $this->readIndex
= $i;
415 // Record if the generic reader index is in "lagged replica DB" mode
416 if ( $laggedReplicaMode ) {
417 $this->laggedReplicaMode
= true;
421 $serverName = $this->getServerName( $i );
422 $this->connLogger
->debug( __METHOD__
. ": using server $serverName for group '$group'" );
428 * @param array $loads List of server weights
429 * @param string|bool $domain
430 * @return array (reader index, lagged replica mode) or false on failure
432 private function pickReaderIndex( array $loads, $domain = false ) {
433 if ( !count( $loads ) ) {
434 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
437 /** @var int|bool $i Index of selected server */
439 /** @var bool $laggedReplicaMode Whether server is considered lagged */
440 $laggedReplicaMode = false;
442 // Quickly look through the available servers for a server that meets criteria...
443 $currentLoads = $loads;
444 while ( count( $currentLoads ) ) {
445 if ( $this->allowLagged ||
$laggedReplicaMode ) {
446 $i = ArrayUtils
::pickRandom( $currentLoads );
449 if ( $this->waitForPos
&& $this->waitForPos
->asOfTime() ) {
450 // "chronologyCallback" sets "waitForPos" for session consistency.
451 // This triggers doWait() after connect, so it's especially good to
452 // avoid lagged servers so as to avoid excessive delay in that method.
453 $ago = microtime( true ) - $this->waitForPos
->asOfTime();
454 // Aim for <= 1 second of waiting (being too picky can backfire)
455 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
457 if ( $i === false ) {
458 // Any server with less lag than it's 'max lag' param is preferable
459 $i = $this->getRandomNonLagged( $currentLoads, $domain );
461 if ( $i === false && count( $currentLoads ) != 0 ) {
462 // All replica DBs lagged. Switch to read-only mode
463 $this->replLogger
->error(
464 __METHOD__
. ": all replica DBs lagged. Switch to read-only mode" );
465 $i = ArrayUtils
::pickRandom( $currentLoads );
466 $laggedReplicaMode = true;
470 if ( $i === false ) {
471 // pickRandom() returned false.
472 // This is permanent and means the configuration or the load monitor
473 // wants us to return false.
474 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
476 return [ false, false ];
479 $serverName = $this->getServerName( $i );
480 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
482 $conn = $this->openConnection( $i, $domain );
484 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
485 unset( $currentLoads[$i] ); // avoid this server next iteration
490 // Decrement reference counter, we are finished with this connection.
491 // It will be incremented for the caller later.
492 if ( $domain !== false ) {
493 $this->reuseConnection( $conn );
496 // Return this server
500 // If all servers were down, quit now
501 if ( !count( $currentLoads ) ) {
502 $this->connLogger
->error( __METHOD__
. ": all servers down" );
505 return [ $i, $laggedReplicaMode ];
508 public function waitFor( $pos ) {
509 $oldPos = $this->waitForPos
;
511 $this->waitForPos
= $pos;
512 // If a generic reader connection was already established, then wait now
513 $i = $this->readIndex
;
515 if ( !$this->doWait( $i ) ) {
516 $this->laggedReplicaMode
= true;
520 // Restore the older position if it was higher since this is used for lag-protection
521 $this->setWaitForPositionIfHigher( $oldPos );
525 public function waitForOne( $pos, $timeout = null ) {
526 $oldPos = $this->waitForPos
;
528 $this->waitForPos
= $pos;
530 $i = $this->readIndex
;
532 // Pick a generic replica DB if there isn't one yet
533 $readLoads = $this->loads
;
534 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
535 $readLoads = array_filter( $readLoads ); // with non-zero load
536 $i = ArrayUtils
::pickRandom( $readLoads );
540 $ok = $this->doWait( $i, true, $timeout );
542 $ok = true; // no applicable loads
545 # Restore the old position, as this is not used for lag-protection but for throttling
546 $this->waitForPos
= $oldPos;
552 public function waitForAll( $pos, $timeout = null ) {
553 $timeout = $timeout ?
: $this->waitTimeout
;
555 $oldPos = $this->waitForPos
;
557 $this->waitForPos
= $pos;
558 $serverCount = count( $this->servers
);
561 for ( $i = 1; $i < $serverCount; $i++
) {
562 if ( $this->loads
[$i] > 0 ) {
563 $start = microtime( true );
564 $ok = $this->doWait( $i, true, $timeout ) && $ok;
565 $timeout -= intval( microtime( true ) - $start );
566 if ( $timeout <= 0 ) {
567 break; // timeout reached
572 # Restore the old position, as this is not used for lag-protection but for throttling
573 $this->waitForPos
= $oldPos;
580 * @param DBMasterPos|bool $pos
582 private function setWaitForPositionIfHigher( $pos ) {
587 if ( !$this->waitForPos ||
$pos->hasReached( $this->waitForPos
) ) {
588 $this->waitForPos
= $pos;
592 public function getAnyOpenConnection( $i, $flags = 0 ) {
593 $autocommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
594 foreach ( $this->conns
as $connsByServer ) {
595 if ( !isset( $connsByServer[$i] ) ) {
599 foreach ( $connsByServer[$i] as $conn ) {
600 if ( !$autocommit ||
$conn->getLBInfo( 'autoCommitOnly' ) ) {
610 * Wait for a given replica DB to catch up to the master pos stored in $this
611 * @param int $index Server index
612 * @param bool $open Check the server even if a new connection has to be made
613 * @param int $timeout Max seconds to wait; default is "waitTimeout" given to __construct()
616 protected function doWait( $index, $open = false, $timeout = null ) {
617 $timeout = max( 1, intval( $timeout ?
: $this->waitTimeout
) );
619 // Check if we already know that the DB has reached this point
620 $server = $this->getServerName( $index );
621 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
622 /** @var DBMasterPos $knownReachedPos */
623 $knownReachedPos = $this->srvCache
->get( $key );
625 $knownReachedPos instanceof DBMasterPos
&&
626 $knownReachedPos->hasReached( $this->waitForPos
)
628 $this->replLogger
->debug(
630 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
631 [ 'dbserver' => $server ]
636 // Find a connection to wait on, creating one if needed and allowed
637 $close = false; // close the connection afterwards
638 $conn = $this->getAnyOpenConnection( $index );
641 $this->replLogger
->debug(
642 __METHOD__
. ': no connection open for {dbserver}',
643 [ 'dbserver' => $server ]
648 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
650 $this->replLogger
->warning(
651 __METHOD__
. ': failed to connect to {dbserver}',
652 [ 'dbserver' => $server ]
657 // Avoid connection spam in waitForAll() when connections
658 // are made just for the sake of doing this lag check.
663 $this->replLogger
->info(
665 ': waiting for replica DB {dbserver} to catch up...',
666 [ 'dbserver' => $server ]
669 $result = $conn->masterPosWait( $this->waitForPos
, $timeout );
671 if ( $result === null ) {
672 $this->replLogger
->warning(
673 __METHOD__
. ': Errored out waiting on {host} pos {pos}',
676 'pos' => $this->waitForPos
,
677 'trace' => ( new RuntimeException() )->getTraceAsString()
681 } elseif ( $result == -1 ) {
682 $this->replLogger
->warning(
683 __METHOD__
. ': Timed out waiting on {host} pos {pos}',
686 'pos' => $this->waitForPos
,
687 'trace' => ( new RuntimeException() )->getTraceAsString()
692 $this->replLogger
->debug( __METHOD__
. ": done waiting" );
694 // Remember that the DB reached this point
695 $this->srvCache
->set( $key, $this->waitForPos
, BagOStuff
::TTL_DAY
);
699 $this->closeConnection( $conn );
705 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
706 if ( $i === null ||
$i === false ) {
707 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
708 ' with invalid server index' );
711 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
712 $domain = false; // local connection requested
715 if ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) === self
::CONN_TRX_AUTOCOMMIT
) {
716 // Assuming all servers are of the same type (or similar), which is overwhelmingly
717 // the case, use the master server information to get the attributes. The information
718 // for $i cannot be used since it might be DB_REPLICA, which might require connection
719 // attempts in order to be resolved into a real server index.
720 $attributes = $this->getServerAttributes( $this->getWriterIndex() );
721 if ( $attributes[Database
::ATTR_DB_LEVEL_LOCKING
] ) {
722 // Callers sometimes want to (a) escape REPEATABLE-READ stateness without locking
723 // rows (e.g. FOR UPDATE) or (b) make small commits during a larger transactions
724 // to reduce lock contention. None of these apply for sqlite and using separate
725 // connections just causes self-deadlocks.
726 $flags &= ~self
::CONN_TRX_AUTOCOMMIT
;
727 $this->connLogger
->info( __METHOD__
.
728 ': ignoring CONN_TRX_AUTOCOMMIT to avoid deadlocks.' );
732 $groups = ( $groups === false ||
$groups === [] )
733 ?
[ false ] // check one "group": the generic pool
736 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
737 $oldConnsOpened = $this->connsOpened
; // connections open now
739 if ( $i == self
::DB_MASTER
) {
740 $i = $this->getWriterIndex();
741 } elseif ( $i == self
::DB_REPLICA
) {
742 # Try to find an available server in any the query groups (in order)
743 foreach ( $groups as $group ) {
744 $groupIndex = $this->getReaderIndex( $group, $domain );
745 if ( $groupIndex !== false ) {
752 # Operation-based index
753 if ( $i == self
::DB_REPLICA
) {
754 $this->lastError
= 'Unknown error'; // reset error string
755 # Try the general server pool if $groups are unavailable.
756 $i = ( $groups === [ false ] )
757 ?
false // don't bother with this if that is what was tried above
758 : $this->getReaderIndex( false, $domain );
759 # Couldn't find a working server in getReaderIndex()?
760 if ( $i === false ) {
761 $this->lastError
= 'No working replica DB server: ' . $this->lastError
;
762 // Throw an exception
763 $this->reportConnectionError();
764 return null; // not reached
768 # Now we have an explicit index into the servers array
769 $conn = $this->openConnection( $i, $domain, $flags );
771 // Throw an exception
772 $this->reportConnectionError();
773 return null; // not reached
776 # Profile any new connections that happen
777 if ( $this->connsOpened
> $oldConnsOpened ) {
778 $host = $conn->getServer();
779 $dbname = $conn->getDBname();
780 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
784 # Make master-requested DB handles inherit any read-only mode setting
785 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
791 public function reuseConnection( IDatabase
$conn ) {
792 $serverIndex = $conn->getLBInfo( 'serverIndex' );
793 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
794 if ( $serverIndex === null ||
$refCount === null ) {
796 * This can happen in code like:
797 * foreach ( $dbs as $db ) {
798 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
800 * $lb->reuseConnection( $conn );
802 * When a connection to the local DB is opened in this way, reuseConnection()
806 } elseif ( $conn instanceof DBConnRef
) {
807 // DBConnRef already handles calling reuseConnection() and only passes the live
808 // Database instance to this method. Any caller passing in a DBConnRef is broken.
809 $this->connLogger
->error(
810 __METHOD__
. ": got DBConnRef instance.\n" .
811 ( new RuntimeException() )->getTraceAsString() );
816 if ( $this->disabled
) {
817 return; // DBConnRef handle probably survived longer than the LoadBalancer
820 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
821 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
822 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
824 $connFreeKey = self
::KEY_FOREIGN_FREE
;
825 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
828 $domain = $conn->getDomainID();
829 if ( !isset( $this->conns
[$connInUseKey][$serverIndex][$domain] ) ) {
830 throw new InvalidArgumentException( __METHOD__
.
831 ": connection $serverIndex/$domain not found; it may have already been freed." );
832 } elseif ( $this->conns
[$connInUseKey][$serverIndex][$domain] !== $conn ) {
833 throw new InvalidArgumentException( __METHOD__
.
834 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
837 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
838 if ( $refCount <= 0 ) {
839 $this->conns
[$connFreeKey][$serverIndex][$domain] = $conn;
840 unset( $this->conns
[$connInUseKey][$serverIndex][$domain] );
841 if ( !$this->conns
[$connInUseKey][$serverIndex] ) {
842 unset( $this->conns
[$connInUseKey][$serverIndex] ); // clean up
844 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
846 $this->connLogger
->debug( __METHOD__
.
847 ": reference count for $serverIndex/$domain reduced to $refCount" );
851 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
852 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
854 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
857 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
858 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
860 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
863 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
864 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
866 return new MaintainableDBConnRef(
867 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
870 public function openConnection( $i, $domain = false, $flags = 0 ) {
871 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
872 $domain = false; // local connection requested
875 if ( !$this->connectionAttempted
&& $this->chronologyCallback
) {
876 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
877 // Load any "waitFor" positions before connecting so that doWait() is triggered
878 $this->connectionAttempted
= true;
879 call_user_func( $this->chronologyCallback
, $this );
882 // Check if an auto-commit connection is being requested. If so, it will not reuse the
883 // main set of DB connections but rather its own pool since:
884 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
885 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
886 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
888 if ( $domain !== false ) {
889 // Connection is to a foreign domain
890 $conn = $this->openForeignConnection( $i, $domain, $flags );
892 // Connection is to the local domain
893 $connKey = $autoCommit ? self
::KEY_LOCAL_NOROUND
: self
::KEY_LOCAL
;
894 if ( isset( $this->conns
[$connKey][$i][0] ) ) {
895 $conn = $this->conns
[$connKey][$i][0];
897 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
898 throw new InvalidArgumentException( "No server with index '$i'." );
900 // Open a new connection
901 $server = $this->servers
[$i];
902 $server['serverIndex'] = $i;
903 $server['autoCommitOnly'] = $autoCommit;
904 if ( $this->localDomain
->getDatabase() !== null ) {
905 // Use the local domain table prefix if the local domain is specified
906 $server['tablePrefix'] = $this->localDomain
->getTablePrefix();
908 $conn = $this->reallyOpenConnection( $server, $this->localDomain
);
909 $host = $this->getServerName( $i );
910 if ( $conn->isOpen() ) {
911 $this->connLogger
->debug(
912 __METHOD__
. ": connected to database $i at '$host'." );
913 $this->conns
[$connKey][$i][0] = $conn;
915 $this->connLogger
->warning(
916 __METHOD__
. ": failed to connect to database $i at '$host'." );
917 $this->errorConnection
= $conn;
923 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
924 // Connection was made but later unrecoverably lost for some reason.
925 // Do not return a handle that will just throw exceptions on use,
926 // but let the calling code (e.g. getReaderIndex) try another server.
927 // See DatabaseMyslBase::ping() for how this can happen.
928 $this->errorConnection
= $conn;
932 if ( $autoCommit && $conn instanceof IDatabase
) {
933 $conn->clearFlag( $conn::DBO_TRX
); // auto-commit mode
940 * Open a connection to a foreign DB, or return one if it is already open.
942 * Increments a reference count on the returned connection which locks the
943 * connection to the requested domain. This reference count can be
944 * decremented by calling reuseConnection().
946 * If a connection is open to the appropriate server already, but with the wrong
947 * database, it will be switched to the right database and returned, as long as
948 * it has been freed first with reuseConnection().
950 * On error, returns false, and the connection which caused the
951 * error will be available via $this->errorConnection.
953 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
955 * @param int $i Server index
956 * @param string $domain Domain ID to open
957 * @param int $flags Class CONN_* constant bitfield
960 private function openForeignConnection( $i, $domain, $flags = 0 ) {
961 $domainInstance = DatabaseDomain
::newFromId( $domain );
962 $dbName = $domainInstance->getDatabase();
963 $prefix = $domainInstance->getTablePrefix();
964 $autoCommit = ( ( $flags & self
::CONN_TRX_AUTOCOMMIT
) == self
::CONN_TRX_AUTOCOMMIT
);
967 $connFreeKey = self
::KEY_FOREIGN_FREE_NOROUND
;
968 $connInUseKey = self
::KEY_FOREIGN_INUSE_NOROUND
;
970 $connFreeKey = self
::KEY_FOREIGN_FREE
;
971 $connInUseKey = self
::KEY_FOREIGN_INUSE
;
974 if ( isset( $this->conns
[$connInUseKey][$i][$domain] ) ) {
975 // Reuse an in-use connection for the same domain
976 $conn = $this->conns
[$connInUseKey][$i][$domain];
977 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
978 } elseif ( isset( $this->conns
[$connFreeKey][$i][$domain] ) ) {
979 // Reuse a free connection for the same domain
980 $conn = $this->conns
[$connFreeKey][$i][$domain];
981 unset( $this->conns
[$connFreeKey][$i][$domain] );
982 $this->conns
[$connInUseKey][$i][$domain] = $conn;
983 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
984 } elseif ( !empty( $this->conns
[$connFreeKey][$i] ) ) {
985 // Reuse a free connection from another domain
986 $conn = reset( $this->conns
[$connFreeKey][$i] );
987 $oldDomain = key( $this->conns
[$connFreeKey][$i] );
988 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
989 $this->lastError
= "Error selecting database '$dbName' on server " .
990 $conn->getServer() . " from client host {$this->host}";
991 $this->errorConnection
= $conn;
994 $conn->tablePrefix( $prefix );
995 unset( $this->conns
[$connFreeKey][$i][$oldDomain] );
996 // Note that if $domain is an empty string, getDomainID() might not match it
997 $this->conns
[$connInUseKey][$i][$conn->getDomainId()] = $conn;
998 $this->connLogger
->debug( __METHOD__
.
999 ": reusing free connection from $oldDomain for $domain" );
1002 if ( !isset( $this->servers
[$i] ) ||
!is_array( $this->servers
[$i] ) ) {
1003 throw new InvalidArgumentException( "No server with index '$i'." );
1005 // Open a new connection
1006 $server = $this->servers
[$i];
1007 $server['serverIndex'] = $i;
1008 $server['foreignPoolRefCount'] = 0;
1009 $server['foreign'] = true;
1010 $server['autoCommitOnly'] = $autoCommit;
1011 $conn = $this->reallyOpenConnection( $server, $domainInstance );
1012 if ( !$conn->isOpen() ) {
1013 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
1014 $this->errorConnection
= $conn;
1017 $conn->tablePrefix( $prefix ); // as specified
1018 // Note that if $domain is an empty string, getDomainID() might not match it
1019 $this->conns
[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1020 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
1024 // Increment reference count
1025 if ( $conn instanceof IDatabase
) {
1026 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
1027 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
1033 public function getServerAttributes( $i ) {
1034 return Database
::attributesFromType(
1035 $this->getServerType( $i ),
1036 isset( $this->servers
[$i]['driver'] ) ?
$this->servers
[$i]['driver'] : null
1041 * Test if the specified index represents an open connection
1043 * @param int $index Server index
1047 private function isOpen( $index ) {
1048 if ( !is_int( $index ) ) {
1052 return (bool)$this->getAnyOpenConnection( $index );
1056 * Open a new network connection to a server (uncached)
1058 * Returns a Database object whether or not the connection was successful.
1060 * @param array $server
1061 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1063 * @throws DBAccessError
1064 * @throws InvalidArgumentException
1066 protected function reallyOpenConnection( array $server, DatabaseDomain
$domainOverride ) {
1067 if ( $this->disabled
) {
1068 throw new DBAccessError();
1071 // Handle $domainOverride being a specified or an unspecified domain
1072 if ( $domainOverride->getDatabase() === null ) {
1073 // Normally, an RDBMS requires a DB name specified on connection and the $server
1074 // configuration array is assumed to already specify an appropriate DB name.
1075 if ( $server['type'] === 'mysql' ) {
1076 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1077 // and the DB name in $server might not exist due to legacy reasons (the default
1078 // domain used to ignore the local LB domain, even when mismatched).
1079 $server['dbname'] = null;
1082 $server['dbname'] = $domainOverride->getDatabase();
1083 $server['schema'] = $domainOverride->getSchema();
1086 // Let the handle know what the cluster master is (e.g. "db1052")
1087 $masterName = $this->getServerName( $this->getWriterIndex() );
1088 $server['clusterMasterHost'] = $masterName;
1090 // Log when many connection are made on requests
1091 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
1092 $this->perfLogger
->warning( __METHOD__
. ": " .
1093 "{$this->connsOpened}+ connections made (master=$masterName)" );
1096 $server['srvCache'] = $this->srvCache
;
1097 // Set loggers and profilers
1098 $server['connLogger'] = $this->connLogger
;
1099 $server['queryLogger'] = $this->queryLogger
;
1100 $server['errorLogger'] = $this->errorLogger
;
1101 $server['deprecationLogger'] = $this->deprecationLogger
;
1102 $server['profiler'] = $this->profiler
;
1103 $server['trxProfiler'] = $this->trxProfiler
;
1104 // Use the same agent and PHP mode for all DB handles
1105 $server['cliMode'] = $this->cliMode
;
1106 $server['agent'] = $this->agent
;
1107 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1108 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1109 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
1111 // Create a live connection object
1113 $db = Database
::factory( $server['type'], $server );
1114 } catch ( DBConnectionError
$e ) {
1115 // FIXME: This is probably the ugliest thing I have ever done to
1116 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1120 $db->setLBInfo( $server );
1121 $db->setLazyMasterHandle(
1122 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
1124 $db->setTableAliases( $this->tableAliases
);
1125 $db->setIndexAliases( $this->indexAliases
);
1127 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1128 if ( $this->trxRoundId
!== false ) {
1129 $this->applyTransactionRoundFlags( $db );
1131 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
1132 $db->setTransactionListener( $name, $callback );
1140 * @throws DBConnectionError
1142 private function reportConnectionError() {
1143 $conn = $this->errorConnection
; // the connection which caused the error
1145 'method' => __METHOD__
,
1146 'last_error' => $this->lastError
,
1149 if ( $conn instanceof IDatabase
) {
1150 $context['db_server'] = $conn->getServer();
1151 $this->connLogger
->warning(
1152 __METHOD__
. ": connection error: {last_error} ({db_server})",
1156 throw new DBConnectionError( $conn, "{$this->lastError} ({$context['db_server']})" );
1158 // No last connection, probably due to all servers being too busy
1159 $this->connLogger
->error(
1161 ": LB failure with no last connection. Connection error: {last_error}",
1165 // If all servers were busy, "lastError" will contain something sensible
1166 throw new DBConnectionError( null, $this->lastError
);
1170 public function getWriterIndex() {
1174 public function haveIndex( $i ) {
1175 return array_key_exists( $i, $this->servers
);
1178 public function isNonZeroLoad( $i ) {
1179 return array_key_exists( $i, $this->servers
) && $this->loads
[$i] != 0;
1182 public function getServerCount() {
1183 return count( $this->servers
);
1186 public function getServerName( $i ) {
1187 if ( isset( $this->servers
[$i]['hostName'] ) ) {
1188 $name = $this->servers
[$i]['hostName'];
1189 } elseif ( isset( $this->servers
[$i]['host'] ) ) {
1190 $name = $this->servers
[$i]['host'];
1195 return ( $name != '' ) ?
$name : 'localhost';
1198 public function getServerType( $i ) {
1199 return isset( $this->servers
[$i]['type'] ) ?
$this->servers
[$i]['type'] : 'unknown';
1202 public function getMasterPos() {
1203 # If this entire request was served from a replica DB without opening a connection to the
1204 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1205 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1206 if ( !$masterConn ) {
1207 $serverCount = count( $this->servers
);
1208 for ( $i = 1; $i < $serverCount; $i++
) {
1209 $conn = $this->getAnyOpenConnection( $i );
1211 return $conn->getReplicaPos();
1215 return $masterConn->getMasterPos();
1221 public function disable() {
1223 $this->disabled
= true;
1226 public function closeAll() {
1227 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1228 $host = $conn->getServer();
1229 $this->connLogger
->debug(
1230 __METHOD__
. ": closing connection to database '$host'." );
1235 self
::KEY_LOCAL
=> [],
1236 self
::KEY_FOREIGN_INUSE
=> [],
1237 self
::KEY_FOREIGN_FREE
=> [],
1238 self
::KEY_LOCAL_NOROUND
=> [],
1239 self
::KEY_FOREIGN_INUSE_NOROUND
=> [],
1240 self
::KEY_FOREIGN_FREE_NOROUND
=> []
1242 $this->connsOpened
= 0;
1245 public function closeConnection( IDatabase
$conn ) {
1246 $serverIndex = $conn->getLBInfo( 'serverIndex' );
1247 foreach ( $this->conns
as $type => $connsByServer ) {
1248 if ( !isset( $connsByServer[$serverIndex] ) ) {
1252 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1253 if ( $conn === $trackedConn ) {
1254 $host = $this->getServerName( $i );
1255 $this->connLogger
->debug(
1256 __METHOD__
. ": closing connection to database $i at '$host'." );
1257 unset( $this->conns
[$type][$serverIndex][$i] );
1258 --$this->connsOpened
;
1267 public function commitAll( $fname = __METHOD__
) {
1268 $this->commitMasterChanges( $fname );
1269 $this->flushMasterSnapshots( $fname );
1270 $this->flushReplicaSnapshots( $fname );
1273 public function finalizeMasterChanges() {
1274 $this->assertTransactionRoundStage( [ self
::ROUND_CURSORY
, self
::ROUND_FINALIZED
] );
1276 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1277 // Loop until callbacks stop adding callbacks on other connections
1280 $count = 0; // callbacks execution attempts
1281 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$count ) {
1282 // Run any pre-commit callbacks while leaving the post-commit ones suppressed.
1283 // Any error should cause all (peer) transactions to be rolled back together.
1284 $count +
= $conn->runOnTransactionPreCommitCallbacks();
1287 } while ( $count > 0 );
1288 // Defer post-commit callbacks until after COMMIT/ROLLBACK happens on all handles
1289 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1290 $conn->setTrxEndCallbackSuppression( true );
1292 $this->trxRoundStage
= self
::ROUND_FINALIZED
;
1297 public function approveMasterChanges( array $options ) {
1298 $this->assertTransactionRoundStage( self
::ROUND_FINALIZED
);
1300 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1302 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1303 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1304 // If atomic sections or explicit transactions are still open, some caller must have
1305 // caught an exception but failed to properly rollback any changes. Detect that and
1306 // throw and error (causing rollback).
1307 if ( $conn->explicitTrxActive() ) {
1308 throw new DBTransactionError(
1310 "Explicit transaction still active. A caller may have caught an error."
1313 // Assert that the time to replicate the transaction will be sane.
1314 // If this fails, then all DB transactions will be rollback back together.
1315 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1316 if ( $limit > 0 && $time > $limit ) {
1317 throw new DBTransactionSizeError(
1319 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1323 // If a connection sits idle while slow queries execute on another, that connection
1324 // may end up dropped before the commit round is reached. Ping servers to detect this.
1325 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1326 throw new DBTransactionError(
1328 "A connection to the {$conn->getDBname()} database was lost before commit."
1332 $this->trxRoundStage
= self
::ROUND_APPROVED
;
1335 public function beginMasterChanges( $fname = __METHOD__
) {
1336 if ( $this->trxRoundId
!== false ) {
1337 throw new DBTransactionError(
1339 "$fname: Transaction round '{$this->trxRoundId}' already started."
1342 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
1344 // Clear any empty transactions (no writes/callbacks) from the implicit round
1345 $this->flushMasterSnapshots( $fname );
1347 $this->trxRoundId
= $fname;
1348 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1349 // Mark applicable handles as participating in this explicit transaction round.
1350 // For each of these handles, any writes and callbacks will be tied to a single
1351 // transaction. The (peer) handles will reject begin()/commit() calls unless they
1352 // are part of an en masse commit or an en masse rollback.
1353 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1354 $this->applyTransactionRoundFlags( $conn );
1356 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1359 public function commitMasterChanges( $fname = __METHOD__
) {
1360 $this->assertTransactionRoundStage( self
::ROUND_APPROVED
);
1364 /** @noinspection PhpUnusedLocalVariableInspection */
1365 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1367 $restore = ( $this->trxRoundId
!== false );
1368 $this->trxRoundId
= false;
1369 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1370 // Commit any writes and clear any snapshots as well (callbacks require AUTOCOMMIT).
1371 // Note that callbacks should already be suppressed due to finalizeMasterChanges().
1372 $this->forEachOpenMasterConnection(
1373 function ( IDatabase
$conn ) use ( $fname, &$failures ) {
1375 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1376 } catch ( DBError
$e ) {
1377 call_user_func( $this->errorLogger
, $e );
1378 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1383 throw new DBTransactionError(
1385 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1389 // Unmark handles as participating in this explicit transaction round
1390 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1391 $this->undoTransactionRoundFlags( $conn );
1394 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
1397 public function runMasterTransactionIdleCallbacks() {
1398 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1399 $type = IDatabase
::TRIGGER_COMMIT
;
1400 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1401 $type = IDatabase
::TRIGGER_ROLLBACK
;
1403 throw new DBTransactionError(
1405 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1409 $oldStage = $this->trxRoundStage
;
1410 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1412 // Now that the COMMIT/ROLLBACK step is over, enable post-commit callback runs
1413 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1414 $conn->setTrxEndCallbackSuppression( false );
1417 $e = null; // first exception
1418 // Loop until callbacks stop adding callbacks on other connections
1420 // Run any pending callbacks for each connection...
1421 $count = 0; // callback execution attempts
1422 $this->forEachOpenMasterConnection(
1423 function ( Database
$conn ) use ( $type, &$e, &$count ) {
1424 if ( $conn->trxLevel() ) {
1425 return; // retry in the next iteration, after commit() is called
1428 $count +
= $conn->runOnTransactionIdleCallbacks( $type );
1429 } catch ( Exception
$ex ) {
1434 // Clear out any active transactions left over from callbacks...
1435 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( &$e ) {
1436 if ( $conn->writesPending() ) {
1437 // A callback from another handle wrote to this one and DBO_TRX is set
1438 $this->queryLogger
->warning( __METHOD__
. ": found writes pending." );
1439 $fnames = implode( ', ', $conn->pendingWriteAndCallbackCallers() );
1440 $this->queryLogger
->warning(
1441 __METHOD__
. ": found writes pending ($fnames).",
1443 'db_server' => $conn->getServer(),
1444 'db_name' => $conn->getDBname()
1447 } elseif ( $conn->trxLevel() ) {
1448 // A callback from another handle read from this one and DBO_TRX is set,
1449 // which can easily happen if there is only one DB (no replicas)
1450 $this->queryLogger
->debug( __METHOD__
. ": found empty transaction." );
1453 $conn->commit( __METHOD__
, $conn::FLUSHING_ALL_PEERS
);
1454 } catch ( Exception
$ex ) {
1458 } while ( $count > 0 );
1460 $this->trxRoundStage
= $oldStage;
1465 public function runMasterTransactionListenerCallbacks() {
1466 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
1467 $type = IDatabase
::TRIGGER_COMMIT
;
1468 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
1469 $type = IDatabase
::TRIGGER_ROLLBACK
;
1471 throw new DBTransactionError(
1473 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1479 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1480 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1482 $conn->runTransactionListenerCallbacks( $type );
1483 } catch ( Exception
$ex ) {
1487 $this->trxRoundStage
= self
::ROUND_CURSORY
;
1492 public function rollbackMasterChanges( $fname = __METHOD__
) {
1493 $restore = ( $this->trxRoundId
!== false );
1494 $this->trxRoundId
= false;
1495 $this->trxRoundStage
= self
::ROUND_ERROR
; // "failed" until proven otherwise
1496 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1497 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1500 // Unmark handles as participating in this explicit transaction round
1501 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1502 $this->undoTransactionRoundFlags( $conn );
1505 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
1509 * @param string|string[] $stage
1511 private function assertTransactionRoundStage( $stage ) {
1512 $stages = (array)$stage;
1514 if ( !in_array( $this->trxRoundStage
, $stages, true ) ) {
1515 $stageList = implode(
1517 array_map( function ( $v ) {
1521 throw new DBTransactionError(
1523 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1529 * Make all DB servers with DBO_DEFAULT/DBO_TRX set join the transaction round
1531 * Some servers may have neither flag enabled, meaning that they opt out of such
1532 * transaction rounds and remain in auto-commit mode. Such behavior might be desired
1533 * when a DB server is used for something like simple key/value storage.
1535 * @param Database $conn
1537 private function applyTransactionRoundFlags( Database
$conn ) {
1538 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1539 return; // transaction rounds do not apply to these connections
1542 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1543 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1544 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1545 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1548 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1549 $conn->setLBInfo( 'trxRoundId', $this->trxRoundId
);
1554 * @param Database $conn
1556 private function undoTransactionRoundFlags( Database
$conn ) {
1557 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1558 return; // transaction rounds do not apply to these connections
1561 if ( $conn->getFlag( $conn::DBO_TRX
) ) {
1562 $conn->setLBInfo( 'trxRoundId', false );
1565 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1566 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1570 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1571 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) use ( $fname ) {
1572 $conn->flushSnapshot( $fname );
1576 public function flushMasterSnapshots( $fname = __METHOD__
) {
1577 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $fname ) {
1578 $conn->flushSnapshot( $fname );
1586 public function getTransactionRoundStage() {
1587 return $this->trxRoundStage
;
1590 public function hasMasterConnection() {
1591 return $this->isOpen( $this->getWriterIndex() );
1594 public function hasMasterChanges() {
1596 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1597 $pending |
= $conn->writesOrCallbacksPending();
1600 return (bool)$pending;
1603 public function lastMasterChangeTimestamp() {
1605 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1606 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1612 public function hasOrMadeRecentMasterChanges( $age = null ) {
1613 $age = ( $age === null ) ?
$this->waitTimeout
: $age;
1615 return ( $this->hasMasterChanges()
1616 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1619 public function pendingMasterChangeCallers() {
1621 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1622 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1628 public function getLaggedReplicaMode( $domain = false ) {
1629 // No-op if there is only one DB (also avoids recursion)
1630 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1632 // See if laggedReplicaMode gets set
1633 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1634 $this->reuseConnection( $conn );
1635 } catch ( DBConnectionError
$e ) {
1636 // Avoid expensive re-connect attempts and failures
1637 $this->allReplicasDownMode
= true;
1638 $this->laggedReplicaMode
= true;
1642 return $this->laggedReplicaMode
;
1645 public function laggedReplicaUsed() {
1646 return $this->laggedReplicaMode
;
1652 * @deprecated Since 1.28; use laggedReplicaUsed()
1654 public function laggedSlaveUsed() {
1655 return $this->laggedReplicaUsed();
1658 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1659 if ( $this->readOnlyReason
!== false ) {
1660 return $this->readOnlyReason
;
1661 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1662 if ( $this->allReplicasDownMode
) {
1663 return 'The database has been automatically locked ' .
1664 'until the replica database servers become available';
1666 return 'The database has been automatically locked ' .
1667 'while the replica database servers catch up to the master.';
1669 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1670 return 'The database master is running in read-only mode.';
1677 * @param string $domain Domain ID, or false for the current domain
1678 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1681 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1682 $cache = $this->wanCache
;
1683 $masterServer = $this->getServerName( $this->getWriterIndex() );
1685 return (bool)$cache->getWithSetCallback(
1686 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1687 self
::TTL_CACHE_READONLY
,
1688 function () use ( $domain, $conn ) {
1689 $old = $this->trxProfiler
->setSilenced( true );
1691 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1692 $readOnly = (int)$dbw->serverIsReadOnly();
1694 $this->reuseConnection( $dbw );
1696 } catch ( DBError
$e ) {
1699 $this->trxProfiler
->setSilenced( $old );
1702 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1706 public function allowLagged( $mode = null ) {
1707 if ( $mode === null ) {
1708 return $this->allowLagged
;
1710 $this->allowLagged
= $mode;
1712 return $this->allowLagged
;
1715 public function pingAll() {
1717 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1718 if ( !$conn->ping() ) {
1726 public function forEachOpenConnection( $callback, array $params = [] ) {
1727 foreach ( $this->conns
as $connsByServer ) {
1728 foreach ( $connsByServer as $serverConns ) {
1729 foreach ( $serverConns as $conn ) {
1730 $mergedParams = array_merge( [ $conn ], $params );
1731 call_user_func_array( $callback, $mergedParams );
1737 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1738 $masterIndex = $this->getWriterIndex();
1739 foreach ( $this->conns
as $connsByServer ) {
1740 if ( isset( $connsByServer[$masterIndex] ) ) {
1741 /** @var IDatabase $conn */
1742 foreach ( $connsByServer[$masterIndex] as $conn ) {
1743 $mergedParams = array_merge( [ $conn ], $params );
1744 call_user_func_array( $callback, $mergedParams );
1750 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1751 foreach ( $this->conns
as $connsByServer ) {
1752 foreach ( $connsByServer as $i => $serverConns ) {
1753 if ( $i === $this->getWriterIndex() ) {
1754 continue; // skip master
1756 foreach ( $serverConns as $conn ) {
1757 $mergedParams = array_merge( [ $conn ], $params );
1758 call_user_func_array( $callback, $mergedParams );
1764 public function getMaxLag( $domain = false ) {
1769 if ( $this->getServerCount() <= 1 ) {
1770 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1773 $lagTimes = $this->getLagTimes( $domain );
1774 foreach ( $lagTimes as $i => $lag ) {
1775 if ( $this->loads
[$i] > 0 && $lag > $maxLag ) {
1777 $host = $this->servers
[$i]['host'];
1782 return [ $host, $maxLag, $maxIndex ];
1785 public function getLagTimes( $domain = false ) {
1786 if ( $this->getServerCount() <= 1 ) {
1787 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1790 $knownLagTimes = []; // map of (server index => 0 seconds)
1791 $indexesWithLag = [];
1792 foreach ( $this->servers
as $i => $server ) {
1793 if ( empty( $server['is static'] ) ) {
1794 $indexesWithLag[] = $i; // DB server might have replication lag
1796 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1800 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1803 public function safeGetLag( IDatabase
$conn ) {
1804 if ( $this->getServerCount() <= 1 ) {
1807 return $conn->getLag();
1812 * @param IDatabase $conn
1813 * @param DBMasterPos|bool $pos
1814 * @param int|null $timeout
1817 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null ) {
1818 $timeout = max( 1, $timeout ?
: $this->waitTimeout
);
1820 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1821 return true; // server is not a replica DB
1825 // Get the current master position, opening a connection if needed
1826 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1827 if ( $masterConn ) {
1828 $pos = $masterConn->getMasterPos();
1830 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1831 $pos = $masterConn->getMasterPos();
1832 $this->closeConnection( $masterConn );
1836 if ( $pos instanceof DBMasterPos
) {
1837 $result = $conn->masterPosWait( $pos, $timeout );
1838 if ( $result == -1 ||
is_null( $result ) ) {
1839 $msg = __METHOD__
. ': timed out waiting on {host} pos {pos}';
1840 $this->replLogger
->warning( $msg, [
1841 'host' => $conn->getServer(),
1843 'trace' => ( new RuntimeException() )->getTraceAsString()
1847 $this->replLogger
->debug( __METHOD__
. ': done waiting' );
1851 $ok = false; // something is misconfigured
1852 $this->replLogger
->error(
1853 __METHOD__
. ': could not get master pos for {host}',
1855 'host' => $conn->getServer(),
1856 'trace' => ( new RuntimeException() )->getTraceAsString()
1864 public function setTransactionListener( $name, callable
$callback = null ) {
1866 $this->trxRecurringCallbacks
[$name] = $callback;
1868 unset( $this->trxRecurringCallbacks
[$name] );
1870 $this->forEachOpenMasterConnection(
1871 function ( IDatabase
$conn ) use ( $name, $callback ) {
1872 $conn->setTransactionListener( $name, $callback );
1877 public function setTableAliases( array $aliases ) {
1878 $this->tableAliases
= $aliases;
1881 public function setIndexAliases( array $aliases ) {
1882 $this->indexAliases
= $aliases;
1885 public function setDomainPrefix( $prefix ) {
1886 // Find connections to explicit foreign domains still marked as in-use...
1888 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$domainsInUse ) {
1889 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1890 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1891 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1892 $domainsInUse[] = $conn->getDomainID();
1896 // Do not switch connections to explicit foreign domains unless marked as safe
1897 if ( $domainsInUse ) {
1898 $domains = implode( ', ', $domainsInUse );
1899 throw new DBUnexpectedError( null,
1900 "Foreign domain connections are still in use ($domains)." );
1903 $oldDomain = $this->localDomain
->getId();
1904 $this->setLocalDomain( new DatabaseDomain(
1905 $this->localDomain
->getDatabase(),
1906 $this->localDomain
->getSchema(),
1910 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix, $oldDomain ) {
1911 if ( !$db->getLBInfo( 'foreign' ) ) {
1912 $db->tablePrefix( $prefix );
1918 * @param DatabaseDomain $domain
1920 private function setLocalDomain( DatabaseDomain
$domain ) {
1921 $this->localDomain
= $domain;
1922 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1923 // always true, gracefully handle the case when they fail to account for escaping.
1924 if ( $this->localDomain
->getTablePrefix() != '' ) {
1925 $this->localDomainIdAlias
=
1926 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
1928 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
1933 * Make PHP ignore user aborts/disconnects until the returned
1934 * value leaves scope. This returns null and does nothing in CLI mode.
1936 * @return ScopedCallback|null
1938 final protected function getScopedPHPBehaviorForCommit() {
1939 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1940 $old = ignore_user_abort( true ); // avoid half-finished operations
1941 return new ScopedCallback( function () use ( $old ) {
1942 ignore_user_abort( $old );
1949 function __destruct() {
1950 // Avoid connection leaks for sanity
1955 class_alias( LoadBalancer
::class, 'LoadBalancer' );