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