MediaWiki master
JobRunner.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\JobQueue;
8
9use LogicException;
20use Psr\Log\LoggerInterface;
21use Throwable;
26use Wikimedia\ScopedCallback;
28use Wikimedia\Timestamp\ConvertibleTimestamp;
29use Wikimedia\Timestamp\TimestampFormat as TS;
30
37class JobRunner {
38
42 public const CONSTRUCTOR_OPTIONS = [
47 ];
48
50 private $options;
51
53 private $lbFactory;
54
56 private $jobQueueGroup;
57
59 private $readOnlyMode;
60
62 private $linkCache;
63
64 private PageProps $pageProps;
65
67 private $statsFactory;
68
70 private $debug;
71
73 private $logger;
74
76 private const MAX_ALLOWED_LAG = 3;
78 private const SYNC_TIMEOUT = self::MAX_ALLOWED_LAG;
80 private const LAG_CHECK_PERIOD = 1.0;
82 private const ERROR_BACKOFF_TTL = 1;
84 private const READONLY_BACKOFF_TTL = 30;
85
89 public function setDebugHandler( $debug ) {
90 $this->debug = $debug;
91 }
92
104 public function __construct(
105 ServiceOptions $serviceOptions,
106 ILBFactory $lbFactory,
107 JobQueueGroup $jobQueueGroup,
108 ReadOnlyMode $readOnlyMode,
109 LinkCache $linkCache,
110 PageProps $pageProps,
111 StatsFactory $statsFactory,
112 LoggerInterface $logger
113 ) {
114 $serviceOptions->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
115 $this->options = $serviceOptions;
116 $this->lbFactory = $lbFactory;
117 $this->jobQueueGroup = $jobQueueGroup;
118 $this->readOnlyMode = $readOnlyMode;
119 $this->linkCache = $linkCache;
120 $this->pageProps = $pageProps;
121 $this->statsFactory = $statsFactory;
122 $this->logger = $logger;
123 }
124
151 public function run( array $options ) {
152 $type = $options['type'] ?? false;
153 $maxJobs = $options['maxJobs'] ?? false;
154 $maxTime = $options['maxTime'] ?? false;
155 $throttle = $options['throttle'] ?? true;
156
157 $jobClasses = $this->options->get( MainConfigNames::JobClasses );
158 $profilerLimits = $this->options->get( MainConfigNames::TrxProfilerLimits );
159
160 $response = [ 'jobs' => [], 'reached' => 'none-ready' ];
161
162 if ( $type !== false && !isset( $jobClasses[$type] ) ) {
163 // Invalid job type specified
164 $response['reached'] = 'none-possible';
165 return $response;
166 }
167
168 if ( $this->readOnlyMode->isReadOnly() ) {
169 // Any jobs popped off the queue might fail to run and thus might end up lost
170 $response['reached'] = 'read-only';
171 return $response;
172 }
173
174 [ , $maxLag ] = $this->lbFactory->getMainLB()->getMaxLag();
175 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
176 // DB lag is already too high; caller can immediately try other wikis if applicable
177 $response['reached'] = 'replica-lag-limit';
178 return $response;
179 }
180
181 // Narrow DB query expectations for this HTTP request
182 $this->lbFactory->getTransactionProfiler()
183 ->setExpectations( $profilerLimits['JobRunner'], __METHOD__ );
184
185 // Error out if an explicit DB transaction round is somehow active
186 if ( $this->lbFactory->hasTransactionRound() ) {
187 throw new LogicException( __METHOD__ . ' called with an active transaction round.' );
188 }
189
190 // Some jobs types should not run until a certain timestamp
191 $backoffs = []; // map of (type => UNIX expiry)
192 $backoffDeltas = []; // map of (type => seconds)
193 $wait = 'wait'; // block to read backoffs the first time
194
195 $loopStartTime = microtime( true );
196 $jobsPopped = 0;
197 $timeMsTotal = 0;
198 $lastSyncTime = 1; // initialize "last sync check timestamp" to "ages ago"
199 // Keep popping and running jobs until there are no more...
200 do {
201 // Sync the persistent backoffs with concurrent runners
202 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
203 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
204 $wait = 'nowait'; // less important now
205
206 if ( $type === false ) {
207 // Treat the default job type queues as a single queue and pop off a job
208 $job = $this->jobQueueGroup
210 } else {
211 // Pop off a job from the specified job type queue unless the execution of
212 // that type of job is currently rate-limited by the back-off list
213 $job = in_array( $type, $backoffKeys ) ? false : $this->jobQueueGroup->pop( $type );
214 }
215
216 if ( $job ) {
217 ++$jobsPopped;
218 $jType = $job->getType();
219
220 // Back off of certain jobs for a while (for throttling and for errors)
221 $ttw = $this->getBackoffTimeToWait( $job );
222 if ( $ttw > 0 ) {
223 // Always add the delta for other runners in case the time running the
224 // job negated the backoff for each individually but not collectively.
225 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
226 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
227 }
228
229 $info = $this->executeJob( $job );
230
231 // Mark completed or "one shot only" jobs as resolved
232 if ( $info['status'] !== false || !$job->allowRetries() ) {
233 $this->jobQueueGroup->ack( $job );
234 }
235
236 // Back off of certain jobs for a while (for throttling and for errors)
237 if ( $info['status'] === false && mt_rand( 0, 49 ) == 0 ) {
238 $ttw = max( $ttw, $this->getErrorBackoffTTL( $info['caught'] ) );
239 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
240 }
241
242 $response['jobs'][] = [
243 'type' => $jType,
244 'status' => ( $info['status'] === false ) ? 'failed' : 'ok',
245 'error' => $info['error'],
246 'time' => $info['timeMs']
247 ];
248 $timeMsTotal += $info['timeMs'];
249
250 // Break out if we hit the job count or wall time limits
251 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
252 $response['reached'] = 'job-limit';
253 break;
254 } elseif ( $maxTime && ( microtime( true ) - $loopStartTime ) > $maxTime ) {
255 $response['reached'] = 'time-limit';
256 break;
257 }
258
259 // Stop if we caught a DBConnectionError. In theory it would be
260 // possible to explicitly reconnect, but the present behaviour
261 // is to just throw more exceptions every time something database-
262 // related is attempted.
263 if ( in_array( DBConnectionError::class, $info['caught'], true ) ) {
264 $response['reached'] = 'exception';
265 break;
266 }
267
268 // Don't let any of the main DB replica DBs get backed up.
269 // This only waits for so long before exiting and letting
270 // other wikis in the farm (on different masters) get a chance.
271 $timePassed = microtime( true ) - $lastSyncTime;
272 if ( $timePassed >= self::LAG_CHECK_PERIOD || $timePassed < 0 ) {
273 $opts = [ 'ifWritesSince' => $lastSyncTime, 'timeout' => self::SYNC_TIMEOUT ];
274 if ( !$this->lbFactory->waitForReplication( $opts ) ) {
275 $response['reached'] = 'replica-lag-limit';
276 break;
277 }
278 $lastSyncTime = microtime( true );
279 }
280
281 // Abort if nearing OOM to avoid erroring out in the middle of a job
282 if ( !$this->checkMemoryOK() ) {
283 $response['reached'] = 'memory-limit';
284 break;
285 }
286 }
287 } while ( $job );
288
289 // Sync the persistent backoffs for the next runJobs.php pass
290 if ( $backoffDeltas ) {
291 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
292 }
293
294 $response['backoffs'] = $backoffs;
295 $response['elapsed'] = $timeMsTotal;
296
297 return $response;
298 }
299
318 public function executeJob( RunnableJob $job ) {
319 $telemetry = Telemetry::getInstance();
320 $oldRequestId = $telemetry->getRequestId();
321
322 if ( $job->getRequestId() !== null ) {
323 // Temporarily inherit the original ID of the web request that spawned this job
324 $telemetry->overrideRequestId( $job->getRequestId() );
325 } else {
326 // TODO: do we need to regenerate if job doesn't have the request id?
327 // If JobRunner was called with X-Request-ID header, regeneration will generate the
328 // same value
329 $telemetry->regenerateRequestId();
330 }
331 // Use an appropriate timeout to balance lag avoidance and job progress
332 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
333 try {
334 return $this->doExecuteJob( $job );
335 } finally {
336 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
337 $telemetry->overrideRequestId( $oldRequestId );
338 }
339 }
340
349 private function doExecuteJob( RunnableJob $job ) {
350 $jType = $job->getType();
351 $msg = $job->toString() . " STARTING";
352 $this->logger->debug( $msg, [ 'job_type' => $job->getType() ] );
353 $this->debugCallback( $msg );
354
355 // Clear out title cache data from prior snapshots
356 // (e.g. from before JobRunner was invoked in this process)
357 $this->linkCache->clear();
358 $this->pageProps->clear();
359
360 // Run the job...
361 $caught = [];
362 $rssStart = $this->getMaxRssKb();
363 $jobStartTime = microtime( true );
364 try {
365 $fnameTrxOwner = get_class( $job ) . '::run'; // give run() outer scope
366 // Flush any pending changes left over from an implicit transaction round
367 if ( $job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
368 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner ); // new implicit round
369 } else {
370 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner ); // new explicit round
371 }
372 // Clear any stale REPEATABLE-READ snapshots from replica DB connections
373
374 $scope = LoggerFactory::getContext()->addScoped( [
375 'context.job_type' => $jType,
376 ] );
377 $status = $job->run();
378 $error = $job->getLastError();
379 ScopedCallback::consume( $scope );
380
381 // Commit all pending changes from this job
382 $this->lbFactory->commitPrimaryChanges(
383 $fnameTrxOwner,
384 // Abort if any transaction was too big
385 $this->options->get( MainConfigNames::MaxJobDBWriteDuration )
386 );
387 // Run any deferred update tasks; doUpdates() manages transactions itself
388 DeferredUpdates::doUpdates();
389 } catch ( Throwable $e ) {
390 MWExceptionHandler::rollbackPrimaryChangesAndLog( $e );
391 $status = false;
392 $error = get_class( $e ) . ': ' . $e->getMessage() . ' in '
393 . $e->getFile() . ' on line ' . $e->getLine();
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 ) {
400 MWExceptionHandler::logException( $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->statsFactory->getTiming( 'jobqueue_pickup_delay_seconds' )
411 ->setLabel( 'jobtype', $jType )
412 ->observe( 1000 * $pickupDelay );
413 }
414 // Record root job age for jobs being run
415 $rootTimestamp = $job->getRootJobParams()['rootJobTimestamp'];
416 if ( $rootTimestamp ) {
417 $age = max( 0, $jobStartTime - (int)wfTimestamp( TS::UNIX, $rootTimestamp ) );
418
419 $this->statsFactory->getTiming( "jobqueue_pickup_root_age_seconds" )
420 ->setLabel( 'jobtype', $jType )
421 ->observe( 1000 * $age );
422 }
423 // Track the execution time for jobs
424 $this->statsFactory->getTiming( 'jobqueue_runtime_seconds' )
425 ->setLabel( 'jobtype', $jType )
426 ->observe( $timeMs );
427 // Track RSS increases for jobs (in case of memory leaks)
428 if ( $rssStart && $rssEnd ) {
429 $this->statsFactory->getCounter( 'jobqueue_rss_delta_total' )
430 ->setLabel( 'rss_delta', $jType )
431 ->incrementBy( max( $rssEnd - $rssStart, 0 ) );
432 }
433
434 if ( $status === false ) {
435 $msg = $job->toString() . " t={job_duration} error={job_error}";
436 $this->logger->error( $msg, [
437 'job_type' => $job->getType(),
438 'job_duration' => $timeMs,
439 'job_error' => $error,
440 ] );
441
442 $msg = $job->toString() . " t=$timeMs error={$error}";
443 $this->debugCallback( $msg );
444 } else {
445 $msg = $job->toString() . " t={job_duration} good";
446 $this->logger->info( $msg, [
447 'job_type' => $job->getType(),
448 'job_duration' => $timeMs,
449 ] );
450
451 $msg = $job->toString() . " t=$timeMs good";
452 $this->debugCallback( $msg );
453 }
454
455 return [
456 'status' => $status,
457 'error' => $error,
458 'caught' => $caught,
459 'timeMs' => $timeMs
460 ];
461 }
462
467 private function getErrorBackoffTTL( array $caught ) {
468 return in_array( DBReadOnlyError::class, $caught )
469 ? self::READONLY_BACKOFF_TTL
470 : self::ERROR_BACKOFF_TTL;
471 }
472
476 private function getMaxRssKb() {
477 $info = getrusage( 0 /* RUSAGE_SELF */ );
478 // see https://linux.die.net/man/2/getrusage
479 return isset( $info['ru_maxrss'] ) ? (int)$info['ru_maxrss'] : null;
480 }
481
487 private function getBackoffTimeToWait( RunnableJob $job ) {
488 $throttling = $this->options->get( MainConfigNames::JobBackoffThrottling );
489
490 if ( !isset( $throttling[$job->getType()] ) || $job instanceof DuplicateJob ) {
491 return 0; // not throttled
492 }
493
494 $itemsPerSecond = $throttling[$job->getType()];
495 if ( $itemsPerSecond <= 0 ) {
496 return 0; // not throttled
497 }
498
499 $seconds = 0;
500 if ( $job->workItemCount() > 0 ) {
501 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
502 // use randomized rounding
503 $seconds = floor( $exactSeconds );
504 $remainder = $exactSeconds - $seconds;
505 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
506 }
507
508 return (int)$seconds;
509 }
510
519 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
520 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
521 if ( is_file( $file ) ) {
522 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
523 $handle = fopen( $file, 'rb' );
524 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
525 fclose( $handle );
526 return $backoffs; // don't wait on lock
527 }
528 $content = stream_get_contents( $handle );
529 flock( $handle, LOCK_UN );
530 fclose( $handle );
531 $ctime = microtime( true );
532 $cBackoffs = json_decode( $content, true ) ?: [];
533 foreach ( $cBackoffs as $type => $timestamp ) {
534 if ( $timestamp < $ctime ) {
535 unset( $cBackoffs[$type] );
536 }
537 }
538 } else {
539 $cBackoffs = [];
540 }
541
542 return $cBackoffs;
543 }
544
556 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
557 if ( !$deltas ) {
558 return $this->loadBackoffs( $backoffs, $mode );
559 }
560
561 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
562 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
563 $handle = fopen( $file, 'wb+' );
564 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
565 fclose( $handle );
566 return $backoffs; // don't wait on lock
567 }
568 $ctime = microtime( true );
569 $content = stream_get_contents( $handle );
570 $cBackoffs = json_decode( $content, true ) ?: [];
571 foreach ( $deltas as $type => $seconds ) {
572 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
573 ? $cBackoffs[$type] + $seconds
574 : $ctime + $seconds;
575 }
576 foreach ( $cBackoffs as $type => $timestamp ) {
577 if ( $timestamp < $ctime ) {
578 unset( $cBackoffs[$type] );
579 }
580 }
581 ftruncate( $handle, 0 );
582 fwrite( $handle, json_encode( $cBackoffs ) );
583 flock( $handle, LOCK_UN );
584 fclose( $handle );
585
586 $deltas = [];
587
588 return $cBackoffs;
589 }
590
596 private function checkMemoryOK() {
597 static $maxBytes = null;
598 if ( $maxBytes === null ) {
599 $m = [];
600 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
601 [ , $num, $unit ] = $m;
602 $conv = [ 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 ];
603 $maxBytes = (int)$num * $conv[strtolower( $unit )];
604 } else {
605 $maxBytes = 0;
606 }
607 }
608 $usedBytes = memory_get_usage();
609 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
610 $msg = "Detected excessive memory usage ({used_bytes}/{max_bytes}).";
611 $this->logger->error( $msg, [
612 'used_bytes' => $usedBytes,
613 'max_bytes' => $maxBytes,
614 ] );
615
616 $msg = "Detected excessive memory usage ($usedBytes/$maxBytes).";
617 $this->debugCallback( $msg );
618
619 return false;
620 }
621
622 return true;
623 }
624
629 private function debugCallback( $msg ) {
630 if ( $this->debug ) {
631 ( $this->debug )( ConvertibleTimestamp::now( TS::DB ) . " $msg\n" );
632 }
633 }
634}
635
637class_alias( JobRunner::class, 'JobRunner' );
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.
A class for passing options to services.
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Defer callable updates to run later in the PHP process.
Handler class for MWExceptions.
Service for handling telemetry data.
Definition Telemetry.php:15
Handle enqueueing of background jobs.
Job queue runner utility methods.
Definition JobRunner.php:37
run(array $options)
Run jobs of the specified number/type for the specified time.
executeJob(RunnableJob $job)
Run a specific job in a manner appropriate for mass use by job dispatchers.
__construct(ServiceOptions $serviceOptions, ILBFactory $lbFactory, JobQueueGroup $jobQueueGroup, ReadOnlyMode $readOnlyMode, LinkCache $linkCache, PageProps $pageProps, StatsFactory $statsFactory, LoggerInterface $logger)
No-op job that does nothing.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const TrxProfilerLimits
Name constant for the TrxProfilerLimits setting, for use with Config::get()
const JobClasses
Name constant for the JobClasses setting, for use with Config::get()
const JobBackoffThrottling
Name constant for the JobBackoffThrottling setting, for use with Config::get()
const MaxJobDBWriteDuration
Name constant for the MaxJobDBWriteDuration setting, for use with Config::get()
Page existence and metadata cache.
Definition LinkCache.php:52
Gives access to properties of a page.
Definition PageProps.php:20
Determine whether a site is currently in read-only mode.
This is the primary interface for validating metrics definitions, caching defined metrics,...
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack().
Manager of ILoadBalancer objects and, indirectly, IDatabase connections.
if(count( $args)< 1) $job