Introduce InterwikiLookupAdapter on top of SiteLookup
[lhc/web/wiklou.git] / includes / db / loadbalancer / LBFactory.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 use Psr\Log\LoggerInterface;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Services\DestructibleService;
27 use MediaWiki\Logger\LoggerFactory;
28
29 /**
30 * An interface for generating database load balancers
31 * @ingroup Database
32 */
33 abstract class LBFactory implements DestructibleService {
34 /** @var ChronologyProtector */
35 protected $chronProt;
36 /** @var TransactionProfiler */
37 protected $trxProfiler;
38 /** @var LoggerInterface */
39 protected $trxLogger;
40 /** @var LoggerInterface */
41 protected $replLogger;
42 /** @var BagOStuff */
43 protected $srvCache;
44 /** @var BagOStuff */
45 protected $memCache;
46 /** @var WANObjectCache */
47 protected $wanCache;
48
49 /** @var mixed */
50 protected $ticket;
51 /** @var string|bool String if a requested DBO_TRX transaction round is active */
52 protected $trxRoundId = false;
53 /** @var string|bool Reason all LBs are read-only or false if not */
54 protected $readOnlyReason = false;
55 /** @var callable[] */
56 protected $replicationWaitCallbacks = [];
57
58 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
59 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
60 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
61
62 /**
63 * Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
64 * @param array $conf
65 * @TODO: inject objects via dependency framework
66 */
67 public function __construct( array $conf ) {
68 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
69 $this->readOnlyReason = $conf['readOnlyReason'];
70 }
71 $this->chronProt = $this->newChronologyProtector();
72 $this->trxProfiler = Profiler::instance()->getTransactionProfiler();
73 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
74 $sCache = ObjectCache::getLocalServerInstance();
75 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
76 $this->srvCache = $sCache;
77 } else {
78 $this->srvCache = new EmptyBagOStuff();
79 }
80 $cCache = ObjectCache::getLocalClusterInstance();
81 if ( $cCache->getQoS( $cCache::ATTR_EMULATION ) > $cCache::QOS_EMULATION_SQL ) {
82 $this->memCache = $cCache;
83 } else {
84 $this->memCache = new EmptyBagOStuff();
85 }
86 $wCache = ObjectCache::getMainWANInstance();
87 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
88 $this->wanCache = $wCache;
89 } else {
90 $this->wanCache = WANObjectCache::newEmpty();
91 }
92 $this->trxLogger = LoggerFactory::getInstance( 'DBTransaction' );
93 $this->replLogger = LoggerFactory::getInstance( 'DBReplication' );
94 $this->ticket = mt_rand();
95 }
96
97 /**
98 * Disables all load balancers. All connections are closed, and any attempt to
99 * open a new connection will result in a DBAccessError.
100 * @see LoadBalancer::disable()
101 */
102 public function destroy() {
103 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
104 $this->forEachLBCallMethod( 'disable' );
105 }
106
107 /**
108 * Disables all access to the load balancer, will cause all database access
109 * to throw a DBAccessError
110 */
111 public static function disableBackend() {
112 MediaWikiServices::disableStorageBackend();
113 }
114
115 /**
116 * Get an LBFactory instance
117 *
118 * @deprecated since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
119 *
120 * @return LBFactory
121 */
122 public static function singleton() {
123 return MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
124 }
125
126 /**
127 * Returns the LBFactory class to use and the load balancer configuration.
128 *
129 * @todo instead of this, use a ServiceContainer for managing the different implementations.
130 *
131 * @param array $config (e.g. $wgLBFactoryConf)
132 * @return string Class name
133 */
134 public static function getLBFactoryClass( array $config ) {
135 // For configuration backward compatibility after removing
136 // underscores from class names in MediaWiki 1.23.
137 $bcClasses = [
138 'LBFactory_Simple' => 'LBFactorySimple',
139 'LBFactory_Single' => 'LBFactorySingle',
140 'LBFactory_Multi' => 'LBFactoryMulti',
141 'LBFactory_Fake' => 'LBFactoryFake',
142 ];
143
144 $class = $config['class'];
145
146 if ( isset( $bcClasses[$class] ) ) {
147 $class = $bcClasses[$class];
148 wfDeprecated(
149 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
150 '1.23'
151 );
152 }
153
154 return $class;
155 }
156
157 /**
158 * Shut down, close connections and destroy the cached instance.
159 *
160 * @deprecated since 1.27, use LBFactory::destroy()
161 */
162 public static function destroyInstance() {
163 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
164 }
165
166 /**
167 * Create a new load balancer object. The resulting object will be untracked,
168 * not chronology-protected, and the caller is responsible for cleaning it up.
169 *
170 * @param bool|string $wiki Wiki ID, or false for the current wiki
171 * @return LoadBalancer
172 */
173 abstract public function newMainLB( $wiki = false );
174
175 /**
176 * Get a cached (tracked) load balancer object.
177 *
178 * @param bool|string $wiki Wiki ID, or false for the current wiki
179 * @return LoadBalancer
180 */
181 abstract public function getMainLB( $wiki = false );
182
183 /**
184 * Create a new load balancer for external storage. The resulting object will be
185 * untracked, not chronology-protected, and the caller is responsible for
186 * cleaning it up.
187 *
188 * @param string $cluster External storage cluster, or false for core
189 * @param bool|string $wiki Wiki ID, or false for the current wiki
190 * @return LoadBalancer
191 */
192 abstract protected function newExternalLB( $cluster, $wiki = false );
193
194 /**
195 * Get a cached (tracked) load balancer for external storage
196 *
197 * @param string $cluster External storage cluster, or false for core
198 * @param bool|string $wiki Wiki ID, or false for the current wiki
199 * @return LoadBalancer
200 */
201 abstract public function getExternalLB( $cluster, $wiki = false );
202
203 /**
204 * Execute a function for each tracked load balancer
205 * The callback is called with the load balancer as the first parameter,
206 * and $params passed as the subsequent parameters.
207 *
208 * @param callable $callback
209 * @param array $params
210 */
211 abstract public function forEachLB( $callback, array $params = [] );
212
213 /**
214 * Prepare all tracked load balancers for shutdown
215 * @param integer $mode One of the class SHUTDOWN_* constants
216 * @param callable|null $workCallback Work to mask ChronologyProtector writes
217 */
218 public function shutdown(
219 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
220 ) {
221 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
222 $this->shutdownChronologyProtector( $this->chronProt, $workCallback, 'sync' );
223 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
224 $this->shutdownChronologyProtector( $this->chronProt, null, 'async' );
225 }
226
227 $this->commitMasterChanges( __METHOD__ ); // sanity
228 }
229
230 /**
231 * Call a method of each tracked load balancer
232 *
233 * @param string $methodName
234 * @param array $args
235 */
236 private function forEachLBCallMethod( $methodName, array $args = [] ) {
237 $this->forEachLB(
238 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
239 call_user_func_array( [ $loadBalancer, $methodName ], $args );
240 },
241 [ $methodName, $args ]
242 );
243 }
244
245 /**
246 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
247 *
248 * @param string $fname Caller name
249 * @since 1.28
250 */
251 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
252 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
253 }
254
255 /**
256 * Commit on all connections. Done for two reasons:
257 * 1. To commit changes to the masters.
258 * 2. To release the snapshot on all connections, master and replica DB.
259 * @param string $fname Caller name
260 * @param array $options Options map:
261 * - maxWriteDuration: abort if more than this much time was spent in write queries
262 */
263 public function commitAll( $fname = __METHOD__, array $options = [] ) {
264 $this->commitMasterChanges( $fname, $options );
265 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
266 }
267
268 /**
269 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
270 *
271 * The DBO_TRX setting will be reverted to the default in each of these methods:
272 * - commitMasterChanges()
273 * - rollbackMasterChanges()
274 * - commitAll()
275 *
276 * This allows for custom transaction rounds from any outer transaction scope.
277 *
278 * @param string $fname
279 * @throws DBTransactionError
280 * @since 1.28
281 */
282 public function beginMasterChanges( $fname = __METHOD__ ) {
283 if ( $this->trxRoundId !== false ) {
284 throw new DBTransactionError(
285 null,
286 "$fname: transaction round '{$this->trxRoundId}' already started."
287 );
288 }
289 $this->trxRoundId = $fname;
290 // Set DBO_TRX flags on all appropriate DBs
291 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
292 }
293
294 /**
295 * Commit changes on all master connections
296 * @param string $fname Caller name
297 * @param array $options Options map:
298 * - maxWriteDuration: abort if more than this much time was spent in write queries
299 * @throws Exception
300 */
301 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
302 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
303 throw new DBTransactionError(
304 null,
305 "$fname: transaction round '{$this->trxRoundId}' still running."
306 );
307 }
308 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
309 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
310 $this->trxRoundId = false;
311 // Perform pre-commit checks, aborting on failure
312 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
313 // Log the DBs and methods involved in multi-DB transactions
314 $this->logIfMultiDbTransaction();
315 // Actually perform the commit on all master DB connections and revert DBO_TRX
316 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
317 // Run all post-commit callbacks
318 /** @var Exception $e */
319 $e = null; // first callback exception
320 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$e ) {
321 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
322 $e = $e ?: $ex;
323 } );
324 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
325 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
326 // Throw any last post-commit callback error
327 if ( $e instanceof Exception ) {
328 throw $e;
329 }
330 }
331
332 /**
333 * Rollback changes on all master connections
334 * @param string $fname Caller name
335 * @since 1.23
336 */
337 public function rollbackMasterChanges( $fname = __METHOD__ ) {
338 $this->trxRoundId = false;
339 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
340 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
341 // Run all post-rollback callbacks
342 $this->forEachLB( function ( LoadBalancer $lb ) {
343 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
344 } );
345 }
346
347 /**
348 * Log query info if multi DB transactions are going to be committed now
349 */
350 private function logIfMultiDbTransaction() {
351 $callersByDB = [];
352 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
353 $masterName = $lb->getServerName( $lb->getWriterIndex() );
354 $callers = $lb->pendingMasterChangeCallers();
355 if ( $callers ) {
356 $callersByDB[$masterName] = $callers;
357 }
358 } );
359
360 if ( count( $callersByDB ) >= 2 ) {
361 $dbs = implode( ', ', array_keys( $callersByDB ) );
362 $msg = "Multi-DB transaction [{$dbs}]:\n";
363 foreach ( $callersByDB as $db => $callers ) {
364 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
365 }
366 $this->trxLogger->info( $msg );
367 }
368 }
369
370 /**
371 * Determine if any master connection has pending changes
372 * @return bool
373 * @since 1.23
374 */
375 public function hasMasterChanges() {
376 $ret = false;
377 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
378 $ret = $ret || $lb->hasMasterChanges();
379 } );
380
381 return $ret;
382 }
383
384 /**
385 * Detemine if any lagged replica DB connection was used
386 * @return bool
387 * @since 1.28
388 */
389 public function laggedReplicaUsed() {
390 $ret = false;
391 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
392 $ret = $ret || $lb->laggedReplicaUsed();
393 } );
394
395 return $ret;
396 }
397
398 /**
399 * @return bool
400 * @since 1.27
401 * @deprecated Since 1.28; use laggedReplicaUsed()
402 */
403 public function laggedSlaveUsed() {
404 return $this->laggedReplicaUsed();
405 }
406
407 /**
408 * Determine if any master connection has pending/written changes from this request
409 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
410 * @return bool
411 * @since 1.27
412 */
413 public function hasOrMadeRecentMasterChanges( $age = null ) {
414 $ret = false;
415 $this->forEachLB( function ( LoadBalancer $lb ) use ( $age, &$ret ) {
416 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
417 } );
418 return $ret;
419 }
420
421 /**
422 * Waits for the replica DBs to catch up to the current master position
423 *
424 * Use this when updating very large numbers of rows, as in maintenance scripts,
425 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
426 *
427 * By default this waits on all DB clusters actually used in this request.
428 * This makes sense when lag being waiting on is caused by the code that does this check.
429 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
430 * that were not changed since the last wait check. To forcefully wait on a specific cluster
431 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
432 * use the "cluster" parameter.
433 *
434 * Never call this function after a large DB write that is *still* in a transaction.
435 * It only makes sense to call this after the possible lag inducing changes were committed.
436 *
437 * @param array $opts Optional fields that include:
438 * - wiki : wait on the load balancer DBs that handles the given wiki
439 * - cluster : wait on the given external load balancer DBs
440 * - timeout : Max wait time. Default: ~60 seconds
441 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
442 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
443 * @since 1.27
444 */
445 public function waitForReplication( array $opts = [] ) {
446 $opts += [
447 'wiki' => false,
448 'cluster' => false,
449 'timeout' => 60,
450 'ifWritesSince' => null
451 ];
452
453 // Figure out which clusters need to be checked
454 /** @var LoadBalancer[] $lbs */
455 $lbs = [];
456 if ( $opts['cluster'] !== false ) {
457 $lbs[] = $this->getExternalLB( $opts['cluster'] );
458 } elseif ( $opts['wiki'] !== false ) {
459 $lbs[] = $this->getMainLB( $opts['wiki'] );
460 } else {
461 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
462 $lbs[] = $lb;
463 } );
464 if ( !$lbs ) {
465 return; // nothing actually used
466 }
467 }
468
469 // Get all the master positions of applicable DBs right now.
470 // This can be faster since waiting on one cluster reduces the
471 // time needed to wait on the next clusters.
472 $masterPositions = array_fill( 0, count( $lbs ), false );
473 foreach ( $lbs as $i => $lb ) {
474 if ( $lb->getServerCount() <= 1 ) {
475 // Bug 27975 - Don't try to wait for replica DBs if there are none
476 // Prevents permission error when getting master position
477 continue;
478 } elseif ( $opts['ifWritesSince']
479 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
480 ) {
481 continue; // no writes since the last wait
482 }
483 $masterPositions[$i] = $lb->getMasterPos();
484 }
485
486 // Run any listener callbacks *after* getting the DB positions. The more
487 // time spent in the callbacks, the less time is spent in waitForAll().
488 foreach ( $this->replicationWaitCallbacks as $callback ) {
489 $callback();
490 }
491
492 $failed = [];
493 foreach ( $lbs as $i => $lb ) {
494 if ( $masterPositions[$i] ) {
495 // The DBMS may not support getMasterPos() or the whole
496 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
497 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
498 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
499 }
500 }
501 }
502
503 if ( $failed ) {
504 throw new DBReplicationWaitError(
505 "Could not wait for replica DBs to catch up to " .
506 implode( ', ', $failed )
507 );
508 }
509 }
510
511 /**
512 * Add a callback to be run in every call to waitForReplication() before waiting
513 *
514 * Callbacks must clear any transactions that they start
515 *
516 * @param string $name Callback name
517 * @param callable|null $callback Use null to unset a callback
518 * @since 1.28
519 */
520 public function setWaitForReplicationListener( $name, callable $callback = null ) {
521 if ( $callback ) {
522 $this->replicationWaitCallbacks[$name] = $callback;
523 } else {
524 unset( $this->replicationWaitCallbacks[$name] );
525 }
526 }
527
528 /**
529 * Get a token asserting that no transaction writes are active
530 *
531 * @param string $fname Caller name (e.g. __METHOD__)
532 * @return mixed A value to pass to commitAndWaitForReplication()
533 * @since 1.28
534 */
535 public function getEmptyTransactionTicket( $fname ) {
536 if ( $this->hasMasterChanges() ) {
537 $this->trxLogger->error( __METHOD__ . ": $fname does not have outer scope." );
538 return null;
539 }
540
541 return $this->ticket;
542 }
543
544 /**
545 * Convenience method for safely running commitMasterChanges()/waitForReplication()
546 *
547 * This will commit and wait unless $ticket indicates it is unsafe to do so
548 *
549 * @param string $fname Caller name (e.g. __METHOD__)
550 * @param mixed $ticket Result of getEmptyTransactionTicket()
551 * @param array $opts Options to waitForReplication()
552 * @throws DBReplicationWaitError
553 * @since 1.28
554 */
555 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
556 if ( $ticket !== $this->ticket ) {
557 $logger = LoggerFactory::getInstance( 'DBPerformance' );
558 $logger->error( __METHOD__ . ": cannot commit; $fname does not have outer scope." );
559 return;
560 }
561
562 // The transaction owner and any caller with the empty transaction ticket can commit
563 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
564 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
565 $this->trxLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
566 $fnameEffective = $this->trxRoundId;
567 } else {
568 $fnameEffective = $fname;
569 }
570
571 $this->commitMasterChanges( $fnameEffective );
572 $this->waitForReplication( $opts );
573 // If a nested caller committed on behalf of $fname, start another empty $fname
574 // transaction, leaving the caller with the same empty transaction state as before.
575 if ( $fnameEffective !== $fname ) {
576 $this->beginMasterChanges( $fnameEffective );
577 }
578 }
579
580 /**
581 * @param string $dbName DB master name (e.g. "db1052")
582 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
583 * @since 1.28
584 */
585 public function getChronologyProtectorTouched( $dbName ) {
586 return $this->chronProt->getTouched( $dbName );
587 }
588
589 /**
590 * Disable the ChronologyProtector for all load balancers
591 *
592 * This can be called at the start of special API entry points
593 *
594 * @since 1.27
595 */
596 public function disableChronologyProtection() {
597 $this->chronProt->setEnabled( false );
598 }
599
600 /**
601 * @return ChronologyProtector
602 */
603 protected function newChronologyProtector() {
604 $request = RequestContext::getMain()->getRequest();
605 $chronProt = new ChronologyProtector(
606 ObjectCache::getMainStashInstance(),
607 [
608 'ip' => $request->getIP(),
609 'agent' => $request->getHeader( 'User-Agent' ),
610 ],
611 $request->getFloat( 'cpPosTime', $request->getCookie( 'cpPosTime', '' ) )
612 );
613 if ( PHP_SAPI === 'cli' ) {
614 $chronProt->setEnabled( false );
615 } elseif ( $request->getHeader( 'ChronologyProtection' ) === 'false' ) {
616 // Request opted out of using position wait logic. This is useful for requests
617 // done by the job queue or background ETL that do not have a meaningful session.
618 $chronProt->setWaitEnabled( false );
619 }
620
621 return $chronProt;
622 }
623
624 /**
625 * Get and record all of the staged DB positions into persistent memory storage
626 *
627 * @param ChronologyProtector $cp
628 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
629 * @param string $mode One of (sync, async); whether to wait on remote datacenters
630 */
631 protected function shutdownChronologyProtector(
632 ChronologyProtector $cp, $workCallback, $mode
633 ) {
634 // Record all the master positions needed
635 $this->forEachLB( function ( LoadBalancer $lb ) use ( $cp ) {
636 $cp->shutdownLB( $lb );
637 } );
638 // Write them to the persistent stash. Try to do something useful by running $work
639 // while ChronologyProtector waits for the stash write to replicate to all DCs.
640 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
641 if ( $unsavedPositions && $workCallback ) {
642 // Invoke callback in case it did not cache the result yet
643 $workCallback(); // work now to block for less time in waitForAll()
644 }
645 // If the positions failed to write to the stash, at least wait on local datacenter
646 // replica DBs to catch up before responding. Even if there are several DCs, this increases
647 // the chance that the user will see their own changes immediately afterwards. As long
648 // as the sticky DC cookie applies (same domain), this is not even an issue.
649 $this->forEachLB( function ( LoadBalancer $lb ) use ( $unsavedPositions ) {
650 $masterName = $lb->getServerName( $lb->getWriterIndex() );
651 if ( isset( $unsavedPositions[$masterName] ) ) {
652 $lb->waitForAll( $unsavedPositions[$masterName] );
653 }
654 } );
655 }
656
657 /**
658 * Base parameters to LoadBalancer::__construct()
659 * @return array
660 */
661 final protected function baseLoadBalancerParams() {
662 return [
663 'localDomain' => wfWikiID(),
664 'readOnlyReason' => $this->readOnlyReason,
665 'srvCache' => $this->srvCache,
666 'memCache' => $this->memCache,
667 'wanCache' => $this->wanCache,
668 'trxProfiler' => $this->trxProfiler,
669 'queryLogger' => LoggerFactory::getInstance( 'DBQuery' ),
670 'connLogger' => LoggerFactory::getInstance( 'DBConnection' ),
671 'replLogger' => LoggerFactory::getInstance( 'DBReplication' ),
672 'errorLogger' => [ MWExceptionHandler::class, 'logException' ]
673 ];
674 }
675
676 /**
677 * @param LoadBalancer $lb
678 */
679 protected function initLoadBalancer( LoadBalancer $lb ) {
680 if ( $this->trxRoundId !== false ) {
681 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
682 }
683 }
684
685 /**
686 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
687 *
688 * Note that unlike cookies, this works accross domains
689 *
690 * @param string $url
691 * @param float $time UNIX timestamp just before shutdown() was called
692 * @return string
693 * @since 1.28
694 */
695 public function appendPreShutdownTimeAsQuery( $url, $time ) {
696 $usedCluster = 0;
697 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$usedCluster ) {
698 $usedCluster |= ( $lb->getServerCount() > 1 );
699 } );
700
701 if ( !$usedCluster ) {
702 return $url; // no master/replica clusters touched
703 }
704
705 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
706 }
707
708 /**
709 * Close all open database connections on all open load balancers.
710 * @since 1.28
711 */
712 public function closeAll() {
713 $this->forEachLBCallMethod( 'closeAll', [] );
714 }
715 }