46 MainConfigNames::JobBackoffThrottling,
47 MainConfigNames::JobClasses,
48 MainConfigNames::JobSerialCommitThreshold,
49 MainConfigNames::MaxJobDBWriteDuration,
50 MainConfigNames::TrxProfilerLimits,
60 private $jobQueueGroup;
63 private $readOnlyMode;
78 private const MAX_ALLOWED_LAG = 3;
80 private const SYNC_TIMEOUT = self::MAX_ALLOWED_LAG;
82 private const LAG_CHECK_PERIOD = 1.0;
84 private const ERROR_BACKOFF_TTL = 1;
86 private const READONLY_BACKOFF_TTL = 30;
92 $this->debug = $debug;
111 StatsdDataFactoryInterface $statsdDataFactory,
112 LoggerInterface $logger
115 $this->options = $serviceOptions;
116 $this->lbFactory = $lbFactory;
117 $this->jobQueueGroup = $jobQueueGroup;
118 $this->readOnlyMode = $readOnlyMode;
119 $this->linkCache = $linkCache;
120 $this->stats = $statsdDataFactory;
121 $this->logger = $logger;
149 public function run( array $options ) {
150 $type = $options[
'type'] ??
false;
151 $maxJobs = $options[
'maxJobs'] ??
false;
152 $maxTime = $options[
'maxTime'] ??
false;
153 $throttle = $options[
'throttle'] ??
true;
155 $jobClasses = $this->options->get( MainConfigNames::JobClasses );
156 $profilerLimits = $this->options->get( MainConfigNames::TrxProfilerLimits );
158 $response = [
'jobs' => [],
'reached' =>
'none-ready' ];
160 if (
$type !==
false && !isset( $jobClasses[
$type] ) ) {
162 $response[
'reached'] =
'none-possible';
166 if ( $this->readOnlyMode->isReadOnly() ) {
168 $response[
'reached'] =
'read-only';
172 [ , $maxLag ] = $this->lbFactory->getMainLB()->getMaxLag();
173 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
175 $response[
'reached'] =
'replica-lag-limit';
180 $this->lbFactory->getTransactionProfiler()
181 ->setExpectations( $profilerLimits[
'JobRunner'], __METHOD__ );
184 if ( $this->lbFactory->hasTransactionRound() ) {
185 throw new LogicException( __METHOD__ .
' called with an active transaction round.' );
193 $loopStartTime = microtime(
true );
200 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
201 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
204 if (
$type ===
false ) {
206 $job = $this->jobQueueGroup
207 ->pop( JobQueueGroup::TYPE_DEFAULT, JobQueueGroup::USE_CACHE, $backoffKeys );
211 $job = in_array(
$type, $backoffKeys ) ? false : $this->jobQueueGroup->pop(
$type );
216 $jType =
$job->getType();
219 $ttw = $this->getBackoffTimeToWait(
$job );
223 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
224 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
230 if ( $info[
'status'] !==
false || !
$job->allowRetries() ) {
231 $this->jobQueueGroup->ack(
$job );
235 if ( $info[
'status'] ===
false && mt_rand( 0, 49 ) == 0 ) {
236 $ttw = max( $ttw, $this->getErrorBackoffTTL( $info[
'caught'] ) );
237 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
240 $response[
'jobs'][] = [
242 'status' => ( $info[
'status'] === false ) ?
'failed' :
'ok',
243 'error' => $info[
'error'],
244 'time' => $info[
'timeMs']
246 $timeMsTotal += $info[
'timeMs'];
249 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
250 $response[
'reached'] =
'job-limit';
252 } elseif ( $maxTime && ( microtime(
true ) - $loopStartTime ) > $maxTime ) {
253 $response[
'reached'] =
'time-limit';
261 if ( in_array( DBConnectionError::class, $info[
'caught'],
true ) ) {
262 $response[
'reached'] =
'exception';
269 $timePassed = microtime(
true ) - $lastSyncTime;
270 if ( $timePassed >= self::LAG_CHECK_PERIOD || $timePassed < 0 ) {
271 $opts = [
'ifWritesSince' => $lastSyncTime,
'timeout' => self::SYNC_TIMEOUT ];
272 if ( !$this->lbFactory->waitForReplication( $opts ) ) {
273 $response[
'reached'] =
'replica-lag-limit';
276 $lastSyncTime = microtime(
true );
280 if ( !$this->checkMemoryOK() ) {
281 $response[
'reached'] =
'memory-limit';
288 if ( $backoffDeltas ) {
289 $this->syncBackoffDeltas( $backoffs, $backoffDeltas,
'wait' );
292 $response[
'backoffs'] = $backoffs;
293 $response[
'elapsed'] = $timeMsTotal;
317 $oldRequestId = WebRequest::getRequestId();
319 WebRequest::overrideRequestId(
$job->getRequestId() );
321 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
323 return $this->doExecuteJob(
$job );
325 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
326 WebRequest::overrideRequestId( $oldRequestId );
339 $jType =
$job->getType();
340 $msg =
$job->toString() .
" STARTING";
341 $this->logger->debug( $msg, [
'job_type' =>
$job->getType() ] );
342 $this->debugCallback( $msg );
346 $this->linkCache->clear();
350 $rssStart = $this->getMaxRssKb();
351 $jobStartTime = microtime(
true );
353 $fnameTrxOwner = get_class(
$job ) .
'::run';
355 if (
$job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
356 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner );
358 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner );
361 $this->lbFactory->flushReplicaSnapshots( $fnameTrxOwner );
362 $status =
$job->run();
363 $error =
$job->getLastError();
365 $this->commitPrimaryChanges(
$job, $fnameTrxOwner );
368 }
catch ( Throwable $e ) {
371 $error = get_class( $e ) .
': ' . $e->getMessage() .
' in '
372 . $e->getFile() .
' on line ' . $e->getLine();
373 $caught[] = get_class( $e );
377 $job->tearDown( $status );
378 }
catch ( Throwable $e ) {
382 $timeMs = intval( ( microtime(
true ) - $jobStartTime ) * 1000 );
383 $rssEnd = $this->getMaxRssKb();
386 $readyTs =
$job->getReadyTimestamp();
388 $pickupDelay = max( 0, $jobStartTime - $readyTs );
389 $this->stats->timing(
'jobqueue.pickup_delay.all', 1000 * $pickupDelay );
390 $this->stats->timing(
"jobqueue.pickup_delay.$jType", 1000 * $pickupDelay );
393 $rootTimestamp =
$job->getRootJobParams()[
'rootJobTimestamp'];
394 if ( $rootTimestamp ) {
395 $age = max( 0, $jobStartTime - (
int)
wfTimestamp( TS_UNIX, $rootTimestamp ) );
396 $this->stats->timing(
"jobqueue.pickup_root_age.$jType", 1000 * $age );
399 $this->stats->timing(
"jobqueue.run.$jType", $timeMs );
401 if ( $rssStart && $rssEnd ) {
402 $this->stats->updateCount(
"jobqueue.rss_delta.$jType", $rssEnd - $rssStart );
405 if ( $status ===
false ) {
406 $msg =
$job->toString() .
" t={job_duration} error={job_error}";
407 $this->logger->error( $msg, [
408 'job_type' =>
$job->getType(),
409 'job_duration' => $timeMs,
410 'job_error' => $error,
413 $msg =
$job->toString() .
" t=$timeMs error={$error}";
414 $this->debugCallback( $msg );
416 $msg =
$job->toString() .
" t={job_duration} good";
417 $this->logger->info( $msg, [
418 'job_type' =>
$job->getType(),
419 'job_duration' => $timeMs,
422 $msg =
$job->toString() .
" t=$timeMs good";
423 $this->debugCallback( $msg );
438 private function getErrorBackoffTTL( array $caught ) {
439 return in_array( DBReadOnlyError::class, $caught )
440 ? self::READONLY_BACKOFF_TTL
441 : self::ERROR_BACKOFF_TTL;
447 private function getMaxRssKb() {
448 $info = getrusage( 0 );
450 return isset( $info[
'ru_maxrss'] ) ? (int)$info[
'ru_maxrss'] : null;
459 $throttling = $this->options->get( MainConfigNames::JobBackoffThrottling );
465 $itemsPerSecond = $throttling[
$job->getType()];
466 if ( $itemsPerSecond <= 0 ) {
471 if (
$job->workItemCount() > 0 ) {
472 $exactSeconds =
$job->workItemCount() / $itemsPerSecond;
474 $seconds = floor( $exactSeconds );
475 $remainder = $exactSeconds - $seconds;
476 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
479 return (
int)$seconds;
490 private function loadBackoffs( array $backoffs, $mode =
'wait' ) {
492 if ( is_file(
$file ) ) {
493 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
494 $handle = fopen(
$file,
'rb' );
495 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
499 $content = stream_get_contents( $handle );
500 flock( $handle, LOCK_UN );
502 $ctime = microtime(
true );
503 $cBackoffs = json_decode(
$content,
true ) ?: [];
504 foreach ( $cBackoffs as
$type => $timestamp ) {
505 if ( $timestamp < $ctime ) {
506 unset( $cBackoffs[
$type] );
527 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode =
'wait' ) {
529 return $this->loadBackoffs( $backoffs, $mode );
532 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
534 $handle = fopen(
$file,
'wb+' );
535 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
539 $ctime = microtime(
true );
540 $content = stream_get_contents( $handle );
541 $cBackoffs = json_decode(
$content,
true ) ?: [];
542 foreach ( $deltas as
$type => $seconds ) {
543 $cBackoffs[
$type] = isset( $cBackoffs[
$type] ) && $cBackoffs[
$type] >= $ctime
544 ? $cBackoffs[
$type] + $seconds
547 foreach ( $cBackoffs as
$type => $timestamp ) {
548 if ( $timestamp < $ctime ) {
549 unset( $cBackoffs[
$type] );
552 ftruncate( $handle, 0 );
553 fwrite( $handle, json_encode( $cBackoffs ) );
554 flock( $handle, LOCK_UN );
567 private function checkMemoryOK() {
568 static $maxBytes =
null;
569 if ( $maxBytes ===
null ) {
571 if ( preg_match(
'!^(\d+)(k|m|g|)$!i', ini_get(
'memory_limit' ), $m ) ) {
572 [ , $num, $unit ] = $m;
573 $conv = [
'g' => 1073741824,
'm' => 1048576,
'k' => 1024,
'' => 1 ];
574 $maxBytes = (int)$num * $conv[strtolower( $unit )];
579 $usedBytes = memory_get_usage();
580 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
581 $msg =
"Detected excessive memory usage ({used_bytes}/{max_bytes}).";
582 $this->logger->error( $msg, [
583 'used_bytes' => $usedBytes,
584 'max_bytes' => $maxBytes,
587 $msg =
"Detected excessive memory usage ($usedBytes/$maxBytes).";
588 $this->debugCallback( $msg );
600 private function debugCallback( $msg ) {
601 if ( $this->debug ) {
602 call_user_func_array( $this->debug, [
wfTimestamp( TS_DB ) .
" $msg\n" ] );
616 private function commitPrimaryChanges(
RunnableJob $job, $fnameTrxOwner ) {
617 $syncThreshold = $this->options->get( MainConfigNames::JobSerialCommitThreshold );
620 $lb = $this->lbFactory->getMainLB();
621 if ( $syncThreshold !==
false && $lb->hasStreamingReplicaServers() ) {
623 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
625 if ( $dbwSerial && $dbwSerial->namedLocksEnqueue() ) {
626 $time = $dbwSerial->pendingWriteQueryDuration( $dbwSerial::ESTIMATE_DB_APPLY );
627 if ( $time < $syncThreshold ) {
639 $this->lbFactory->commitPrimaryChanges(
642 $this->options->get( MainConfigNames::MaxJobDBWriteDuration )
648 $ms = intval( 1000 * $time );
650 $msg =
$job->toString() .
" COMMIT ENQUEUED [{job_commit_write_ms}ms of writes]";
651 $this->logger->info( $msg, [
652 'job_type' =>
$job->getType(),
653 'job_commit_write_ms' => $ms,
656 $msg =
$job->toString() .
" COMMIT ENQUEUED [{$ms}ms of writes]";
657 $this->debugCallback( $msg );
660 if ( !$dbwSerial->lock(
'jobrunner-serial-commit', $fnameTrxOwner, 30 ) ) {
662 throw new DBError( $dbwSerial,
"Timed out waiting on commit queue." );
664 $unlocker =
new ScopedCallback(
static function () use ( $dbwSerial, $fnameTrxOwner ) {
665 $dbwSerial->unlock(
'jobrunner-serial-commit', $fnameTrxOwner );
669 $pos = $lb->getPrimaryPos();
671 $lb->waitForAll( $pos );
675 $this->lbFactory->commitPrimaryChanges(
678 $this->options->get( MainConfigNames::MaxJobDBWriteDuration )
680 ScopedCallback::consume( $unlocker );