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