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