MediaWiki REL1_39
JobRunner.php
Go to the documentation of this file.
1<?php
24use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
29use Psr\Log\LoggerAwareInterface;
30use Psr\Log\LoggerInterface;
35use Wikimedia\ScopedCallback;
36
43class JobRunner implements LoggerAwareInterface {
44
48 public const CONSTRUCTOR_OPTIONS = [
49 MainConfigNames::JobBackoffThrottling,
50 MainConfigNames::JobClasses,
51 MainConfigNames::JobSerialCommitThreshold,
52 MainConfigNames::MaxJobDBWriteDuration,
53 MainConfigNames::TrxProfilerLimits,
54 ];
55
57 private $options;
58
60 private $lbFactory;
61
63 private $jobQueueGroup;
64
66 private $readOnlyMode;
67
69 private $linkCache;
70
72 private $stats;
73
75 private $debug;
76
78 private $logger;
79
81 private const MAX_ALLOWED_LAG = 3;
83 private const SYNC_TIMEOUT = self::MAX_ALLOWED_LAG;
85 private const LAG_CHECK_PERIOD = 1.0;
87 private const ERROR_BACKOFF_TTL = 1;
89 private const READONLY_BACKOFF_TTL = 30;
90
94 public function setDebugHandler( $debug ) {
95 $this->debug = $debug;
96 }
97
103 public function setLogger( LoggerInterface $logger ) {
104 wfDeprecated( __METHOD__, '1.35' );
105 $this->logger = $logger;
106 }
107
119 public function __construct(
120 $serviceOptions = null,
121 ILBFactory $lbFactory = null,
122 JobQueueGroup $jobQueueGroup = null,
123 ReadOnlyMode $readOnlyMode = null,
124 LinkCache $linkCache = null,
125 StatsdDataFactoryInterface $statsdDataFactory = null,
126 LoggerInterface $logger = null
127 ) {
128 if ( !$serviceOptions || $serviceOptions instanceof LoggerInterface ) {
129 wfDeprecated( __METHOD__ . ' called directly. Use MediaWikiServices instead', '1.39' );
130 $logger = $serviceOptions;
131 $serviceOptions = new ServiceOptions(
132 static::CONSTRUCTOR_OPTIONS,
133 MediaWikiServices::getInstance()->getMainConfig()
134 );
135 }
136
137 $this->options = $serviceOptions;
138 $this->lbFactory = $lbFactory ?? MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
139 $this->jobQueueGroup = $jobQueueGroup ?? MediaWikiServices::getInstance()->getJobQueueGroup();
140 $this->readOnlyMode = $readOnlyMode ?: MediaWikiServices::getInstance()->getReadOnlyMode();
141 $this->linkCache = $linkCache ?? MediaWikiServices::getInstance()->getLinkCache();
142 $this->stats = $statsdDataFactory ?? MediaWikiServices::getInstance()->getStatsdDataFactory();
143 $this->logger = $logger ?? LoggerFactory::getInstance( 'runJobs' );
144 }
145
171 public function run( array $options ) {
172 $type = $options['type'] ?? false;
173 $maxJobs = $options['maxJobs'] ?? false;
174 $maxTime = $options['maxTime'] ?? false;
175 $throttle = $options['throttle'] ?? true;
176
177 $jobClasses = $this->options->get( MainConfigNames::JobClasses );
178 $profilerLimits = $this->options->get( MainConfigNames::TrxProfilerLimits );
179
180 $response = [ 'jobs' => [], 'reached' => 'none-ready' ];
181
182 if ( $type !== false && !isset( $jobClasses[$type] ) ) {
183 // Invalid job type specified
184 $response['reached'] = 'none-possible';
185 return $response;
186 }
187
188 if ( $this->readOnlyMode->isReadOnly() ) {
189 // Any jobs popped off the queue might fail to run and thus might end up lost
190 $response['reached'] = 'read-only';
191 return $response;
192 }
193
194 list( , $maxLag ) = $this->lbFactory->getMainLB()->getMaxLag();
195 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
196 // DB lag is already too high; caller can immediately try other wikis if applicable
197 $response['reached'] = 'replica-lag-limit';
198 return $response;
199 }
200
201 // Narrow DB query expectations for this HTTP request
202 $this->lbFactory->getTransactionProfiler()
203 ->setExpectations( $profilerLimits['JobRunner'], __METHOD__ );
204
205 // Error out if an explicit DB transaction round is somehow active
206 if ( $this->lbFactory->hasTransactionRound() ) {
207 throw new LogicException( __METHOD__ . ' called with an active transaction round.' );
208 }
209
210 // Some jobs types should not run until a certain timestamp
211 $backoffs = []; // map of (type => UNIX expiry)
212 $backoffDeltas = []; // map of (type => seconds)
213 $wait = 'wait'; // block to read backoffs the first time
214
215 $loopStartTime = microtime( true );
216 $jobsPopped = 0;
217 $timeMsTotal = 0;
218 $lastSyncTime = 1; // initialize "last sync check timestamp" to "ages ago"
219 // Keep popping and running jobs until there are no more...
220 do {
221 // Sync the persistent backoffs with concurrent runners
222 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
223 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
224 $wait = 'nowait'; // less important now
225
226 if ( $type === false ) {
227 // Treat the default job type queues as a single queue and pop off a job
228 $job = $this->jobQueueGroup
229 ->pop( JobQueueGroup::TYPE_DEFAULT, JobQueueGroup::USE_CACHE, $backoffKeys );
230 } else {
231 // Pop off a job from the specified job type queue unless the execution of
232 // that type of job is currently rate-limited by the back-off list
233 $job = in_array( $type, $backoffKeys ) ? false : $this->jobQueueGroup->pop( $type );
234 }
235
236 if ( $job ) {
237 ++$jobsPopped;
238 $jType = $job->getType();
239
240 // Back off of certain jobs for a while (for throttling and for errors)
241 $ttw = $this->getBackoffTimeToWait( $job );
242 if ( $ttw > 0 ) {
243 // Always add the delta for other runners in case the time running the
244 // job negated the backoff for each individually but not collectively.
245 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
246 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
247 }
248
249 $info = $this->executeJob( $job );
250
251 // Mark completed or "one shot only" jobs as resolved
252 if ( $info['status'] !== false || !$job->allowRetries() ) {
253 $this->jobQueueGroup->ack( $job );
254 }
255
256 // Back off of certain jobs for a while (for throttling and for errors)
257 if ( $info['status'] === false && mt_rand( 0, 49 ) == 0 ) {
258 $ttw = max( $ttw, $this->getErrorBackoffTTL( $info['caught'] ) );
259 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
260 }
261
262 $response['jobs'][] = [
263 'type' => $jType,
264 'status' => ( $info['status'] === false ) ? 'failed' : 'ok',
265 'error' => $info['error'],
266 'time' => $info['timeMs']
267 ];
268 $timeMsTotal += $info['timeMs'];
269
270 // Break out if we hit the job count or wall time limits
271 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
272 $response['reached'] = 'job-limit';
273 break;
274 } elseif ( $maxTime && ( microtime( true ) - $loopStartTime ) > $maxTime ) {
275 $response['reached'] = 'time-limit';
276 break;
277 }
278
279 // Stop if we caught a DBConnectionError. In theory it would be
280 // possible to explicitly reconnect, but the present behaviour
281 // is to just throw more exceptions every time something database-
282 // related is attempted.
283 if ( in_array( DBConnectionError::class, $info['caught'], true ) ) {
284 $response['reached'] = 'exception';
285 break;
286 }
287
288 // Don't let any of the main DB replica DBs get backed up.
289 // This only waits for so long before exiting and letting
290 // other wikis in the farm (on different masters) get a chance.
291 $timePassed = microtime( true ) - $lastSyncTime;
292 if ( $timePassed >= self::LAG_CHECK_PERIOD || $timePassed < 0 ) {
293 $opts = [ 'ifWritesSince' => $lastSyncTime, 'timeout' => self::SYNC_TIMEOUT ];
294 if ( !$this->lbFactory->waitForReplication( $opts ) ) {
295 $response['reached'] = 'replica-lag-limit';
296 break;
297 }
298 $lastSyncTime = microtime( true );
299 }
300
301 // Abort if nearing OOM to avoid erroring out in the middle of a job
302 if ( !$this->checkMemoryOK() ) {
303 $response['reached'] = 'memory-limit';
304 break;
305 }
306 }
307 } while ( $job );
308
309 // Sync the persistent backoffs for the next runJobs.php pass
310 if ( $backoffDeltas ) {
311 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
312 }
313
314 $response['backoffs'] = $backoffs;
315 $response['elapsed'] = $timeMsTotal;
316
317 return $response;
318 }
319
338 public function executeJob( RunnableJob $job ) {
339 $oldRequestId = WebRequest::getRequestId();
340 // Temporarily inherit the original ID of the web request that spawned this job
341 WebRequest::overrideRequestId( $job->getRequestId() );
342 // Use an appropriate timeout to balance lag avoidance and job progress
343 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
344 try {
345 return $this->doExecuteJob( $job );
346 } finally {
347 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
348 WebRequest::overrideRequestId( $oldRequestId );
349 }
350 }
351
360 private function doExecuteJob( RunnableJob $job ) {
361 $jType = $job->getType();
362 $msg = $job->toString() . " STARTING";
363 $this->logger->debug( $msg, [ 'job_type' => $job->getType() ] );
364 $this->debugCallback( $msg );
365
366 // Clear out title cache data from prior snapshots
367 // (e.g. from before JobRunner was invoked in this process)
368 $this->linkCache->clear();
369
370 // Run the job...
371 $caught = [];
372 $rssStart = $this->getMaxRssKb();
373 $jobStartTime = microtime( true );
374 try {
375 $fnameTrxOwner = get_class( $job ) . '::run'; // give run() outer scope
376 // Flush any pending changes left over from an implicit transaction round
377 if ( $job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
378 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner ); // new implicit round
379 } else {
380 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner ); // new explicit round
381 }
382 // Clear any stale REPEATABLE-READ snapshots from replica DB connections
383 $this->lbFactory->flushReplicaSnapshots( $fnameTrxOwner );
384 $status = $job->run();
385 $error = $job->getLastError();
386 // Commit all pending changes from this job
387 $this->commitPrimaryChanges( $job, $fnameTrxOwner );
388 // Run any deferred update tasks; doUpdates() manages transactions itself
390 } catch ( Throwable $e ) {
392 $status = false;
393 $error = get_class( $e ) . ': ' . $e->getMessage();
394 $caught[] = get_class( $e );
395 }
396 // Always attempt to call teardown(), even if Job throws exception
397 try {
398 $job->tearDown( $status );
399 } catch ( Throwable $e ) {
401 }
402
403 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
404 $rssEnd = $this->getMaxRssKb();
405
406 // Record how long jobs wait before getting popped
407 $readyTs = $job->getReadyTimestamp();
408 if ( $readyTs ) {
409 $pickupDelay = max( 0, $jobStartTime - $readyTs );
410 $this->stats->timing( 'jobqueue.pickup_delay.all', 1000 * $pickupDelay );
411 $this->stats->timing( "jobqueue.pickup_delay.$jType", 1000 * $pickupDelay );
412 }
413 // Record root job age for jobs being run
414 $rootTimestamp = $job->getRootJobParams()['rootJobTimestamp'];
415 if ( $rootTimestamp ) {
416 $age = max( 0, $jobStartTime - (int)wfTimestamp( TS_UNIX, $rootTimestamp ) );
417 $this->stats->timing( "jobqueue.pickup_root_age.$jType", 1000 * $age );
418 }
419 // Track the execution time for jobs
420 $this->stats->timing( "jobqueue.run.$jType", $timeMs );
421 // Track RSS increases for jobs (in case of memory leaks)
422 if ( $rssStart && $rssEnd ) {
423 $this->stats->updateCount( "jobqueue.rss_delta.$jType", $rssEnd - $rssStart );
424 }
425
426 if ( $status === false ) {
427 $msg = $job->toString() . " t={job_duration} error={job_error}";
428 $this->logger->error( $msg, [
429 'job_type' => $job->getType(),
430 'job_duration' => $timeMs,
431 'job_error' => $error,
432 ] );
433
434 $msg = $job->toString() . " t=$timeMs error={$error}";
435 $this->debugCallback( $msg );
436 } else {
437 $msg = $job->toString() . " t={job_duration} good";
438 $this->logger->info( $msg, [
439 'job_type' => $job->getType(),
440 'job_duration' => $timeMs,
441 ] );
442
443 $msg = $job->toString() . " t=$timeMs good";
444 $this->debugCallback( $msg );
445 }
446
447 return [
448 'status' => $status,
449 'error' => $error,
450 'caught' => $caught,
451 'timeMs' => $timeMs
452 ];
453 }
454
459 private function getErrorBackoffTTL( array $caught ) {
460 return in_array( DBReadOnlyError::class, $caught )
461 ? self::READONLY_BACKOFF_TTL
462 : self::ERROR_BACKOFF_TTL;
463 }
464
468 private function getMaxRssKb() {
469 $info = getrusage( 0 /* RUSAGE_SELF */ );
470 // see https://linux.die.net/man/2/getrusage
471 return isset( $info['ru_maxrss'] ) ? (int)$info['ru_maxrss'] : null;
472 }
473
479 private function getBackoffTimeToWait( RunnableJob $job ) {
480 $throttling = $this->options->get( MainConfigNames::JobBackoffThrottling );
481
482 if ( !isset( $throttling[$job->getType()] ) || $job instanceof DuplicateJob ) {
483 return 0; // not throttled
484 }
485
486 $itemsPerSecond = $throttling[$job->getType()];
487 if ( $itemsPerSecond <= 0 ) {
488 return 0; // not throttled
489 }
490
491 $seconds = 0;
492 if ( $job->workItemCount() > 0 ) {
493 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
494 // use randomized rounding
495 $seconds = floor( $exactSeconds );
496 $remainder = $exactSeconds - $seconds;
497 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
498 }
499
500 return (int)$seconds;
501 }
502
511 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
512 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
513 if ( is_file( $file ) ) {
514 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
515 $handle = fopen( $file, 'rb' );
516 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
517 fclose( $handle );
518 return $backoffs; // don't wait on lock
519 }
520 $content = stream_get_contents( $handle );
521 flock( $handle, LOCK_UN );
522 fclose( $handle );
523 $ctime = microtime( true );
524 $cBackoffs = json_decode( $content, true ) ?: [];
525 foreach ( $cBackoffs as $type => $timestamp ) {
526 if ( $timestamp < $ctime ) {
527 unset( $cBackoffs[$type] );
528 }
529 }
530 } else {
531 $cBackoffs = [];
532 }
533
534 return $cBackoffs;
535 }
536
548 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
549 if ( !$deltas ) {
550 return $this->loadBackoffs( $backoffs, $mode );
551 }
552
553 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
554 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
555 $handle = fopen( $file, 'wb+' );
556 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
557 fclose( $handle );
558 return $backoffs; // don't wait on lock
559 }
560 $ctime = microtime( true );
561 $content = stream_get_contents( $handle );
562 $cBackoffs = json_decode( $content, true ) ?: [];
563 foreach ( $deltas as $type => $seconds ) {
564 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
565 ? $cBackoffs[$type] + $seconds
566 : $ctime + $seconds;
567 }
568 foreach ( $cBackoffs as $type => $timestamp ) {
569 if ( $timestamp < $ctime ) {
570 unset( $cBackoffs[$type] );
571 }
572 }
573 ftruncate( $handle, 0 );
574 fwrite( $handle, json_encode( $cBackoffs ) );
575 flock( $handle, LOCK_UN );
576 fclose( $handle );
577
578 $deltas = [];
579
580 return $cBackoffs;
581 }
582
588 private function checkMemoryOK() {
589 static $maxBytes = null;
590 if ( $maxBytes === null ) {
591 $m = [];
592 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
593 list( , $num, $unit ) = $m;
594 $conv = [ 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 ];
595 $maxBytes = (int)$num * $conv[strtolower( $unit )];
596 } else {
597 $maxBytes = 0;
598 }
599 }
600 $usedBytes = memory_get_usage();
601 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
602 $msg = "Detected excessive memory usage ({used_bytes}/{max_bytes}).";
603 $this->logger->error( $msg, [
604 'used_bytes' => $usedBytes,
605 'max_bytes' => $maxBytes,
606 ] );
607
608 $msg = "Detected excessive memory usage ($usedBytes/$maxBytes).";
609 $this->debugCallback( $msg );
610
611 return false;
612 }
613
614 return true;
615 }
616
621 private function debugCallback( $msg ) {
622 if ( $this->debug ) {
623 call_user_func_array( $this->debug, [ wfTimestamp( TS_DB ) . " $msg\n" ] );
624 }
625 }
626
637 private function commitPrimaryChanges( RunnableJob $job, $fnameTrxOwner ) {
638 $syncThreshold = $this->options->get( MainConfigNames::JobSerialCommitThreshold );
639
640 $time = false;
641 $lb = $this->lbFactory->getMainLB();
642 if ( $syncThreshold !== false && $lb->hasStreamingReplicaServers() ) {
643 // Generally, there is one primary connection to the local DB
644 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
645 // We need natively blocking fast locks
646 if ( $dbwSerial && $dbwSerial->namedLocksEnqueue() ) {
647 $time = $dbwSerial->pendingWriteQueryDuration( $dbwSerial::ESTIMATE_DB_APPLY );
648 if ( $time < $syncThreshold ) {
649 $dbwSerial = false;
650 }
651 } else {
652 $dbwSerial = false;
653 }
654 } else {
655 // There are no replica DBs or writes are all to foreign DB (we don't handle that)
656 $dbwSerial = false;
657 }
658
659 if ( !$dbwSerial ) {
660 $this->lbFactory->commitPrimaryChanges(
661 $fnameTrxOwner,
662 // Abort if any transaction was too big
663 [ 'maxWriteDuration' =>
664 $this->options->get( MainConfigNames::MaxJobDBWriteDuration ) ]
665 );
666
667 return;
668 }
669
670 $ms = intval( 1000 * $time );
671
672 $msg = $job->toString() . " COMMIT ENQUEUED [{job_commit_write_ms}ms of writes]";
673 $this->logger->info( $msg, [
674 'job_type' => $job->getType(),
675 'job_commit_write_ms' => $ms,
676 ] );
677
678 $msg = $job->toString() . " COMMIT ENQUEUED [{$ms}ms of writes]";
679 $this->debugCallback( $msg );
680
681 // Wait for an exclusive lock to commit
682 if ( !$dbwSerial->lock( 'jobrunner-serial-commit', $fnameTrxOwner, 30 ) ) {
683 // This will trigger a rollback in the main loop
684 throw new DBError( $dbwSerial, "Timed out waiting on commit queue." );
685 }
686 $unlocker = new ScopedCallback( static function () use ( $dbwSerial, $fnameTrxOwner ) {
687 $dbwSerial->unlock( 'jobrunner-serial-commit', $fnameTrxOwner );
688 } );
689
690 // Wait for the replica DBs to catch up
691 $pos = $lb->getPrimaryPos();
692 if ( $pos ) {
693 $lb->waitForAll( $pos );
694 }
695
696 // Actually commit the DB primary changes
697 $this->lbFactory->commitPrimaryChanges(
698 $fnameTrxOwner,
699 // Abort if any transaction was too big
700 [ 'maxWriteDuration' => $this->options->get( MainConfigNames::MaxJobDBWriteDuration ) ]
701 );
702 ScopedCallback::consume( $unlocker );
703 }
704}
wfTempDir()
Tries to get the system directory for temporary files.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
static doUpdates( $unused=null, $stage=self::ALL)
Consume and execute all pending updates.
No-op job that does nothing.
Class to handle enqueueing of background jobs.
Job queue runner utility methods.
Definition JobRunner.php:43
setDebugHandler( $debug)
Definition JobRunner.php:94
run(array $options)
Run jobs of the specified number/type for the specified time.
const CONSTRUCTOR_OPTIONS
Definition JobRunner.php:48
setLogger(LoggerInterface $logger)
executeJob(RunnableJob $job)
Run a specific job in a manner appropriate for mass use by job dispatchers.
__construct( $serviceOptions=null, ILBFactory $lbFactory=null, JobQueueGroup $jobQueueGroup=null, ReadOnlyMode $readOnlyMode=null, LinkCache $linkCache=null, StatsdDataFactoryInterface $statsdDataFactory=null, LoggerInterface $logger=null)
Calling this directly is deprecated.
Cache for article titles (prefixed DB keys) and ids linked from one source.
Definition LinkCache.php:42
static rollbackPrimaryChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
A class for passing options to services.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
A service class for fetching the wiki's current read-only mode.
Database error base class.
Definition DBError.php:31
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
Manager of ILoadBalancer objects, and indirectly of IDatabase connections.
$debug
Definition mcc.php:31
if(count( $args)< 1) $job
$content
Definition router.php:76
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42