d75ba931ee96f930f3c978dee1def1b027ab2d68
[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 use Psr\Log\LoggerInterface;
25
26 /**
27 * An interface for generating database load balancers
28 * @ingroup Database
29 */
30 abstract class LBFactory {
31 /** @var ChronologyProtector */
32 protected $chronProt;
33 /** @var object|string Class name or object With profileIn/profileOut methods */
34 protected $profiler;
35 /** @var TransactionProfiler */
36 protected $trxProfiler;
37 /** @var LoggerInterface */
38 protected $replLogger;
39 /** @var LoggerInterface */
40 protected $connLogger;
41 /** @var LoggerInterface */
42 protected $queryLogger;
43 /** @var LoggerInterface */
44 protected $perfLogger;
45 /** @var callable Error logger */
46 protected $errorLogger;
47 /** @var BagOStuff */
48 protected $srvCache;
49 /** @var BagOStuff */
50 protected $memCache;
51 /** @var WANObjectCache */
52 protected $wanCache;
53
54 /** @var DatabaseDomain Local domain */
55 protected $localDomain;
56 /** @var string Local hostname of the app server */
57 protected $hostname;
58 /** @var array Web request information about the client */
59 protected $requestInfo;
60
61 /** @var mixed */
62 protected $ticket;
63 /** @var string|bool String if a requested DBO_TRX transaction round is active */
64 protected $trxRoundId = false;
65 /** @var string|bool Reason all LBs are read-only or false if not */
66 protected $readOnlyReason = false;
67 /** @var callable[] */
68 protected $replicationWaitCallbacks = [];
69
70 /** @var bool Whether this PHP instance is for a CLI script */
71 protected $cliMode;
72 /** @var string Agent name for query profiling */
73 protected $agent;
74
75 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
76 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
77 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
78
79 private static $loggerFields =
80 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
81
82 /**
83 * Construct a manager of ILoadBalancer objects
84 *
85 * Sub-classes will extend the required keys in $conf with additional parameters
86 *
87 * @param $conf $params Array with keys:
88 * - localDomain: A DatabaseDomain or domain ID string.
89 * - readOnlyReason : Reason the master DB is read-only if so [optional]
90 * - srvCache : BagOStuff object for server cache [optional]
91 * - memCache : BagOStuff object for cluster memory cache [optional]
92 * - wanCache : WANObjectCache object [optional]
93 * - hostname : The name of the current server [optional]
94 * - cliMode: Whether the execution context is a CLI script. [optional]
95 * - profiler : Class name or instance with profileIn()/profileOut() methods. [optional]
96 * - trxProfiler: TransactionProfiler instance. [optional]
97 * - replLogger: PSR-3 logger instance. [optional]
98 * - connLogger: PSR-3 logger instance. [optional]
99 * - queryLogger: PSR-3 logger instance. [optional]
100 * - perfLogger: PSR-3 logger instance. [optional]
101 * - errorLogger : Callback that takes an Exception and logs it. [optional]
102 * @throws InvalidArgumentException
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->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : 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( E_WARNING, get_class( $e ) . ': ' . $e->getMessage() );
126 };
127
128 $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null;
129 $this->trxProfiler = isset( $conf['trxProfiler'] )
130 ? $conf['trxProfiler']
131 : new TransactionProfiler();
132
133 $this->requestInfo = [
134 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
135 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
136 'ChronologyProtection' => 'true'
137 ];
138
139 $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
140 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
141 $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
142
143 $this->ticket = mt_rand();
144 }
145
146 /**
147 * Disables all load balancers. All connections are closed, and any attempt to
148 * open a new connection will result in a DBAccessError.
149 * @see ILoadBalancer::disable()
150 */
151 public function destroy() {
152 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
153 $this->forEachLBCallMethod( 'disable' );
154 }
155
156 /**
157 * Create a new load balancer object. The resulting object will be untracked,
158 * not chronology-protected, and the caller is responsible for cleaning it up.
159 *
160 * @param bool|string $domain Domain ID, or false for the current domain
161 * @return ILoadBalancer
162 */
163 abstract public function newMainLB( $domain = false );
164
165 /**
166 * Get a cached (tracked) load balancer object.
167 *
168 * @param bool|string $domain Domain ID, or false for the current domain
169 * @return ILoadBalancer
170 */
171 abstract public function getMainLB( $domain = false );
172
173 /**
174 * Create a new load balancer for external storage. The resulting object will be
175 * untracked, not chronology-protected, and the caller is responsible for
176 * cleaning it up.
177 *
178 * @param string $cluster External storage cluster, or false for core
179 * @param bool|string $domain Domain ID, or false for the current domain
180 * @return ILoadBalancer
181 */
182 abstract protected function newExternalLB( $cluster, $domain = false );
183
184 /**
185 * Get a cached (tracked) load balancer for external storage
186 *
187 * @param string $cluster External storage cluster, or false for core
188 * @param bool|string $domain Domain ID, or false for the current domain
189 * @return ILoadBalancer
190 */
191 abstract public function getExternalLB( $cluster, $domain = false );
192
193 /**
194 * Execute a function for each tracked load balancer
195 * The callback is called with the load balancer as the first parameter,
196 * and $params passed as the subsequent parameters.
197 *
198 * @param callable $callback
199 * @param array $params
200 */
201 abstract public function forEachLB( $callback, array $params = [] );
202
203 /**
204 * Prepare all tracked load balancers for shutdown
205 * @param integer $mode One of the class SHUTDOWN_* constants
206 * @param callable|null $workCallback Work to mask ChronologyProtector writes
207 */
208 public function shutdown(
209 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
210 ) {
211 $chronProt = $this->getChronologyProtector();
212 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
213 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
214 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
215 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
216 }
217
218 $this->commitMasterChanges( __METHOD__ ); // sanity
219 }
220
221 /**
222 * Call a method of each tracked load balancer
223 *
224 * @param string $methodName
225 * @param array $args
226 */
227 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
228 $this->forEachLB(
229 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
230 call_user_func_array( [ $loadBalancer, $methodName ], $args );
231 },
232 [ $methodName, $args ]
233 );
234 }
235
236 /**
237 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
238 *
239 * @param string $fname Caller name
240 * @since 1.28
241 */
242 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
243 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
244 }
245
246 /**
247 * Commit on all connections. Done for two reasons:
248 * 1. To commit changes to the masters.
249 * 2. To release the snapshot on all connections, master and replica DB.
250 * @param string $fname Caller name
251 * @param array $options Options map:
252 * - maxWriteDuration: abort if more than this much time was spent in write queries
253 */
254 public function commitAll( $fname = __METHOD__, array $options = [] ) {
255 $this->commitMasterChanges( $fname, $options );
256 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
257 }
258
259 /**
260 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
261 *
262 * The DBO_TRX setting will be reverted to the default in each of these methods:
263 * - commitMasterChanges()
264 * - rollbackMasterChanges()
265 * - commitAll()
266 *
267 * This allows for custom transaction rounds from any outer transaction scope.
268 *
269 * @param string $fname
270 * @throws DBTransactionError
271 * @since 1.28
272 */
273 public function beginMasterChanges( $fname = __METHOD__ ) {
274 if ( $this->trxRoundId !== false ) {
275 throw new DBTransactionError(
276 null,
277 "$fname: transaction round '{$this->trxRoundId}' already started."
278 );
279 }
280 $this->trxRoundId = $fname;
281 // Set DBO_TRX flags on all appropriate DBs
282 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
283 }
284
285 /**
286 * Commit changes on all master connections
287 * @param string $fname Caller name
288 * @param array $options Options map:
289 * - maxWriteDuration: abort if more than this much time was spent in write queries
290 * @throws Exception
291 */
292 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
293 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
294 throw new DBTransactionError(
295 null,
296 "$fname: transaction round '{$this->trxRoundId}' still running."
297 );
298 }
299 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
300 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
301 $this->trxRoundId = false;
302 // Perform pre-commit checks, aborting on failure
303 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
304 // Log the DBs and methods involved in multi-DB transactions
305 $this->logIfMultiDbTransaction();
306 // Actually perform the commit on all master DB connections and revert DBO_TRX
307 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
308 // Run all post-commit callbacks
309 /** @var Exception $e */
310 $e = null; // first callback exception
311 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
312 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
313 $e = $e ?: $ex;
314 } );
315 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
316 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
317 // Throw any last post-commit callback error
318 if ( $e instanceof Exception ) {
319 throw $e;
320 }
321 }
322
323 /**
324 * Rollback changes on all master connections
325 * @param string $fname Caller name
326 * @since 1.23
327 */
328 public function rollbackMasterChanges( $fname = __METHOD__ ) {
329 $this->trxRoundId = false;
330 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
331 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
332 // Run all post-rollback callbacks
333 $this->forEachLB( function ( ILoadBalancer $lb ) {
334 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
335 } );
336 }
337
338 /**
339 * Log query info if multi DB transactions are going to be committed now
340 */
341 private function logIfMultiDbTransaction() {
342 $callersByDB = [];
343 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
344 $masterName = $lb->getServerName( $lb->getWriterIndex() );
345 $callers = $lb->pendingMasterChangeCallers();
346 if ( $callers ) {
347 $callersByDB[$masterName] = $callers;
348 }
349 } );
350
351 if ( count( $callersByDB ) >= 2 ) {
352 $dbs = implode( ', ', array_keys( $callersByDB ) );
353 $msg = "Multi-DB transaction [{$dbs}]:\n";
354 foreach ( $callersByDB as $db => $callers ) {
355 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
356 }
357 $this->queryLogger->info( $msg );
358 }
359 }
360
361 /**
362 * Determine if any master connection has pending changes
363 * @return bool
364 * @since 1.23
365 */
366 public function hasMasterChanges() {
367 $ret = false;
368 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
369 $ret = $ret || $lb->hasMasterChanges();
370 } );
371
372 return $ret;
373 }
374
375 /**
376 * Detemine if any lagged replica DB connection was used
377 * @return bool
378 * @since 1.28
379 */
380 public function laggedReplicaUsed() {
381 $ret = false;
382 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
383 $ret = $ret || $lb->laggedReplicaUsed();
384 } );
385
386 return $ret;
387 }
388
389 /**
390 * Determine if any master connection has pending/written changes from this request
391 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
392 * @return bool
393 * @since 1.27
394 */
395 public function hasOrMadeRecentMasterChanges( $age = null ) {
396 $ret = false;
397 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
398 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
399 } );
400 return $ret;
401 }
402
403 /**
404 * Waits for the replica DBs to catch up to the current master position
405 *
406 * Use this when updating very large numbers of rows, as in maintenance scripts,
407 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
408 *
409 * By default this waits on all DB clusters actually used in this request.
410 * This makes sense when lag being waiting on is caused by the code that does this check.
411 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
412 * that were not changed since the last wait check. To forcefully wait on a specific cluster
413 * for a given domain, use the 'domain' parameter. To forcefully wait on an "external" cluster,
414 * use the "cluster" parameter.
415 *
416 * Never call this function after a large DB write that is *still* in a transaction.
417 * It only makes sense to call this after the possible lag inducing changes were committed.
418 *
419 * @param array $opts Optional fields that include:
420 * - domain : wait on the load balancer DBs that handles the given domain ID
421 * - cluster : wait on the given external load balancer DBs
422 * - timeout : Max wait time. Default: ~60 seconds
423 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
424 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
425 * @since 1.27
426 */
427 public function waitForReplication( array $opts = [] ) {
428 $opts += [
429 'domain' => false,
430 'cluster' => false,
431 'timeout' => 60,
432 'ifWritesSince' => null
433 ];
434
435 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
436 $opts['domain'] = $opts['wiki']; // b/c
437 }
438
439 // Figure out which clusters need to be checked
440 /** @var ILoadBalancer[] $lbs */
441 $lbs = [];
442 if ( $opts['cluster'] !== false ) {
443 $lbs[] = $this->getExternalLB( $opts['cluster'] );
444 } elseif ( $opts['domain'] !== false ) {
445 $lbs[] = $this->getMainLB( $opts['domain'] );
446 } else {
447 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
448 $lbs[] = $lb;
449 } );
450 if ( !$lbs ) {
451 return; // nothing actually used
452 }
453 }
454
455 // Get all the master positions of applicable DBs right now.
456 // This can be faster since waiting on one cluster reduces the
457 // time needed to wait on the next clusters.
458 $masterPositions = array_fill( 0, count( $lbs ), false );
459 foreach ( $lbs as $i => $lb ) {
460 if ( $lb->getServerCount() <= 1 ) {
461 // Bug 27975 - Don't try to wait for replica DBs if there are none
462 // Prevents permission error when getting master position
463 continue;
464 } elseif ( $opts['ifWritesSince']
465 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
466 ) {
467 continue; // no writes since the last wait
468 }
469 $masterPositions[$i] = $lb->getMasterPos();
470 }
471
472 // Run any listener callbacks *after* getting the DB positions. The more
473 // time spent in the callbacks, the less time is spent in waitForAll().
474 foreach ( $this->replicationWaitCallbacks as $callback ) {
475 $callback();
476 }
477
478 $failed = [];
479 foreach ( $lbs as $i => $lb ) {
480 if ( $masterPositions[$i] ) {
481 // The DBMS may not support getMasterPos()
482 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
483 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
484 }
485 }
486 }
487
488 if ( $failed ) {
489 throw new DBReplicationWaitError(
490 "Could not wait for replica DBs to catch up to " .
491 implode( ', ', $failed )
492 );
493 }
494 }
495
496 /**
497 * Add a callback to be run in every call to waitForReplication() before waiting
498 *
499 * Callbacks must clear any transactions that they start
500 *
501 * @param string $name Callback name
502 * @param callable|null $callback Use null to unset a callback
503 * @since 1.28
504 */
505 public function setWaitForReplicationListener( $name, callable $callback = null ) {
506 if ( $callback ) {
507 $this->replicationWaitCallbacks[$name] = $callback;
508 } else {
509 unset( $this->replicationWaitCallbacks[$name] );
510 }
511 }
512
513 /**
514 * Get a token asserting that no transaction writes are active
515 *
516 * @param string $fname Caller name (e.g. __METHOD__)
517 * @return mixed A value to pass to commitAndWaitForReplication()
518 * @since 1.28
519 */
520 public function getEmptyTransactionTicket( $fname ) {
521 if ( $this->hasMasterChanges() ) {
522 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope." );
523 return null;
524 }
525
526 return $this->ticket;
527 }
528
529 /**
530 * Convenience method for safely running commitMasterChanges()/waitForReplication()
531 *
532 * This will commit and wait unless $ticket indicates it is unsafe to do so
533 *
534 * @param string $fname Caller name (e.g. __METHOD__)
535 * @param mixed $ticket Result of getEmptyTransactionTicket()
536 * @param array $opts Options to waitForReplication()
537 * @throws DBReplicationWaitError
538 * @since 1.28
539 */
540 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
541 if ( $ticket !== $this->ticket ) {
542 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope." );
543 return;
544 }
545
546 // The transaction owner and any caller with the empty transaction ticket can commit
547 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
548 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
549 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
550 $fnameEffective = $this->trxRoundId;
551 } else {
552 $fnameEffective = $fname;
553 }
554
555 $this->commitMasterChanges( $fnameEffective );
556 $this->waitForReplication( $opts );
557 // If a nested caller committed on behalf of $fname, start another empty $fname
558 // transaction, leaving the caller with the same empty transaction state as before.
559 if ( $fnameEffective !== $fname ) {
560 $this->beginMasterChanges( $fnameEffective );
561 }
562 }
563
564 /**
565 * @param string $dbName DB master name (e.g. "db1052")
566 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
567 * @since 1.28
568 */
569 public function getChronologyProtectorTouched( $dbName ) {
570 return $this->getChronologyProtector()->getTouched( $dbName );
571 }
572
573 /**
574 * Disable the ChronologyProtector for all load balancers
575 *
576 * This can be called at the start of special API entry points
577 *
578 * @since 1.27
579 */
580 public function disableChronologyProtection() {
581 $this->getChronologyProtector()->setEnabled( false );
582 }
583
584 /**
585 * @return ChronologyProtector
586 */
587 protected function getChronologyProtector() {
588 if ( $this->chronProt ) {
589 return $this->chronProt;
590 }
591
592 $this->chronProt = new ChronologyProtector(
593 $this->memCache,
594 [
595 'ip' => $this->requestInfo['IPAddress'],
596 'agent' => $this->requestInfo['UserAgent'],
597 ],
598 isset( $_GET['cpPosTime'] ) ? $_GET['cpPosTime'] : null
599 );
600 $this->chronProt->setLogger( $this->replLogger );
601
602 if ( $this->cliMode ) {
603 $this->chronProt->setEnabled( false );
604 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
605 // Request opted out of using position wait logic. This is useful for requests
606 // done by the job queue or background ETL that do not have a meaningful session.
607 $this->chronProt->setWaitEnabled( false );
608 }
609
610 $this->replLogger->debug( __METHOD__ . ': using request info ' .
611 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
612
613 return $this->chronProt;
614 }
615
616 /**
617 * Get and record all of the staged DB positions into persistent memory storage
618 *
619 * @param ChronologyProtector $cp
620 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
621 * @param string $mode One of (sync, async); whether to wait on remote datacenters
622 */
623 protected function shutdownChronologyProtector(
624 ChronologyProtector $cp, $workCallback, $mode
625 ) {
626 // Record all the master positions needed
627 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
628 $cp->shutdownLB( $lb );
629 } );
630 // Write them to the persistent stash. Try to do something useful by running $work
631 // while ChronologyProtector waits for the stash write to replicate to all DCs.
632 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
633 if ( $unsavedPositions && $workCallback ) {
634 // Invoke callback in case it did not cache the result yet
635 $workCallback(); // work now to block for less time in waitForAll()
636 }
637 // If the positions failed to write to the stash, at least wait on local datacenter
638 // replica DBs to catch up before responding. Even if there are several DCs, this increases
639 // the chance that the user will see their own changes immediately afterwards. As long
640 // as the sticky DC cookie applies (same domain), this is not even an issue.
641 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
642 $masterName = $lb->getServerName( $lb->getWriterIndex() );
643 if ( isset( $unsavedPositions[$masterName] ) ) {
644 $lb->waitForAll( $unsavedPositions[$masterName] );
645 }
646 } );
647 }
648
649 /**
650 * Base parameters to LoadBalancer::__construct()
651 * @return array
652 */
653 final protected function baseLoadBalancerParams() {
654 return [
655 'localDomain' => $this->localDomain,
656 'readOnlyReason' => $this->readOnlyReason,
657 'srvCache' => $this->srvCache,
658 'wanCache' => $this->wanCache,
659 'profiler' => $this->profiler,
660 'trxProfiler' => $this->trxProfiler,
661 'queryLogger' => $this->queryLogger,
662 'connLogger' => $this->connLogger,
663 'replLogger' => $this->replLogger,
664 'errorLogger' => $this->errorLogger,
665 'hostname' => $this->hostname,
666 'cliMode' => $this->cliMode,
667 'agent' => $this->agent
668 ];
669 }
670
671 /**
672 * @param ILoadBalancer $lb
673 */
674 protected function initLoadBalancer( ILoadBalancer $lb ) {
675 if ( $this->trxRoundId !== false ) {
676 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
677 }
678 }
679
680 /**
681 * Set a new table prefix for the existing local domain ID for testing
682 *
683 * @param string $prefix
684 * @since 1.28
685 */
686 public function setDomainPrefix( $prefix ) {
687 $this->localDomain = new DatabaseDomain(
688 $this->localDomain->getDatabase(),
689 null,
690 $prefix
691 );
692
693 $this->forEachLB( function( ILoadBalancer $lb ) use ( $prefix ) {
694 $lb->setDomainPrefix( $prefix );
695 } );
696 }
697
698 /**
699 * Close all open database connections on all open load balancers.
700 * @since 1.28
701 */
702 public function closeAll() {
703 $this->forEachLBCallMethod( 'closeAll', [] );
704 }
705
706 /**
707 * @param string $agent Agent name for query profiling
708 * @since 1.28
709 */
710 public function setAgentName( $agent ) {
711 $this->agent = $agent;
712 }
713
714 /**
715 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
716 *
717 * Note that unlike cookies, this works accross domains
718 *
719 * @param string $url
720 * @param float $time UNIX timestamp just before shutdown() was called
721 * @return string
722 * @since 1.28
723 */
724 public function appendPreShutdownTimeAsQuery( $url, $time ) {
725 $usedCluster = 0;
726 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
727 $usedCluster |= ( $lb->getServerCount() > 1 );
728 } );
729
730 if ( !$usedCluster ) {
731 return $url; // no master/replica clusters touched
732 }
733
734 return strpos( $url, '?' ) === false ? "$url?cpPosTime=$time" : "$url&cpPosTime=$time";
735 }
736
737 /**
738 * @param array $info Map of fields, including:
739 * - IPAddress : IP address
740 * - UserAgent : User-Agent HTTP header
741 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
742 * @since 1.28
743 */
744 public function setRequestInfo( array $info ) {
745 $this->requestInfo = $info + $this->requestInfo;
746 }
747
748 function __destruct() {
749 $this->destroy();
750 }
751 }