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