MediaWiki master
JobRunner.php
Go to the documentation of this file.
1<?php
21use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
27use Psr\Log\LoggerInterface;
32
39class JobRunner {
40
44 public const CONSTRUCTOR_OPTIONS = [
45 MainConfigNames::JobBackoffThrottling,
46 MainConfigNames::JobClasses,
47 MainConfigNames::MaxJobDBWriteDuration,
48 MainConfigNames::TrxProfilerLimits,
49 ];
50
52 private $options;
53
55 private $lbFactory;
56
58 private $jobQueueGroup;
59
61 private $readOnlyMode;
62
64 private $linkCache;
65
67 private $stats;
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
103 public function __construct(
104 ServiceOptions $serviceOptions,
105 ILBFactory $lbFactory,
106 JobQueueGroup $jobQueueGroup,
107 ReadOnlyMode $readOnlyMode,
108 LinkCache $linkCache,
109 StatsdDataFactoryInterface $statsdDataFactory,
110 LoggerInterface $logger
111 ) {
112 $serviceOptions->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
113 $this->options = $serviceOptions;
114 $this->lbFactory = $lbFactory;
115 $this->jobQueueGroup = $jobQueueGroup;
116 $this->readOnlyMode = $readOnlyMode;
117 $this->linkCache = $linkCache;
118 $this->stats = $statsdDataFactory;
119 $this->logger = $logger;
120 }
121
147 public function run( array $options ) {
148 $type = $options['type'] ?? false;
149 $maxJobs = $options['maxJobs'] ?? false;
150 $maxTime = $options['maxTime'] ?? false;
151 $throttle = $options['throttle'] ?? true;
152
153 $jobClasses = $this->options->get( MainConfigNames::JobClasses );
154 $profilerLimits = $this->options->get( MainConfigNames::TrxProfilerLimits );
155
156 $response = [ 'jobs' => [], 'reached' => 'none-ready' ];
157
158 if ( $type !== false && !isset( $jobClasses[$type] ) ) {
159 // Invalid job type specified
160 $response['reached'] = 'none-possible';
161 return $response;
162 }
163
164 if ( $this->readOnlyMode->isReadOnly() ) {
165 // Any jobs popped off the queue might fail to run and thus might end up lost
166 $response['reached'] = 'read-only';
167 return $response;
168 }
169
170 [ , $maxLag ] = $this->lbFactory->getMainLB()->getMaxLag();
171 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
172 // DB lag is already too high; caller can immediately try other wikis if applicable
173 $response['reached'] = 'replica-lag-limit';
174 return $response;
175 }
176
177 // Narrow DB query expectations for this HTTP request
178 $this->lbFactory->getTransactionProfiler()
179 ->setExpectations( $profilerLimits['JobRunner'], __METHOD__ );
180
181 // Error out if an explicit DB transaction round is somehow active
182 if ( $this->lbFactory->hasTransactionRound() ) {
183 throw new LogicException( __METHOD__ . ' called with an active transaction round.' );
184 }
185
186 // Some jobs types should not run until a certain timestamp
187 $backoffs = []; // map of (type => UNIX expiry)
188 $backoffDeltas = []; // map of (type => seconds)
189 $wait = 'wait'; // block to read backoffs the first time
190
191 $loopStartTime = microtime( true );
192 $jobsPopped = 0;
193 $timeMsTotal = 0;
194 $lastSyncTime = 1; // initialize "last sync check timestamp" to "ages ago"
195 // Keep popping and running jobs until there are no more...
196 do {
197 // Sync the persistent backoffs with concurrent runners
198 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
199 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
200 $wait = 'nowait'; // less important now
201
202 if ( $type === false ) {
203 // Treat the default job type queues as a single queue and pop off a job
204 $job = $this->jobQueueGroup
205 ->pop( JobQueueGroup::TYPE_DEFAULT, JobQueueGroup::USE_CACHE, $backoffKeys );
206 } else {
207 // Pop off a job from the specified job type queue unless the execution of
208 // that type of job is currently rate-limited by the back-off list
209 $job = in_array( $type, $backoffKeys ) ? false : $this->jobQueueGroup->pop( $type );
210 }
211
212 if ( $job ) {
213 ++$jobsPopped;
214 $jType = $job->getType();
215
216 // Back off of certain jobs for a while (for throttling and for errors)
217 $ttw = $this->getBackoffTimeToWait( $job );
218 if ( $ttw > 0 ) {
219 // Always add the delta for other runners in case the time running the
220 // job negated the backoff for each individually but not collectively.
221 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
222 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
223 }
224
225 $info = $this->executeJob( $job );
226
227 // Mark completed or "one shot only" jobs as resolved
228 if ( $info['status'] !== false || !$job->allowRetries() ) {
229 $this->jobQueueGroup->ack( $job );
230 }
231
232 // Back off of certain jobs for a while (for throttling and for errors)
233 if ( $info['status'] === false && mt_rand( 0, 49 ) == 0 ) {
234 $ttw = max( $ttw, $this->getErrorBackoffTTL( $info['caught'] ) );
235 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
236 }
237
238 $response['jobs'][] = [
239 'type' => $jType,
240 'status' => ( $info['status'] === false ) ? 'failed' : 'ok',
241 'error' => $info['error'],
242 'time' => $info['timeMs']
243 ];
244 $timeMsTotal += $info['timeMs'];
245
246 // Break out if we hit the job count or wall time limits
247 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
248 $response['reached'] = 'job-limit';
249 break;
250 } elseif ( $maxTime && ( microtime( true ) - $loopStartTime ) > $maxTime ) {
251 $response['reached'] = 'time-limit';
252 break;
253 }
254
255 // Stop if we caught a DBConnectionError. In theory it would be
256 // possible to explicitly reconnect, but the present behaviour
257 // is to just throw more exceptions every time something database-
258 // related is attempted.
259 if ( in_array( DBConnectionError::class, $info['caught'], true ) ) {
260 $response['reached'] = 'exception';
261 break;
262 }
263
264 // Don't let any of the main DB replica DBs get backed up.
265 // This only waits for so long before exiting and letting
266 // other wikis in the farm (on different masters) get a chance.
267 $timePassed = microtime( true ) - $lastSyncTime;
268 if ( $timePassed >= self::LAG_CHECK_PERIOD || $timePassed < 0 ) {
269 $opts = [ 'ifWritesSince' => $lastSyncTime, 'timeout' => self::SYNC_TIMEOUT ];
270 if ( !$this->lbFactory->waitForReplication( $opts ) ) {
271 $response['reached'] = 'replica-lag-limit';
272 break;
273 }
274 $lastSyncTime = microtime( true );
275 }
276
277 // Abort if nearing OOM to avoid erroring out in the middle of a job
278 if ( !$this->checkMemoryOK() ) {
279 $response['reached'] = 'memory-limit';
280 break;
281 }
282 }
283 } while ( $job );
284
285 // Sync the persistent backoffs for the next runJobs.php pass
286 if ( $backoffDeltas ) {
287 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
288 }
289
290 $response['backoffs'] = $backoffs;
291 $response['elapsed'] = $timeMsTotal;
292
293 return $response;
294 }
295
314 public function executeJob( RunnableJob $job ) {
315 $telemetry = Telemetry::getInstance();
316 $oldRequestId = $telemetry->getRequestId();
317
318 if ( $job->getRequestId() !== null ) {
319 // Temporarily inherit the original ID of the web request that spawned this job
320 $telemetry->overrideRequestId( $job->getRequestId() );
321 } else {
322 // TODO: do we need to regenerate if job doesn't have the request id?
323 // If JobRunner was called with X-Request-ID header, regeneration will generate the
324 // same value
325 $telemetry->regenerateRequestId();
326 }
327 // Use an appropriate timeout to balance lag avoidance and job progress
328 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
329 try {
330 return $this->doExecuteJob( $job );
331 } finally {
332 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
333 $telemetry->overrideRequestId( $oldRequestId );
334 }
335 }
336
345 private function doExecuteJob( RunnableJob $job ) {
346 $jType = $job->getType();
347 $msg = $job->toString() . " STARTING";
348 $this->logger->debug( $msg, [ 'job_type' => $job->getType() ] );
349 $this->debugCallback( $msg );
350
351 // Clear out title cache data from prior snapshots
352 // (e.g. from before JobRunner was invoked in this process)
353 $this->linkCache->clear();
354
355 // Run the job...
356 $caught = [];
357 $rssStart = $this->getMaxRssKb();
358 $jobStartTime = microtime( true );
359 try {
360 $fnameTrxOwner = get_class( $job ) . '::run'; // give run() outer scope
361 // Flush any pending changes left over from an implicit transaction round
362 if ( $job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
363 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner ); // new implicit round
364 } else {
365 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner ); // new explicit round
366 }
367 // Clear any stale REPEATABLE-READ snapshots from replica DB connections
368 $status = $job->run();
369 $error = $job->getLastError();
370 // Commit all pending changes from this job
371 $this->lbFactory->commitPrimaryChanges(
372 $fnameTrxOwner,
373 // Abort if any transaction was too big
374 $this->options->get( MainConfigNames::MaxJobDBWriteDuration )
375 );
376 // Run any deferred update tasks; doUpdates() manages transactions itself
377 DeferredUpdates::doUpdates();
378 } catch ( Throwable $e ) {
380 $status = false;
381 $error = get_class( $e ) . ': ' . $e->getMessage() . ' in '
382 . $e->getFile() . ' on line ' . $e->getLine();
383 $caught[] = get_class( $e );
384 }
385 // Always attempt to call teardown(), even if Job throws exception
386 try {
387 $job->tearDown( $status );
388 } catch ( Throwable $e ) {
390 }
391
392 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
393 $rssEnd = $this->getMaxRssKb();
394
395 // Record how long jobs wait before getting popped
396 $readyTs = $job->getReadyTimestamp();
397 if ( $readyTs ) {
398 $pickupDelay = max( 0, $jobStartTime - $readyTs );
399 $this->stats->timing( 'jobqueue.pickup_delay.all', 1000 * $pickupDelay );
400 $this->stats->timing( "jobqueue.pickup_delay.$jType", 1000 * $pickupDelay );
401 }
402 // Record root job age for jobs being run
403 $rootTimestamp = $job->getRootJobParams()['rootJobTimestamp'];
404 if ( $rootTimestamp ) {
405 $age = max( 0, $jobStartTime - (int)wfTimestamp( TS_UNIX, $rootTimestamp ) );
406 $this->stats->timing( "jobqueue.pickup_root_age.$jType", 1000 * $age );
407 }
408 // Track the execution time for jobs
409 $this->stats->timing( "jobqueue.run.$jType", $timeMs );
410 // Track RSS increases for jobs (in case of memory leaks)
411 if ( $rssStart && $rssEnd ) {
412 $this->stats->updateCount( "jobqueue.rss_delta.$jType", $rssEnd - $rssStart );
413 }
414
415 if ( $status === false ) {
416 $msg = $job->toString() . " t={job_duration} error={job_error}";
417 $this->logger->error( $msg, [
418 'job_type' => $job->getType(),
419 'job_duration' => $timeMs,
420 'job_error' => $error,
421 ] );
422
423 $msg = $job->toString() . " t=$timeMs error={$error}";
424 $this->debugCallback( $msg );
425 } else {
426 $msg = $job->toString() . " t={job_duration} good";
427 $this->logger->info( $msg, [
428 'job_type' => $job->getType(),
429 'job_duration' => $timeMs,
430 ] );
431
432 $msg = $job->toString() . " t=$timeMs good";
433 $this->debugCallback( $msg );
434 }
435
436 return [
437 'status' => $status,
438 'error' => $error,
439 'caught' => $caught,
440 'timeMs' => $timeMs
441 ];
442 }
443
448 private function getErrorBackoffTTL( array $caught ) {
449 return in_array( DBReadOnlyError::class, $caught )
450 ? self::READONLY_BACKOFF_TTL
451 : self::ERROR_BACKOFF_TTL;
452 }
453
457 private function getMaxRssKb() {
458 $info = getrusage( 0 /* RUSAGE_SELF */ );
459 // see https://linux.die.net/man/2/getrusage
460 return isset( $info['ru_maxrss'] ) ? (int)$info['ru_maxrss'] : null;
461 }
462
468 private function getBackoffTimeToWait( RunnableJob $job ) {
469 $throttling = $this->options->get( MainConfigNames::JobBackoffThrottling );
470
471 if ( !isset( $throttling[$job->getType()] ) || $job instanceof DuplicateJob ) {
472 return 0; // not throttled
473 }
474
475 $itemsPerSecond = $throttling[$job->getType()];
476 if ( $itemsPerSecond <= 0 ) {
477 return 0; // not throttled
478 }
479
480 $seconds = 0;
481 if ( $job->workItemCount() > 0 ) {
482 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
483 // use randomized rounding
484 $seconds = floor( $exactSeconds );
485 $remainder = $exactSeconds - $seconds;
486 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
487 }
488
489 return (int)$seconds;
490 }
491
500 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
501 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
502 if ( is_file( $file ) ) {
503 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
504 $handle = fopen( $file, 'rb' );
505 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
506 fclose( $handle );
507 return $backoffs; // don't wait on lock
508 }
509 $content = stream_get_contents( $handle );
510 flock( $handle, LOCK_UN );
511 fclose( $handle );
512 $ctime = microtime( true );
513 $cBackoffs = json_decode( $content, true ) ?: [];
514 foreach ( $cBackoffs as $type => $timestamp ) {
515 if ( $timestamp < $ctime ) {
516 unset( $cBackoffs[$type] );
517 }
518 }
519 } else {
520 $cBackoffs = [];
521 }
522
523 return $cBackoffs;
524 }
525
537 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
538 if ( !$deltas ) {
539 return $this->loadBackoffs( $backoffs, $mode );
540 }
541
542 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
543 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
544 $handle = fopen( $file, 'wb+' );
545 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
546 fclose( $handle );
547 return $backoffs; // don't wait on lock
548 }
549 $ctime = microtime( true );
550 $content = stream_get_contents( $handle );
551 $cBackoffs = json_decode( $content, true ) ?: [];
552 foreach ( $deltas as $type => $seconds ) {
553 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
554 ? $cBackoffs[$type] + $seconds
555 : $ctime + $seconds;
556 }
557 foreach ( $cBackoffs as $type => $timestamp ) {
558 if ( $timestamp < $ctime ) {
559 unset( $cBackoffs[$type] );
560 }
561 }
562 ftruncate( $handle, 0 );
563 fwrite( $handle, json_encode( $cBackoffs ) );
564 flock( $handle, LOCK_UN );
565 fclose( $handle );
566
567 $deltas = [];
568
569 return $cBackoffs;
570 }
571
577 private function checkMemoryOK() {
578 static $maxBytes = null;
579 if ( $maxBytes === null ) {
580 $m = [];
581 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
582 [ , $num, $unit ] = $m;
583 $conv = [ 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 ];
584 $maxBytes = (int)$num * $conv[strtolower( $unit )];
585 } else {
586 $maxBytes = 0;
587 }
588 }
589 $usedBytes = memory_get_usage();
590 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
591 $msg = "Detected excessive memory usage ({used_bytes}/{max_bytes}).";
592 $this->logger->error( $msg, [
593 'used_bytes' => $usedBytes,
594 'max_bytes' => $maxBytes,
595 ] );
596
597 $msg = "Detected excessive memory usage ($usedBytes/$maxBytes).";
598 $this->debugCallback( $msg );
599
600 return false;
601 }
602
603 return true;
604 }
605
610 private function debugCallback( $msg ) {
611 if ( $this->debug ) {
612 call_user_func_array( $this->debug, [ wfTimestamp( TS_DB ) . " $msg\n" ] );
613 }
614 }
615}
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.
No-op job that does nothing.
Handle enqueueing of background jobs.
Job queue runner utility methods.
Definition JobRunner.php:39
setDebugHandler( $debug)
Definition JobRunner.php:89
run(array $options)
Run jobs of the specified number/type for the specified time.
const CONSTRUCTOR_OPTIONS
Definition JobRunner.php:44
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, StatsdDataFactoryInterface $statsdDataFactory, LoggerInterface $logger)
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).
Cache for article titles (prefixed DB keys) and ids linked from one source.
Definition LinkCache.php:52
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.
Service for handling telemetry data.
Definition Telemetry.php:29
A class containing constants representing the names of configuration variables.
Determine whether a site is currently in read-only mode.
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