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