Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactory.php
1 <?php
2 /**
3 * Generator and manager 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 namespace Wikimedia\Rdbms;
25
26 use Psr\Log\LoggerInterface;
27 use Wikimedia\ScopedCallback;
28 use BagOStuff;
29 use EmptyBagOStuff;
30 use WANObjectCache;
31 use Exception;
32 use RuntimeException;
33 use LogicException;
34
35 /**
36 * An interface for generating database load balancers
37 * @ingroup Database
38 */
39 abstract class LBFactory implements ILBFactory {
40 /** @var ChronologyProtector */
41 protected $chronProt;
42 /** @var object|string Class name or object With profileIn/profileOut methods */
43 protected $profiler;
44 /** @var TransactionProfiler */
45 protected $trxProfiler;
46 /** @var LoggerInterface */
47 protected $replLogger;
48 /** @var LoggerInterface */
49 protected $connLogger;
50 /** @var LoggerInterface */
51 protected $queryLogger;
52 /** @var LoggerInterface */
53 protected $perfLogger;
54 /** @var callable Error logger */
55 protected $errorLogger;
56 /** @var callable Deprecation logger */
57 protected $deprecationLogger;
58 /** @var BagOStuff */
59 protected $srvCache;
60 /** @var BagOStuff */
61 protected $memStash;
62 /** @var WANObjectCache */
63 protected $wanCache;
64
65 /** @var DatabaseDomain Local domain */
66 protected $localDomain;
67 /** @var string Local hostname of the app server */
68 protected $hostname;
69 /** @var array Web request information about the client */
70 protected $requestInfo;
71
72 /** @var mixed */
73 protected $ticket;
74 /** @var string|bool String if a requested DBO_TRX transaction round is active */
75 protected $trxRoundId = false;
76 /** @var string|bool Reason all LBs are read-only or false if not */
77 protected $readOnlyReason = false;
78 /** @var callable[] */
79 protected $replicationWaitCallbacks = [];
80
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 protected $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 protected $indexAliases = [];
85
86 /** @var bool Whether this PHP instance is for a CLI script */
87 protected $cliMode;
88 /** @var string Agent name for query profiling */
89 protected $agent;
90
91 /** @var string One of the ROUND_* class constants */
92 private $trxRoundStage = self::ROUND_CURSORY;
93
94 const ROUND_CURSORY = 'cursory';
95 const ROUND_BEGINNING = 'within-begin';
96 const ROUND_COMMITTING = 'within-commit';
97 const ROUND_ROLLING_BACK = 'within-rollback';
98 const ROUND_COMMIT_CALLBACKS = 'within-commit-callbacks';
99 const ROUND_ROLLBACK_CALLBACKS = 'within-rollback-callbacks';
100
101 private static $loggerFields =
102 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
103
104 public function __construct( array $conf ) {
105 $this->localDomain = isset( $conf['localDomain'] )
106 ? DatabaseDomain::newFromId( $conf['localDomain'] )
107 : DatabaseDomain::newUnspecified();
108
109 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
110 $this->readOnlyReason = $conf['readOnlyReason'];
111 }
112
113 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
114 $this->memStash = isset( $conf['memStash'] ) ? $conf['memStash'] : new EmptyBagOStuff();
115 $this->wanCache = isset( $conf['wanCache'] )
116 ? $conf['wanCache']
117 : WANObjectCache::newEmpty();
118
119 foreach ( self::$loggerFields as $key ) {
120 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
121 }
122 $this->errorLogger = isset( $conf['errorLogger'] )
123 ? $conf['errorLogger']
124 : function ( Exception $e ) {
125 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
126 };
127 $this->deprecationLogger = isset( $conf['deprecationLogger'] )
128 ? $conf['deprecationLogger']
129 : function ( $msg ) {
130 trigger_error( $msg, E_USER_DEPRECATED );
131 };
132
133 $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null;
134 $this->trxProfiler = isset( $conf['trxProfiler'] )
135 ? $conf['trxProfiler']
136 : new TransactionProfiler();
137
138 $this->requestInfo = [
139 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
140 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
141 'ChronologyProtection' => 'true',
142 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ? $_GET['cpPosIndex'] : null
143 ];
144
145 $this->cliMode = isset( $conf['cliMode'] )
146 ? $conf['cliMode']
147 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
148 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
149 $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : '';
150
151 $this->ticket = mt_rand();
152 }
153
154 public function destroy() {
155 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
156 $this->forEachLBCallMethod( 'disable' );
157 }
158
159 public function shutdown(
160 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null, &$cpIndex = null
161 ) {
162 $chronProt = $this->getChronologyProtector();
163 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
164 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
165 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
166 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
167 }
168
169 $this->commitMasterChanges( __METHOD__ ); // sanity
170 }
171
172 /**
173 * @see ILBFactory::newMainLB()
174 * @param bool $domain
175 * @return ILoadBalancer
176 */
177 abstract public function newMainLB( $domain = false );
178
179 /**
180 * @see ILBFactory::getMainLB()
181 * @param bool $domain
182 * @return ILoadBalancer
183 */
184 abstract public function getMainLB( $domain = false );
185
186 /**
187 * @see ILBFactory::newExternalLB()
188 * @param string $cluster
189 * @return ILoadBalancer
190 */
191 abstract public function newExternalLB( $cluster );
192
193 /**
194 * @see ILBFactory::getExternalLB()
195 * @param string $cluster
196 * @return ILoadBalancer
197 */
198 abstract public function getExternalLB( $cluster );
199
200 /**
201 * Call a method of each tracked load balancer
202 *
203 * @param string $methodName
204 * @param array $args
205 */
206 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
207 $this->forEachLB(
208 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
209 call_user_func_array( [ $loadBalancer, $methodName ], $args );
210 },
211 [ $methodName, $args ]
212 );
213 }
214
215 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
216 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
217 }
218
219 final public function commitAll( $fname = __METHOD__, array $options = [] ) {
220 $this->commitMasterChanges( $fname, $options );
221 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
222 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
223 }
224
225 final public function beginMasterChanges( $fname = __METHOD__ ) {
226 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
227 $this->trxRoundStage = self::ROUND_BEGINNING;
228 if ( $this->trxRoundId !== false ) {
229 throw new DBTransactionError(
230 null,
231 "$fname: transaction round '{$this->trxRoundId}' already started."
232 );
233 }
234 $this->trxRoundId = $fname;
235 // Set DBO_TRX flags on all appropriate DBs
236 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
237 $this->trxRoundStage = self::ROUND_CURSORY;
238 }
239
240 final public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
241 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
242 $this->trxRoundStage = self::ROUND_COMMITTING;
243 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
244 throw new DBTransactionError(
245 null,
246 "$fname: transaction round '{$this->trxRoundId}' still running."
247 );
248 }
249 /** @noinspection PhpUnusedLocalVariableInspection */
250 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
251 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
252 do {
253 $count = 0; // number of callbacks executed this iteration
254 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$count ) {
255 $count += $lb->finalizeMasterChanges();
256 } );
257 } while ( $count > 0 );
258 $this->trxRoundId = false;
259 // Perform pre-commit checks, aborting on failure
260 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
261 // Log the DBs and methods involved in multi-DB transactions
262 $this->logIfMultiDbTransaction();
263 // Actually perform the commit on all master DB connections and revert DBO_TRX
264 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
265 // Run all post-commit callbacks in a separate step
266 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
267 $e = $this->executePostTransactionCallbacks();
268 $this->trxRoundStage = self::ROUND_CURSORY;
269 // Throw any last post-commit callback error
270 if ( $e instanceof Exception ) {
271 throw $e;
272 }
273 }
274
275 final public function rollbackMasterChanges( $fname = __METHOD__ ) {
276 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
277 $this->trxRoundId = false;
278 // Actually perform the rollback on all master DB connections and revert DBO_TRX
279 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
280 // Run all post-commit callbacks in a separate step
281 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
282 $this->executePostTransactionCallbacks();
283 $this->trxRoundStage = self::ROUND_CURSORY;
284 }
285
286 /**
287 * @return Exception|null
288 */
289 private function executePostTransactionCallbacks() {
290 // Run all post-commit callbacks until new ones stop getting added
291 $e = null; // first callback exception
292 do {
293 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
294 $ex = $lb->runMasterTransactionIdleCallbacks();
295 $e = $e ?: $ex;
296 } );
297 } while ( $this->hasMasterChanges() );
298 // Run all listener callbacks once
299 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
300 $ex = $lb->runMasterTransactionListenerCallbacks();
301 $e = $e ?: $ex;
302 } );
303
304 return $e;
305 }
306
307 public function hasTransactionRound() {
308 return ( $this->trxRoundId !== false );
309 }
310
311 public function isReadyForRoundOperations() {
312 return ( $this->trxRoundStage === self::ROUND_CURSORY );
313 }
314
315 /**
316 * Log query info if multi DB transactions are going to be committed now
317 */
318 private function logIfMultiDbTransaction() {
319 $callersByDB = [];
320 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
321 $masterName = $lb->getServerName( $lb->getWriterIndex() );
322 $callers = $lb->pendingMasterChangeCallers();
323 if ( $callers ) {
324 $callersByDB[$masterName] = $callers;
325 }
326 } );
327
328 if ( count( $callersByDB ) >= 2 ) {
329 $dbs = implode( ', ', array_keys( $callersByDB ) );
330 $msg = "Multi-DB transaction [{$dbs}]:\n";
331 foreach ( $callersByDB as $db => $callers ) {
332 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
333 }
334 $this->queryLogger->info( $msg );
335 }
336 }
337
338 public function hasMasterChanges() {
339 $ret = false;
340 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
341 $ret = $ret || $lb->hasMasterChanges();
342 } );
343
344 return $ret;
345 }
346
347 public function laggedReplicaUsed() {
348 $ret = false;
349 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
350 $ret = $ret || $lb->laggedReplicaUsed();
351 } );
352
353 return $ret;
354 }
355
356 public function hasOrMadeRecentMasterChanges( $age = null ) {
357 $ret = false;
358 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
359 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
360 } );
361 return $ret;
362 }
363
364 public function waitForReplication( array $opts = [] ) {
365 $opts += [
366 'domain' => false,
367 'cluster' => false,
368 'timeout' => $this->cliMode ? 60 : 10,
369 'ifWritesSince' => null
370 ];
371
372 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
373 $opts['domain'] = $opts['wiki']; // b/c
374 }
375
376 // Figure out which clusters need to be checked
377 /** @var ILoadBalancer[] $lbs */
378 $lbs = [];
379 if ( $opts['cluster'] !== false ) {
380 $lbs[] = $this->getExternalLB( $opts['cluster'] );
381 } elseif ( $opts['domain'] !== false ) {
382 $lbs[] = $this->getMainLB( $opts['domain'] );
383 } else {
384 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
385 $lbs[] = $lb;
386 } );
387 if ( !$lbs ) {
388 return; // nothing actually used
389 }
390 }
391
392 // Get all the master positions of applicable DBs right now.
393 // This can be faster since waiting on one cluster reduces the
394 // time needed to wait on the next clusters.
395 $masterPositions = array_fill( 0, count( $lbs ), false );
396 foreach ( $lbs as $i => $lb ) {
397 if ( $lb->getServerCount() <= 1 ) {
398 // T29975 - Don't try to wait for replica DBs if there are none
399 // Prevents permission error when getting master position
400 continue;
401 } elseif ( $opts['ifWritesSince']
402 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
403 ) {
404 continue; // no writes since the last wait
405 }
406 $masterPositions[$i] = $lb->getMasterPos();
407 }
408
409 // Run any listener callbacks *after* getting the DB positions. The more
410 // time spent in the callbacks, the less time is spent in waitForAll().
411 foreach ( $this->replicationWaitCallbacks as $callback ) {
412 $callback();
413 }
414
415 $failed = [];
416 foreach ( $lbs as $i => $lb ) {
417 if ( $masterPositions[$i] ) {
418 // The RDBMS may not support getMasterPos()
419 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
420 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
421 }
422 }
423 }
424
425 if ( $failed ) {
426 throw new DBReplicationWaitError(
427 null,
428 "Could not wait for replica DBs to catch up to " .
429 implode( ', ', $failed )
430 );
431 }
432 }
433
434 public function setWaitForReplicationListener( $name, callable $callback = null ) {
435 if ( $callback ) {
436 $this->replicationWaitCallbacks[$name] = $callback;
437 } else {
438 unset( $this->replicationWaitCallbacks[$name] );
439 }
440 }
441
442 public function getEmptyTransactionTicket( $fname ) {
443 if ( $this->hasMasterChanges() ) {
444 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
445 ( new RuntimeException() )->getTraceAsString() );
446
447 return null;
448 }
449
450 return $this->ticket;
451 }
452
453 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
454 if ( $ticket !== $this->ticket ) {
455 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
456 ( new RuntimeException() )->getTraceAsString() );
457
458 return;
459 }
460
461 // The transaction owner and any caller with the empty transaction ticket can commit
462 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
463 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
464 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
465 $fnameEffective = $this->trxRoundId;
466 } else {
467 $fnameEffective = $fname;
468 }
469
470 $this->commitMasterChanges( $fnameEffective );
471 $this->waitForReplication( $opts );
472 // If a nested caller committed on behalf of $fname, start another empty $fname
473 // transaction, leaving the caller with the same empty transaction state as before.
474 if ( $fnameEffective !== $fname ) {
475 $this->beginMasterChanges( $fnameEffective );
476 }
477 }
478
479 public function getChronologyProtectorTouched( $dbName ) {
480 return $this->getChronologyProtector()->getTouched( $dbName );
481 }
482
483 public function disableChronologyProtection() {
484 $this->getChronologyProtector()->setEnabled( false );
485 }
486
487 /**
488 * @return ChronologyProtector
489 */
490 protected function getChronologyProtector() {
491 if ( $this->chronProt ) {
492 return $this->chronProt;
493 }
494
495 $this->chronProt = new ChronologyProtector(
496 $this->memStash,
497 [
498 'ip' => $this->requestInfo['IPAddress'],
499 'agent' => $this->requestInfo['UserAgent'],
500 ],
501 $this->requestInfo['ChronologyPositionIndex']
502 );
503 $this->chronProt->setLogger( $this->replLogger );
504
505 if ( $this->cliMode ) {
506 $this->chronProt->setEnabled( false );
507 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
508 // Request opted out of using position wait logic. This is useful for requests
509 // done by the job queue or background ETL that do not have a meaningful session.
510 $this->chronProt->setWaitEnabled( false );
511 }
512
513 $this->replLogger->debug( __METHOD__ . ': using request info ' .
514 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
515
516 return $this->chronProt;
517 }
518
519 /**
520 * Get and record all of the staged DB positions into persistent memory storage
521 *
522 * @param ChronologyProtector $cp
523 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
524 * @param string $mode One of (sync, async); whether to wait on remote datacenters
525 * @param int|null &$cpIndex DB position key write counter; incremented on update
526 */
527 protected function shutdownChronologyProtector(
528 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
529 ) {
530 // Record all the master positions needed
531 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
532 $cp->shutdownLB( $lb );
533 } );
534 // Write them to the persistent stash. Try to do something useful by running $work
535 // while ChronologyProtector waits for the stash write to replicate to all DCs.
536 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
537 if ( $unsavedPositions && $workCallback ) {
538 // Invoke callback in case it did not cache the result yet
539 $workCallback(); // work now to block for less time in waitForAll()
540 }
541 // If the positions failed to write to the stash, at least wait on local datacenter
542 // replica DBs to catch up before responding. Even if there are several DCs, this increases
543 // the chance that the user will see their own changes immediately afterwards. As long
544 // as the sticky DC cookie applies (same domain), this is not even an issue.
545 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
546 $masterName = $lb->getServerName( $lb->getWriterIndex() );
547 if ( isset( $unsavedPositions[$masterName] ) ) {
548 $lb->waitForAll( $unsavedPositions[$masterName] );
549 }
550 } );
551 }
552
553 /**
554 * Base parameters to ILoadBalancer::__construct()
555 * @return array
556 */
557 final protected function baseLoadBalancerParams() {
558 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
559 $initStage = ILoadBalancer::STAGE_POSTCOMMIT_CALLBACKS;
560 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
561 $initStage = ILoadBalancer::STAGE_POSTROLLBACK_CALLBACKS;
562 } else {
563 $initStage = null;
564 }
565
566 return [
567 'localDomain' => $this->localDomain,
568 'readOnlyReason' => $this->readOnlyReason,
569 'srvCache' => $this->srvCache,
570 'wanCache' => $this->wanCache,
571 'profiler' => $this->profiler,
572 'trxProfiler' => $this->trxProfiler,
573 'queryLogger' => $this->queryLogger,
574 'connLogger' => $this->connLogger,
575 'replLogger' => $this->replLogger,
576 'errorLogger' => $this->errorLogger,
577 'deprecationLogger' => $this->deprecationLogger,
578 'hostname' => $this->hostname,
579 'cliMode' => $this->cliMode,
580 'agent' => $this->agent,
581 'chronologyCallback' => function ( ILoadBalancer $lb ) {
582 // Defer ChronologyProtector construction in case setRequestInfo() ends up
583 // being called later (but before the first connection attempt) (T192611)
584 $this->getChronologyProtector()->initLB( $lb );
585 },
586 'roundStage' => $initStage
587 ];
588 }
589
590 /**
591 * @param ILoadBalancer $lb
592 */
593 protected function initLoadBalancer( ILoadBalancer $lb ) {
594 if ( $this->trxRoundId !== false ) {
595 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
596 }
597
598 $lb->setTableAliases( $this->tableAliases );
599 $lb->setIndexAliases( $this->indexAliases );
600 }
601
602 public function setTableAliases( array $aliases ) {
603 $this->tableAliases = $aliases;
604 }
605
606 public function setIndexAliases( array $aliases ) {
607 $this->indexAliases = $aliases;
608 }
609
610 public function setDomainPrefix( $prefix ) {
611 $this->localDomain = new DatabaseDomain(
612 $this->localDomain->getDatabase(),
613 null,
614 $prefix
615 );
616
617 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
618 $lb->setDomainPrefix( $prefix );
619 } );
620 }
621
622 public function closeAll() {
623 $this->forEachLBCallMethod( 'closeAll', [] );
624 }
625
626 public function setAgentName( $agent ) {
627 $this->agent = $agent;
628 }
629
630 public function appendShutdownCPIndexAsQuery( $url, $index ) {
631 $usedCluster = 0;
632 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
633 $usedCluster |= ( $lb->getServerCount() > 1 );
634 } );
635
636 if ( !$usedCluster ) {
637 return $url; // no master/replica clusters touched
638 }
639
640 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
641 }
642
643 public function setRequestInfo( array $info ) {
644 if ( $this->chronProt ) {
645 throw new LogicException( 'ChronologyProtector already initialized.' );
646 }
647
648 $this->requestInfo = $info + $this->requestInfo;
649 }
650
651 /**
652 * @param string $stage
653 */
654 private function assertTransactionRoundStage( $stage ) {
655 if ( $this->trxRoundStage !== $stage ) {
656 throw new DBTransactionError(
657 null,
658 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
659 );
660 }
661 }
662
663 /**
664 * Make PHP ignore user aborts/disconnects until the returned
665 * value leaves scope. This returns null and does nothing in CLI mode.
666 *
667 * @return ScopedCallback|null
668 */
669 final protected function getScopedPHPBehaviorForCommit() {
670 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
671 $old = ignore_user_abort( true ); // avoid half-finished operations
672 return new ScopedCallback( function () use ( $old ) {
673 ignore_user_abort( $old );
674 } );
675 }
676
677 return null;
678 }
679
680 function __destruct() {
681 $this->destroy();
682 }
683 }
684
685 class_alias( LBFactory::class, 'LBFactory' );