rdbms: add IDatabase::lockForUpdate() convenience method
[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 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
139 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
140 ];
141
142 $this->cliMode = $conf['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
143 $this->hostname = $conf['hostname'] ?? gethostname();
144 $this->agent = $conf['agent'] ?? '';
145 $this->defaultGroup = $conf['defaultGroup'] ?? null;
146
147 $this->ticket = mt_rand();
148 }
149
150 public function destroy() {
151 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
152 $this->forEachLBCallMethod( 'disable' );
153 }
154
155 public function shutdown(
156 $mode = self::SHUTDOWN_CHRONPROT_SYNC,
157 callable $workCallback = null,
158 &$cpIndex = null,
159 &$cpClientId = null
160 ) {
161 $chronProt = $this->getChronologyProtector();
162 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
163 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
164 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
165 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
166 }
167
168 $cpClientId = $chronProt->getClientId();
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 $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 'clientId' => $this->requestInfo['ChronologyClientId']
502 ],
503 $this->requestInfo['ChronologyPositionIndex']
504 );
505 $this->chronProt->setLogger( $this->replLogger );
506
507 if ( $this->cliMode ) {
508 $this->chronProt->setEnabled( false );
509 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
510 // Request opted out of using position wait logic. This is useful for requests
511 // done by the job queue or background ETL that do not have a meaningful session.
512 $this->chronProt->setWaitEnabled( false );
513 } elseif ( $this->memStash instanceof EmptyBagOStuff ) {
514 // No where to store any DB positions and wait for them to appear
515 $this->chronProt->setEnabled( false );
516 $this->replLogger->info( 'Cannot use ChronologyProtector with EmptyBagOStuff.' );
517 }
518
519 $this->replLogger->debug( __METHOD__ . ': using request info ' .
520 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
521
522 return $this->chronProt;
523 }
524
525 /**
526 * Get and record all of the staged DB positions into persistent memory storage
527 *
528 * @param ChronologyProtector $cp
529 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
530 * @param string $mode One of (sync, async); whether to wait on remote datacenters
531 * @param int|null &$cpIndex DB position key write counter; incremented on update
532 */
533 protected function shutdownChronologyProtector(
534 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
535 ) {
536 // Record all the master positions needed
537 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
538 $cp->shutdownLB( $lb );
539 } );
540 // Write them to the persistent stash. Try to do something useful by running $work
541 // while ChronologyProtector waits for the stash write to replicate to all DCs.
542 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
543 if ( $unsavedPositions && $workCallback ) {
544 // Invoke callback in case it did not cache the result yet
545 $workCallback(); // work now to block for less time in waitForAll()
546 }
547 // If the positions failed to write to the stash, at least wait on local datacenter
548 // replica DBs to catch up before responding. Even if there are several DCs, this increases
549 // the chance that the user will see their own changes immediately afterwards. As long
550 // as the sticky DC cookie applies (same domain), this is not even an issue.
551 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
552 $masterName = $lb->getServerName( $lb->getWriterIndex() );
553 if ( isset( $unsavedPositions[$masterName] ) ) {
554 $lb->waitForAll( $unsavedPositions[$masterName] );
555 }
556 } );
557 }
558
559 /**
560 * Base parameters to ILoadBalancer::__construct()
561 * @return array
562 */
563 final protected function baseLoadBalancerParams() {
564 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
565 $initStage = ILoadBalancer::STAGE_POSTCOMMIT_CALLBACKS;
566 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
567 $initStage = ILoadBalancer::STAGE_POSTROLLBACK_CALLBACKS;
568 } else {
569 $initStage = null;
570 }
571
572 return [
573 'localDomain' => $this->localDomain,
574 'readOnlyReason' => $this->readOnlyReason,
575 'srvCache' => $this->srvCache,
576 'wanCache' => $this->wanCache,
577 'profiler' => $this->profiler,
578 'trxProfiler' => $this->trxProfiler,
579 'queryLogger' => $this->queryLogger,
580 'connLogger' => $this->connLogger,
581 'replLogger' => $this->replLogger,
582 'errorLogger' => $this->errorLogger,
583 'deprecationLogger' => $this->deprecationLogger,
584 'hostname' => $this->hostname,
585 'cliMode' => $this->cliMode,
586 'agent' => $this->agent,
587 'defaultGroup' => $this->defaultGroup,
588 'chronologyCallback' => function ( ILoadBalancer $lb ) {
589 // Defer ChronologyProtector construction in case setRequestInfo() ends up
590 // being called later (but before the first connection attempt) (T192611)
591 $this->getChronologyProtector()->initLB( $lb );
592 },
593 'roundStage' => $initStage
594 ];
595 }
596
597 /**
598 * @param ILoadBalancer $lb
599 */
600 protected function initLoadBalancer( ILoadBalancer $lb ) {
601 if ( $this->trxRoundId !== false ) {
602 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
603 }
604
605 $lb->setTableAliases( $this->tableAliases );
606 $lb->setIndexAliases( $this->indexAliases );
607 }
608
609 public function setTableAliases( array $aliases ) {
610 $this->tableAliases = $aliases;
611 }
612
613 public function setIndexAliases( array $aliases ) {
614 $this->indexAliases = $aliases;
615 }
616
617 public function setDomainPrefix( $prefix ) {
618 $this->localDomain = new DatabaseDomain(
619 $this->localDomain->getDatabase(),
620 null,
621 $prefix
622 );
623
624 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
625 $lb->setDomainPrefix( $prefix );
626 } );
627 }
628
629 public function closeAll() {
630 $this->forEachLBCallMethod( 'closeAll', [] );
631 }
632
633 public function setAgentName( $agent ) {
634 $this->agent = $agent;
635 }
636
637 public function appendShutdownCPIndexAsQuery( $url, $index ) {
638 $usedCluster = 0;
639 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
640 $usedCluster |= ( $lb->getServerCount() > 1 );
641 } );
642
643 if ( !$usedCluster ) {
644 return $url; // no master/replica clusters touched
645 }
646
647 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
648 }
649
650 /**
651 * @param int $index Write index
652 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
653 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
654 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
655 * @since 1.32
656 */
657 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
658 return "$index@$time#$clientId";
659 }
660
661 /**
662 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
663 * @param int $minTimestamp Lowest UNIX timestamp that a non-expired value can have
664 * @return array (index: int or null, clientId: string or null)
665 * @since 1.32
666 */
667 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
668 static $placeholder = [ 'index' => null, 'clientId' => null ];
669
670 if ( !preg_match( '/^(\d+)@(\d+)#([0-9a-f]{32})$/', $value, $m ) ) {
671 return $placeholder; // invalid
672 }
673
674 $index = (int)$m[1];
675 if ( $index <= 0 ) {
676 return $placeholder; // invalid
677 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
678 return $placeholder; // expired
679 }
680
681 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ? $m[3] : null;
682
683 return [ 'index' => $index, 'clientId' => $clientId ];
684 }
685
686 public function setRequestInfo( array $info ) {
687 if ( $this->chronProt ) {
688 throw new LogicException( 'ChronologyProtector already initialized.' );
689 }
690
691 $this->requestInfo = $info + $this->requestInfo;
692 }
693
694 /**
695 * @param string $stage
696 */
697 private function assertTransactionRoundStage( $stage ) {
698 if ( $this->trxRoundStage !== $stage ) {
699 throw new DBTransactionError(
700 null,
701 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
702 );
703 }
704 }
705
706 /**
707 * Make PHP ignore user aborts/disconnects until the returned
708 * value leaves scope. This returns null and does nothing in CLI mode.
709 *
710 * @return ScopedCallback|null
711 */
712 final protected function getScopedPHPBehaviorForCommit() {
713 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
714 $old = ignore_user_abort( true ); // avoid half-finished operations
715 return new ScopedCallback( function () use ( $old ) {
716 ignore_user_abort( $old );
717 } );
718 }
719
720 return null;
721 }
722
723 function __destruct() {
724 $this->destroy();
725 }
726 }
727
728 /**
729 * @deprecated since 1.29
730 */
731 class_alias( LBFactory::class, 'LBFactory' );