24use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
28use Psr\Log\LoggerAwareInterface;
29use Psr\Log\LoggerInterface;
33use Wikimedia\ScopedCallback;
47 'JobBackoffThrottling',
49 'JobSerialCommitThreshold',
50 'MaxJobDBWriteDuration',
79 private const MAX_ALLOWED_LAG = 3;
81 private const SYNC_TIMEOUT = self::MAX_ALLOWED_LAG;
83 private const LAG_CHECK_PERIOD = 1.0;
85 private const ERROR_BACKOFF_TTL = 1;
87 private const READONLY_BACKOFF_TTL = 30;
103 $this->logger = $logger;
118 $serviceOptions =
null,
123 StatsdDataFactoryInterface $statsdDataFactory =
null,
124 LoggerInterface $logger =
null
126 if ( !$serviceOptions || $serviceOptions instanceof LoggerInterface ) {
130 static::CONSTRUCTOR_OPTIONS,
131 MediaWikiServices::getInstance()->getMainConfig()
135 $this->options = $serviceOptions;
136 $this->lbFactory =
$lbFactory ?? MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
137 $this->jobQueueGroup =
$jobQueueGroup ?? JobQueueGroup::singleton();
138 $this->readOnlyMode =
$readOnlyMode ?: MediaWikiServices::getInstance()->getReadOnlyMode();
139 $this->linkCache =
$linkCache ?? MediaWikiServices::getInstance()->getLinkCache();
140 $this->stats = $statsdDataFactory ?? MediaWikiServices::getInstance()->getStatsdDataFactory();
141 $this->logger =
$logger ?? LoggerFactory::getInstance(
'runJobs' );
169 public function run( array $options ) {
170 $type = $options[
'type'] ??
false;
171 $maxJobs = $options[
'maxJobs'] ??
false;
172 $maxTime = $options[
'maxTime'] ??
false;
173 $throttle = $options[
'throttle'] ??
true;
175 $jobClasses = $this->options->get(
'JobClasses' );
176 $profilerLimits = $this->options->get(
'TrxProfilerLimits' );
178 $response = [
'jobs' => [],
'reached' =>
'none-ready' ];
180 if (
$type !==
false && !isset( $jobClasses[
$type] ) ) {
182 $response[
'reached'] =
'none-possible';
186 if ( $this->readOnlyMode->isReadOnly() ) {
188 $response[
'reached'] =
'read-only';
192 list( , $maxLag ) = $this->lbFactory->getMainLB()->getMaxLag();
193 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
195 $response[
'reached'] =
'replica-lag-limit';
200 $this->lbFactory->getTransactionProfiler()
201 ->setExpectations( $profilerLimits[
'JobRunner'], __METHOD__ );
204 if ( $this->lbFactory->hasTransactionRound() ) {
205 throw new LogicException( __METHOD__ .
' called with an active transaction round.' );
213 $loopStartTime = microtime(
true );
221 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
224 if (
$type ===
false ) {
226 $job = $this->jobQueueGroup
227 ->pop( JobQueueGroup::TYPE_DEFAULT, JobQueueGroup::USE_CACHE, $backoffKeys );
231 $job = in_array(
$type, $backoffKeys ) ? false : $this->jobQueueGroup->pop(
$type );
236 $jType =
$job->getType();
243 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
250 if ( $info[
'status'] !==
false || !
$job->allowRetries() ) {
251 $this->jobQueueGroup->ack(
$job );
255 if ( $info[
'status'] ===
false && mt_rand( 0, 49 ) == 0 ) {
257 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
260 $response[
'jobs'][] = [
262 'status' => ( $info[
'status'] === false ) ?
'failed' :
'ok',
263 'error' => $info[
'error'],
264 'time' => $info[
'timeMs']
266 $timeMsTotal += $info[
'timeMs'];
269 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
270 $response[
'reached'] =
'job-limit';
272 } elseif ( $maxTime && ( microtime(
true ) - $loopStartTime ) > $maxTime ) {
273 $response[
'reached'] =
'time-limit';
280 $timePassed = microtime(
true ) - $lastSyncTime;
281 if ( $timePassed >= self::LAG_CHECK_PERIOD || $timePassed < 0 ) {
282 $opts = [
'ifWritesSince' => $lastSyncTime,
'timeout' => self::SYNC_TIMEOUT ];
283 if ( !$this->lbFactory->waitForReplication( $opts ) ) {
284 $response[
'reached'] =
'replica-lag-limit';
287 $lastSyncTime = microtime(
true );
292 $response[
'reached'] =
'memory-limit';
299 if ( $backoffDeltas ) {
303 $response[
'backoffs'] = $backoffs;
304 $response[
'elapsed'] = $timeMsTotal;
328 $oldRequestId = WebRequest::getRequestId();
330 WebRequest::overrideRequestId(
$job->getRequestId() );
332 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
336 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
337 WebRequest::overrideRequestId( $oldRequestId );
350 $jType =
$job->getType();
351 $msg =
$job->toString() .
" STARTING";
352 $this->logger->debug( $msg, [
'job_type' =>
$job->getType() ] );
357 $this->linkCache->clear();
362 $jobStartTime = microtime(
true );
364 $fnameTrxOwner = get_class(
$job ) .
'::run';
366 if (
$job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
367 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner );
369 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner );
372 $this->lbFactory->flushReplicaSnapshots( $fnameTrxOwner );
373 $status =
$job->run();
374 $error =
$job->getLastError();
378 DeferredUpdates::doUpdates();
379 }
catch ( Throwable $e ) {
380 MWExceptionHandler::rollbackPrimaryChangesAndLog( $e );
382 $error = get_class( $e ) .
': ' . $e->getMessage();
383 $caught[] = get_class( $e );
387 $job->tearDown( $status );
388 }
catch ( Throwable $e ) {
389 MWExceptionHandler::logException( $e );
392 $timeMs = intval( ( microtime(
true ) - $jobStartTime ) * 1000 );
396 $readyTs =
$job->getReadyTimestamp();
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 );
403 $rootTimestamp =
$job->getRootJobParams()[
'rootJobTimestamp'];
404 if ( $rootTimestamp ) {
405 $age = max( 0, $jobStartTime -
wfTimestamp( TS_UNIX, $rootTimestamp ) );
406 $this->stats->timing(
"jobqueue.pickup_root_age.$jType", 1000 * $age );
409 $this->stats->timing(
"jobqueue.run.$jType", $timeMs );
411 if ( $rssStart && $rssEnd ) {
412 $this->stats->updateCount(
"jobqueue.rss_delta.$jType", $rssEnd - $rssStart );
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,
423 $msg =
$job->toString() .
" t=$timeMs error={$error}";
426 $msg =
$job->toString() .
" t={job_duration} good";
427 $this->logger->info( $msg, [
428 'job_type' =>
$job->getType(),
429 'job_duration' => $timeMs,
432 $msg =
$job->toString() .
" t=$timeMs good";
449 return in_array( DBReadOnlyError::class, $caught )
450 ? self::READONLY_BACKOFF_TTL
451 : self::ERROR_BACKOFF_TTL;
458 $info = getrusage( 0 );
460 return isset( $info[
'ru_maxrss'] ) ? (int)$info[
'ru_maxrss'] :
null;
469 $throttling = $this->options->get(
'JobBackoffThrottling' );
475 $itemsPerSecond = $throttling[
$job->getType()];
476 if ( $itemsPerSecond <= 0 ) {
481 if (
$job->workItemCount() > 0 ) {
482 $exactSeconds =
$job->workItemCount() / $itemsPerSecond;
484 $seconds = floor( $exactSeconds );
485 $remainder = $exactSeconds - $seconds;
486 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
489 return (
int)$seconds;
502 if ( is_file(
$file ) ) {
503 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
504 $handle = fopen(
$file,
'rb' );
505 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
509 $content = stream_get_contents( $handle );
510 flock( $handle, LOCK_UN );
512 $ctime = microtime(
true );
513 $cBackoffs = json_decode(
$content,
true ) ?: [];
514 foreach ( $cBackoffs as
$type => $timestamp ) {
515 if ( $timestamp < $ctime ) {
516 unset( $cBackoffs[
$type] );
542 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
544 $handle = fopen(
$file,
'wb+' );
545 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
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
557 foreach ( $cBackoffs as
$type => $timestamp ) {
558 if ( $timestamp < $ctime ) {
559 unset( $cBackoffs[
$type] );
562 ftruncate( $handle, 0 );
563 fwrite( $handle, json_encode( $cBackoffs ) );
564 flock( $handle, LOCK_UN );
578 static $maxBytes =
null;
579 if ( $maxBytes ===
null ) {
581 if ( preg_match(
'!^(\d+)(k|m|g|)$!i', ini_get(
'memory_limit' ), $m ) ) {
582 list( , $num, $unit ) = $m;
583 $conv = [
'g' => 1073741824,
'm' => 1048576,
'k' => 1024,
'' => 1 ];
584 $maxBytes = $num * $conv[strtolower( $unit )];
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,
597 $msg =
"Detected excessive memory usage ($usedBytes/$maxBytes).";
611 if ( $this->debug ) {
612 call_user_func_array( $this->debug, [
wfTimestamp( TS_DB ) .
" $msg\n" ] );
627 $syncThreshold = $this->options->get(
'JobSerialCommitThreshold' );
630 $lb = $this->lbFactory->getMainLB();
631 if ( $syncThreshold !==
false && $lb->hasStreamingReplicaServers() ) {
633 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
635 if ( $dbwSerial && $dbwSerial->namedLocksEnqueue() ) {
636 $time = $dbwSerial->pendingWriteQueryDuration( $dbwSerial::ESTIMATE_DB_APPLY );
637 if ( $time < $syncThreshold ) {
649 $this->lbFactory->commitPrimaryChanges(
652 [
'maxWriteDuration' => $this->options->get(
'MaxJobDBWriteDuration' ) ]
658 $ms = intval( 1000 * $time );
660 $msg =
$job->toString() .
" COMMIT ENQUEUED [{job_commit_write_ms}ms of writes]";
661 $this->logger->info( $msg, [
662 'job_type' =>
$job->getType(),
663 'job_commit_write_ms' => $ms,
666 $msg =
$job->toString() .
" COMMIT ENQUEUED [{$ms}ms of writes]";
670 if ( !$dbwSerial->lock(
'jobrunner-serial-commit', $fnameTrxOwner, 30 ) ) {
672 throw new DBError( $dbwSerial,
"Timed out waiting on commit queue." );
674 $unlocker =
new ScopedCallback(
static function () use ( $dbwSerial, $fnameTrxOwner ) {
675 $dbwSerial->unlock(
'jobrunner-serial-commit', $fnameTrxOwner );
679 $pos = $lb->getPrimaryPos();
681 $lb->waitForAll( $pos );
685 $this->lbFactory->commitPrimaryChanges(
688 [
'maxWriteDuration' => $this->options->get(
'MaxJobDBWriteDuration' ) ]
690 ScopedCallback::consume( $unlocker );
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.
No-op job that does nothing.
Class to handle enqueueing of background jobs.
Job queue runner utility methods.
run(array $options)
Run jobs of the specified number/type for the specified time.
getErrorBackoffTTL(array $caught)
ReadOnlyMode $readOnlyMode
const CONSTRUCTOR_OPTIONS
callable null $debug
Debug output handler.
setLogger(LoggerInterface $logger)
executeJob(RunnableJob $job)
Run a specific job in a manner appropriate for mass use by job dispatchers.
syncBackoffDeltas(array $backoffs, array &$deltas, $mode='wait')
Merge the current backoff expiries from persistent storage.
commitPrimaryChanges(RunnableJob $job, $fnameTrxOwner)
Issue a commit on all masters who are currently in a transaction and have made changes to the databas...
JobQueueGroup $jobQueueGroup
StatsdDataFactoryInterface $stats
doExecuteJob(RunnableJob $job)
debugCallback( $msg)
Log the job message.
getBackoffTimeToWait(RunnableJob $job)
checkMemoryOK()
Make sure that this script is not too close to the memory usage limit.
__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.
loadBackoffs(array $backoffs, $mode='wait')
Get the previous backoff expiries from persistent storage On I/O or lock acquisition failure this ret...
Cache for article titles (prefixed DB keys) and ids linked from one source.
A service class for fetching the wiki's current read-only mode.
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
if(count( $args)< 1) $job
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.