49 MainConfigNames::JobBackoffThrottling,
50 MainConfigNames::JobClasses,
51 MainConfigNames::JobSerialCommitThreshold,
52 MainConfigNames::MaxJobDBWriteDuration,
53 MainConfigNames::TrxProfilerLimits,
63 private $jobQueueGroup;
66 private $readOnlyMode;
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;
105 $this->logger = $logger;
120 $serviceOptions =
null,
125 StatsdDataFactoryInterface $statsdDataFactory =
null,
126 LoggerInterface $logger =
null
128 if ( !$serviceOptions || $serviceOptions instanceof LoggerInterface ) {
129 wfDeprecated( __METHOD__ .
' called directly. Use MediaWikiServices instead',
'1.39' );
130 $logger = $serviceOptions;
132 static::CONSTRUCTOR_OPTIONS,
133 MediaWikiServices::getInstance()->getMainConfig()
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' );
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;
177 $jobClasses = $this->options->get( MainConfigNames::JobClasses );
178 $profilerLimits = $this->options->get( MainConfigNames::TrxProfilerLimits );
180 $response = [
'jobs' => [],
'reached' =>
'none-ready' ];
182 if (
$type !==
false && !isset( $jobClasses[
$type] ) ) {
184 $response[
'reached'] =
'none-possible';
188 if ( $this->readOnlyMode->isReadOnly() ) {
190 $response[
'reached'] =
'read-only';
194 list( , $maxLag ) = $this->lbFactory->getMainLB()->getMaxLag();
195 if ( $maxLag >= self::MAX_ALLOWED_LAG ) {
197 $response[
'reached'] =
'replica-lag-limit';
202 $this->lbFactory->getTransactionProfiler()
203 ->setExpectations( $profilerLimits[
'JobRunner'], __METHOD__ );
206 if ( $this->lbFactory->hasTransactionRound() ) {
207 throw new LogicException( __METHOD__ .
' called with an active transaction round.' );
215 $loopStartTime = microtime(
true );
222 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
223 $backoffKeys = $throttle ? array_keys( $backoffs ) : [];
226 if (
$type ===
false ) {
228 $job = $this->jobQueueGroup
229 ->pop( JobQueueGroup::TYPE_DEFAULT, JobQueueGroup::USE_CACHE, $backoffKeys );
233 $job = in_array(
$type, $backoffKeys ) ? false : $this->jobQueueGroup->pop(
$type );
238 $jType =
$job->getType();
241 $ttw = $this->getBackoffTimeToWait(
$job );
245 $backoffDeltas[$jType] = ( $backoffDeltas[$jType] ?? 0 ) + $ttw;
246 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
252 if ( $info[
'status'] !==
false || !
$job->allowRetries() ) {
253 $this->jobQueueGroup->ack(
$job );
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;
262 $response[
'jobs'][] = [
264 'status' => ( $info[
'status'] === false ) ?
'failed' :
'ok',
265 'error' => $info[
'error'],
266 'time' => $info[
'timeMs']
268 $timeMsTotal += $info[
'timeMs'];
271 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
272 $response[
'reached'] =
'job-limit';
274 } elseif ( $maxTime && ( microtime(
true ) - $loopStartTime ) > $maxTime ) {
275 $response[
'reached'] =
'time-limit';
283 if ( in_array( DBConnectionError::class, $info[
'caught'],
true ) ) {
284 $response[
'reached'] =
'exception';
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';
298 $lastSyncTime = microtime(
true );
302 if ( !$this->checkMemoryOK() ) {
303 $response[
'reached'] =
'memory-limit';
310 if ( $backoffDeltas ) {
311 $this->syncBackoffDeltas( $backoffs, $backoffDeltas,
'wait' );
314 $response[
'backoffs'] = $backoffs;
315 $response[
'elapsed'] = $timeMsTotal;
339 $oldRequestId = WebRequest::getRequestId();
341 WebRequest::overrideRequestId(
$job->getRequestId() );
343 $oldTimeout = $this->lbFactory->setDefaultReplicationWaitTimeout( self::SYNC_TIMEOUT );
345 return $this->doExecuteJob(
$job );
347 $this->lbFactory->setDefaultReplicationWaitTimeout( $oldTimeout );
348 WebRequest::overrideRequestId( $oldRequestId );
361 $jType =
$job->getType();
362 $msg =
$job->toString() .
" STARTING";
363 $this->logger->debug( $msg, [
'job_type' =>
$job->getType() ] );
364 $this->debugCallback( $msg );
368 $this->linkCache->clear();
372 $rssStart = $this->getMaxRssKb();
373 $jobStartTime = microtime(
true );
375 $fnameTrxOwner = get_class(
$job ) .
'::run';
377 if (
$job->hasExecutionFlag( $job::JOB_NO_EXPLICIT_TRX_ROUND ) ) {
378 $this->lbFactory->commitPrimaryChanges( $fnameTrxOwner );
380 $this->lbFactory->beginPrimaryChanges( $fnameTrxOwner );
383 $this->lbFactory->flushReplicaSnapshots( $fnameTrxOwner );
384 $status =
$job->run();
385 $error =
$job->getLastError();
387 $this->commitPrimaryChanges(
$job, $fnameTrxOwner );
390 }
catch ( Throwable $e ) {
393 $error = get_class( $e ) .
': ' . $e->getMessage();
394 $caught[] = get_class( $e );
398 $job->tearDown( $status );
399 }
catch ( Throwable $e ) {
403 $timeMs = intval( ( microtime(
true ) - $jobStartTime ) * 1000 );
404 $rssEnd = $this->getMaxRssKb();
407 $readyTs =
$job->getReadyTimestamp();
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 );
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 );
420 $this->stats->timing(
"jobqueue.run.$jType", $timeMs );
422 if ( $rssStart && $rssEnd ) {
423 $this->stats->updateCount(
"jobqueue.rss_delta.$jType", $rssEnd - $rssStart );
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,
434 $msg =
$job->toString() .
" t=$timeMs error={$error}";
435 $this->debugCallback( $msg );
437 $msg =
$job->toString() .
" t={job_duration} good";
438 $this->logger->info( $msg, [
439 'job_type' =>
$job->getType(),
440 'job_duration' => $timeMs,
443 $msg =
$job->toString() .
" t=$timeMs good";
444 $this->debugCallback( $msg );
459 private function getErrorBackoffTTL( array $caught ) {
460 return in_array( DBReadOnlyError::class, $caught )
461 ? self::READONLY_BACKOFF_TTL
462 : self::ERROR_BACKOFF_TTL;
468 private function getMaxRssKb() {
469 $info = getrusage( 0 );
471 return isset( $info[
'ru_maxrss'] ) ? (int)$info[
'ru_maxrss'] : null;
480 $throttling = $this->options->get( MainConfigNames::JobBackoffThrottling );
486 $itemsPerSecond = $throttling[
$job->getType()];
487 if ( $itemsPerSecond <= 0 ) {
492 if (
$job->workItemCount() > 0 ) {
493 $exactSeconds =
$job->workItemCount() / $itemsPerSecond;
495 $seconds = floor( $exactSeconds );
496 $remainder = $exactSeconds - $seconds;
497 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
500 return (
int)$seconds;
511 private function loadBackoffs( array $backoffs, $mode =
'wait' ) {
513 if ( is_file(
$file ) ) {
514 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
515 $handle = fopen(
$file,
'rb' );
516 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
520 $content = stream_get_contents( $handle );
521 flock( $handle, LOCK_UN );
523 $ctime = microtime(
true );
524 $cBackoffs = json_decode(
$content,
true ) ?: [];
525 foreach ( $cBackoffs as
$type => $timestamp ) {
526 if ( $timestamp < $ctime ) {
527 unset( $cBackoffs[
$type] );
548 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode =
'wait' ) {
550 return $this->loadBackoffs( $backoffs, $mode );
553 $noblock = ( $mode ===
'nowait' ) ? LOCK_NB : 0;
555 $handle = fopen(
$file,
'wb+' );
556 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
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
568 foreach ( $cBackoffs as
$type => $timestamp ) {
569 if ( $timestamp < $ctime ) {
570 unset( $cBackoffs[
$type] );
573 ftruncate( $handle, 0 );
574 fwrite( $handle, json_encode( $cBackoffs ) );
575 flock( $handle, LOCK_UN );
588 private function checkMemoryOK() {
589 static $maxBytes =
null;
590 if ( $maxBytes ===
null ) {
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 )];
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,
608 $msg =
"Detected excessive memory usage ($usedBytes/$maxBytes).";
609 $this->debugCallback( $msg );
621 private function debugCallback( $msg ) {
622 if ( $this->debug ) {
623 call_user_func_array( $this->debug, [
wfTimestamp( TS_DB ) .
" $msg\n" ] );
637 private function commitPrimaryChanges(
RunnableJob $job, $fnameTrxOwner ) {
638 $syncThreshold = $this->options->get( MainConfigNames::JobSerialCommitThreshold );
641 $lb = $this->lbFactory->getMainLB();
642 if ( $syncThreshold !==
false && $lb->hasStreamingReplicaServers() ) {
644 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
646 if ( $dbwSerial && $dbwSerial->namedLocksEnqueue() ) {
647 $time = $dbwSerial->pendingWriteQueryDuration( $dbwSerial::ESTIMATE_DB_APPLY );
648 if ( $time < $syncThreshold ) {
660 $this->lbFactory->commitPrimaryChanges(
663 [
'maxWriteDuration' =>
664 $this->options->get( MainConfigNames::MaxJobDBWriteDuration ) ]
670 $ms = intval( 1000 * $time );
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,
678 $msg =
$job->toString() .
" COMMIT ENQUEUED [{$ms}ms of writes]";
679 $this->debugCallback( $msg );
682 if ( !$dbwSerial->lock(
'jobrunner-serial-commit', $fnameTrxOwner, 30 ) ) {
684 throw new DBError( $dbwSerial,
"Timed out waiting on commit queue." );
686 $unlocker =
new ScopedCallback(
static function () use ( $dbwSerial, $fnameTrxOwner ) {
687 $dbwSerial->unlock(
'jobrunner-serial-commit', $fnameTrxOwner );
691 $pos = $lb->getPrimaryPos();
693 $lb->waitForAll( $pos );
697 $this->lbFactory->commitPrimaryChanges(
700 [
'maxWriteDuration' => $this->options->get( MainConfigNames::MaxJobDBWriteDuration ) ]
702 ScopedCallback::consume( $unlocker );