Remove unused LBFactoryFake class
[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 // Use APC/memcached style caching, but avoids loops with CACHE_DB (T141804)
72 $sCache = ObjectCache::getLocalServerInstance();
73 if ( $sCache->getQoS( $sCache::ATTR_EMULATION ) > $sCache::QOS_EMULATION_SQL ) {
74 $this->srvCache = $sCache;
75 } else {
76 $this->srvCache = new EmptyBagOStuff();
77 }
78 $cCache = ObjectCache::getLocalClusterInstance();
79 if ( $cCache->getQoS( $cCache::ATTR_EMULATION ) > $cCache::QOS_EMULATION_SQL ) {
80 $this->memCache = $cCache;
81 } else {
82 $this->memCache = new EmptyBagOStuff();
83 }
84 $wCache = ObjectCache::getMainWANInstance();
85 if ( $wCache->getQoS( $wCache::ATTR_EMULATION ) > $wCache::QOS_EMULATION_SQL ) {
86 $this->wanCache = $wCache;
87 } else {
88 $this->wanCache = WANObjectCache::newEmpty();
89 }
90 $this->trxProfiler = Profiler::instance()->getTransactionProfiler();
91 $this->trxLogger = LoggerFactory::getInstance( 'DBTransaction' );
92 $this->replLogger = LoggerFactory::getInstance( 'DBReplication' );
93 $this->chronProt = $this->newChronologyProtector();
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 ];
142
143 $class = $config['class'];
144
145 if ( isset( $bcClasses[$class] ) ) {
146 $class = $bcClasses[$class];
147 wfDeprecated(
148 '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details',
149 '1.23'
150 );
151 }
152
153 return $class;
154 }
155
156 /**
157 * Shut down, close connections and destroy the cached instance.
158 *
159 * @deprecated since 1.27, use LBFactory::destroy()
160 */
161 public static function destroyInstance() {
162 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
163 }
164
165 /**
166 * Create a new load balancer object. The resulting object will be untracked,
167 * not chronology-protected, and the caller is responsible for cleaning it up.
168 *
169 * @param bool|string $wiki Wiki ID, or false for the current wiki
170 * @return LoadBalancer
171 */
172 abstract public function newMainLB( $wiki = false );
173
174 /**
175 * Get a cached (tracked) load balancer object.
176 *
177 * @param bool|string $wiki Wiki ID, or false for the current wiki
178 * @return LoadBalancer
179 */
180 abstract public function getMainLB( $wiki = false );
181
182 /**
183 * Create a new load balancer for external storage. The resulting object will be
184 * untracked, not chronology-protected, and the caller is responsible for
185 * cleaning it up.
186 *
187 * @param string $cluster External storage cluster, or false for core
188 * @param bool|string $wiki Wiki ID, or false for the current wiki
189 * @return LoadBalancer
190 */
191 abstract protected function newExternalLB( $cluster, $wiki = false );
192
193 /**
194 * Get a cached (tracked) load balancer for external storage
195 *
196 * @param string $cluster External storage cluster, or false for core
197 * @param bool|string $wiki Wiki ID, or false for the current wiki
198 * @return LoadBalancer
199 */
200 abstract public function getExternalLB( $cluster, $wiki = false );
201
202 /**
203 * Execute a function for each tracked load balancer
204 * The callback is called with the load balancer as the first parameter,
205 * and $params passed as the subsequent parameters.
206 *
207 * @param callable $callback
208 * @param array $params
209 */
210 abstract public function forEachLB( $callback, array $params = [] );
211
212 /**
213 * Prepare all tracked load balancers for shutdown
214 * @param integer $mode One of the class SHUTDOWN_* constants
215 * @param callable|null $workCallback Work to mask ChronologyProtector writes
216 */
217 public function shutdown(
218 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
219 ) {
220 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
221 $this->shutdownChronologyProtector( $this->chronProt, $workCallback, 'sync' );
222 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
223 $this->shutdownChronologyProtector( $this->chronProt, null, 'async' );
224 }
225
226 $this->commitMasterChanges( __METHOD__ ); // sanity
227 }
228
229 /**
230 * Call a method of each tracked load balancer
231 *
232 * @param string $methodName
233 * @param array $args
234 */
235 private function forEachLBCallMethod( $methodName, array $args = [] ) {
236 $this->forEachLB(
237 function ( LoadBalancer $loadBalancer, $methodName, array $args ) {
238 call_user_func_array( [ $loadBalancer, $methodName ], $args );
239 },
240 [ $methodName, $args ]
241 );
242 }
243
244 /**
245 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
246 *
247 * @param string $fname Caller name
248 * @since 1.28
249 */
250 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
251 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
252 }
253
254 /**
255 * Commit on all connections. Done for two reasons:
256 * 1. To commit changes to the masters.
257 * 2. To release the snapshot on all connections, master and replica DB.
258 * @param string $fname Caller name
259 * @param array $options Options map:
260 * - maxWriteDuration: abort if more than this much time was spent in write queries
261 */
262 public function commitAll( $fname = __METHOD__, array $options = [] ) {
263 $this->commitMasterChanges( $fname, $options );
264 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
265 }
266
267 /**
268 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
269 *
270 * The DBO_TRX setting will be reverted to the default in each of these methods:
271 * - commitMasterChanges()
272 * - rollbackMasterChanges()
273 * - commitAll()
274 *
275 * This allows for custom transaction rounds from any outer transaction scope.
276 *
277 * @param string $fname
278 * @throws DBTransactionError
279 * @since 1.28
280 */
281 public function beginMasterChanges( $fname = __METHOD__ ) {
282 if ( $this->trxRoundId !== false ) {
283 throw new DBTransactionError(
284 null,
285 "$fname: transaction round '{$this->trxRoundId}' already started."
286 );
287 }
288 $this->trxRoundId = $fname;
289 // Set DBO_TRX flags on all appropriate DBs
290 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
291 }
292
293 /**
294 * Commit changes on all master connections
295 * @param string $fname Caller name
296 * @param array $options Options map:
297 * - maxWriteDuration: abort if more than this much time was spent in write queries
298 * @throws Exception
299 */
300 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
301 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
302 throw new DBTransactionError(
303 null,
304 "$fname: transaction round '{$this->trxRoundId}' still running."
305 );
306 }
307 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
308 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
309 $this->trxRoundId = false;
310 // Perform pre-commit checks, aborting on failure
311 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
312 // Log the DBs and methods involved in multi-DB transactions
313 $this->logIfMultiDbTransaction();
314 // Actually perform the commit on all master DB connections and revert DBO_TRX
315 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
316 // Run all post-commit callbacks
317 /** @var Exception $e */
318 $e = null; // first callback exception
319 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$e ) {
320 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
321 $e = $e ?: $ex;
322 } );
323 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
324 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
325 // Throw any last post-commit callback error
326 if ( $e instanceof Exception ) {
327 throw $e;
328 }
329 }
330
331 /**
332 * Rollback changes on all master connections
333 * @param string $fname Caller name
334 * @since 1.23
335 */
336 public function rollbackMasterChanges( $fname = __METHOD__ ) {
337 $this->trxRoundId = false;
338 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
339 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
340 // Run all post-rollback callbacks
341 $this->forEachLB( function ( LoadBalancer $lb ) {
342 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
343 } );
344 }
345
346 /**
347 * Log query info if multi DB transactions are going to be committed now
348 */
349 private function logIfMultiDbTransaction() {
350 $callersByDB = [];
351 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$callersByDB ) {
352 $masterName = $lb->getServerName( $lb->getWriterIndex() );
353 $callers = $lb->pendingMasterChangeCallers();
354 if ( $callers ) {
355 $callersByDB[$masterName] = $callers;
356 }
357 } );
358
359 if ( count( $callersByDB ) >= 2 ) {
360 $dbs = implode( ', ', array_keys( $callersByDB ) );
361 $msg = "Multi-DB transaction [{$dbs}]:\n";
362 foreach ( $callersByDB as $db => $callers ) {
363 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
364 }
365 $this->trxLogger->info( $msg );
366 }
367 }
368
369 /**
370 * Determine if any master connection has pending changes
371 * @return bool
372 * @since 1.23
373 */
374 public function hasMasterChanges() {
375 $ret = false;
376 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
377 $ret = $ret || $lb->hasMasterChanges();
378 } );
379
380 return $ret;
381 }
382
383 /**
384 * Detemine if any lagged replica DB connection was used
385 * @return bool
386 * @since 1.28
387 */
388 public function laggedReplicaUsed() {
389 $ret = false;
390 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$ret ) {
391 $ret = $ret || $lb->laggedReplicaUsed();
392 } );
393
394 return $ret;
395 }
396
397 /**
398 * @return bool
399 * @since 1.27
400 * @deprecated Since 1.28; use laggedReplicaUsed()
401 */
402 public function laggedSlaveUsed() {
403 return $this->laggedReplicaUsed();
404 }
405
406 /**
407 * Determine if any master connection has pending/written changes from this request
408 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
409 * @return bool
410 * @since 1.27
411 */
412 public function hasOrMadeRecentMasterChanges( $age = null ) {
413 $ret = false;
414 $this->forEachLB( function ( LoadBalancer $lb ) use ( $age, &$ret ) {
415 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
416 } );
417 return $ret;
418 }
419
420 /**
421 * Waits for the replica DBs to catch up to the current master position
422 *
423 * Use this when updating very large numbers of rows, as in maintenance scripts,
424 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
425 *
426 * By default this waits on all DB clusters actually used in this request.
427 * This makes sense when lag being waiting on is caused by the code that does this check.
428 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
429 * that were not changed since the last wait check. To forcefully wait on a specific cluster
430 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
431 * use the "cluster" parameter.
432 *
433 * Never call this function after a large DB write that is *still* in a transaction.
434 * It only makes sense to call this after the possible lag inducing changes were committed.
435 *
436 * @param array $opts Optional fields that include:
437 * - wiki : wait on the load balancer DBs that handles the given wiki
438 * - cluster : wait on the given external load balancer DBs
439 * - timeout : Max wait time. Default: ~60 seconds
440 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
441 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
442 * @since 1.27
443 */
444 public function waitForReplication( array $opts = [] ) {
445 $opts += [
446 'wiki' => false,
447 'cluster' => false,
448 'timeout' => 60,
449 'ifWritesSince' => null
450 ];
451
452 // Figure out which clusters need to be checked
453 /** @var LoadBalancer[] $lbs */
454 $lbs = [];
455 if ( $opts['cluster'] !== false ) {
456 $lbs[] = $this->getExternalLB( $opts['cluster'] );
457 } elseif ( $opts['wiki'] !== false ) {
458 $lbs[] = $this->getMainLB( $opts['wiki'] );
459 } else {
460 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$lbs ) {
461 $lbs[] = $lb;
462 } );
463 if ( !$lbs ) {
464 return; // nothing actually used
465 }
466 }
467
468 // Get all the master positions of applicable DBs right now.
469 // This can be faster since waiting on one cluster reduces the
470 // time needed to wait on the next clusters.
471 $masterPositions = array_fill( 0, count( $lbs ), false );
472 foreach ( $lbs as $i => $lb ) {
473 if ( $lb->getServerCount() <= 1 ) {
474 // Bug 27975 - Don't try to wait for replica DBs if there are none
475 // Prevents permission error when getting master position
476 continue;
477 } elseif ( $opts['ifWritesSince']
478 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
479 ) {
480 continue; // no writes since the last wait
481 }
482 $masterPositions[$i] = $lb->getMasterPos();
483 }
484
485 // Run any listener callbacks *after* getting the DB positions. The more
486 // time spent in the callbacks, the less time is spent in waitForAll().
487 foreach ( $this->replicationWaitCallbacks as $callback ) {
488 $callback();
489 }
490
491 $failed = [];
492 foreach ( $lbs as $i => $lb ) {
493 if ( $masterPositions[$i] ) {
494 // The DBMS may not support getMasterPos() or the whole
495 // load balancer might be fake (e.g. $wgAllDBsAreLocalhost).
496 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
497 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
498 }
499 }
500 }
501
502 if ( $failed ) {
503 throw new DBReplicationWaitError(
504 "Could not wait for replica DBs to catch up to " .
505 implode( ', ', $failed )
506 );
507 }
508 }
509
510 /**
511 * Add a callback to be run in every call to waitForReplication() before waiting
512 *
513 * Callbacks must clear any transactions that they start
514 *
515 * @param string $name Callback name
516 * @param callable|null $callback Use null to unset a callback
517 * @since 1.28
518 */
519 public function setWaitForReplicationListener( $name, callable $callback = null ) {
520 if ( $callback ) {
521 $this->replicationWaitCallbacks[$name] = $callback;
522 } else {
523 unset( $this->replicationWaitCallbacks[$name] );
524 }
525 }
526
527 /**
528 * Get a token asserting that no transaction writes are active
529 *
530 * @param string $fname Caller name (e.g. __METHOD__)
531 * @return mixed A value to pass to commitAndWaitForReplication()
532 * @since 1.28
533 */
534 public function getEmptyTransactionTicket( $fname ) {
535 if ( $this->hasMasterChanges() ) {
536 $this->trxLogger->error( __METHOD__ . ": $fname does not have outer scope." );
537 return null;
538 }
539
540 return $this->ticket;
541 }
542
543 /**
544 * Convenience method for safely running commitMasterChanges()/waitForReplication()
545 *
546 * This will commit and wait unless $ticket indicates it is unsafe to do so
547 *
548 * @param string $fname Caller name (e.g. __METHOD__)
549 * @param mixed $ticket Result of getEmptyTransactionTicket()
550 * @param array $opts Options to waitForReplication()
551 * @throws DBReplicationWaitError
552 * @since 1.28
553 */
554 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
555 if ( $ticket !== $this->ticket ) {
556 $logger = LoggerFactory::getInstance( 'DBPerformance' );
557 $logger->error( __METHOD__ . ": cannot commit; $fname does not have outer scope." );
558 return;
559 }
560
561 // The transaction owner and any caller with the empty transaction ticket can commit
562 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
563 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
564 $this->trxLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
565 $fnameEffective = $this->trxRoundId;
566 } else {
567 $fnameEffective = $fname;
568 }
569
570 $this->commitMasterChanges( $fnameEffective );
571 $this->waitForReplication( $opts );
572 // If a nested caller committed on behalf of $fname, start another empty $fname
573 // transaction, leaving the caller with the same empty transaction state as before.
574 if ( $fnameEffective !== $fname ) {
575 $this->beginMasterChanges( $fnameEffective );
576 }
577 }
578
579 /**
580 * @param string $dbName DB master name (e.g. "db1052")
581 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
582 * @since 1.28
583 */
584 public function getChronologyProtectorTouched( $dbName ) {
585 return $this->chronProt->getTouched( $dbName );
586 }
587
588 /**
589 * Disable the ChronologyProtector for all load balancers
590 *
591 * This can be called at the start of special API entry points
592 *
593 * @since 1.27
594 */
595 public function disableChronologyProtection() {
596 $this->chronProt->setEnabled( false );
597 }
598
599 /**
600 * @return ChronologyProtector
601 */
602 protected function newChronologyProtector() {
603 $request = RequestContext::getMain()->getRequest();
604 $chronProt = new ChronologyProtector(
605 ObjectCache::getMainStashInstance(),
606 [
607 'ip' => $request->getIP(),
608 'agent' => $request->getHeader( 'User-Agent' ),
609 ],
610 $request->getFloat( 'cpPosTime', $request->getCookie( 'cpPosTime', '' ) )
611 );
612 $chronProt->setLogger( $this->replLogger );
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 'hostname' => wfHostname()
674 ];
675 }
676
677 /**
678 * @param LoadBalancer $lb
679 */
680 protected function initLoadBalancer( LoadBalancer $lb ) {
681 if ( $this->trxRoundId !== false ) {
682 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
683 }
684 }
685
686 /**
687 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
688 *
689 * Note that unlike cookies, this works accross domains
690 *
691 * @param string $url
692 * @param float $time UNIX timestamp just before shutdown() was called
693 * @return string
694 * @since 1.28
695 */
696 public function appendPreShutdownTimeAsQuery( $url, $time ) {
697 $usedCluster = 0;
698 $this->forEachLB( function ( LoadBalancer $lb ) use ( &$usedCluster ) {
699 $usedCluster |= ( $lb->getServerCount() > 1 );
700 } );
701
702 if ( !$usedCluster ) {
703 return $url; // no master/replica clusters touched
704 }
705
706 return wfAppendQuery( $url, [ 'cpPosTime' => $time ] );
707 }
708
709 /**
710 * Close all open database connections on all open load balancers.
711 * @since 1.28
712 */
713 public function closeAll() {
714 $this->forEachLBCallMethod( 'closeAll', [] );
715 }
716 }