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