3 * Job queue runner utility methods
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Logger\LoggerFactory
;
25 use Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
29 * Job queue runner utility methods
34 class JobRunner
implements LoggerAwareInterface
{
35 /** @var callable|null Debug output handler */
39 * @var LoggerInterface $logger
44 * @param callable $debug Optional debug output handler
46 public function setDebugHandler( $debug ) {
47 $this->debug
= $debug;
51 * @param LoggerInterface $logger
54 public function setLogger( LoggerInterface
$logger ) {
55 $this->logger
= $logger;
59 * @param LoggerInterface $logger
61 public function __construct( LoggerInterface
$logger = null ) {
62 if ( $logger === null ) {
63 $logger = LoggerFactory
::getInstance( 'runJobs' );
65 $this->setLogger( $logger );
69 * Run jobs of the specified number/type for the specified time
71 * The response map has a 'job' field that lists status of each job, including:
72 * - type : the job type
73 * - status : ok/failed
74 * - error : any error message string
75 * - time : the job run time in ms
76 * The response map also has:
77 * - backoffs : the (job type => seconds) map of backoff times
78 * - elapsed : the total time spent running tasks in ms
79 * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit)
81 * This method outputs status information only if a debug handler was set.
82 * Any exceptions are caught and logged, but are not reported as output.
84 * @param array $options Map of parameters:
85 * - type : the job type (or false for the default types)
86 * - maxJobs : maximum number of jobs to run
87 * - maxTime : maximum time in seconds before stopping
88 * - throttle : whether to respect job backoff configuration
89 * @return array Summary response that can easily be JSON serialized
91 public function run( array $options ) {
92 global $wgJobClasses, $wgTrxProfilerLimits;
94 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
96 $type = isset( $options['type'] ) ?
$options['type'] : false;
97 $maxJobs = isset( $options['maxJobs'] ) ?
$options['maxJobs'] : false;
98 $maxTime = isset( $options['maxTime'] ) ?
$options['maxTime'] : false;
99 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
101 if ( $type !== false && !isset( $wgJobClasses[$type] ) ) {
102 $response['reached'] = 'none-possible';
106 $group = JobQueueGroup
::singleton();
107 // Handle any required periodic queue maintenance
108 $count = $group->executeReadyPeriodicTasks();
110 $msg = "Executed $count periodic queue task(s).";
111 $this->logger
->debug( $msg );
112 $this->debugCallback( $msg );
115 // Bail out if in read-only mode
116 if ( wfReadOnly() ) {
117 $response['reached'] = 'read-only';
121 // Catch huge single updates that lead to slave lag
122 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
123 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
124 $trxProfiler->setExpectations( $wgTrxProfilerLimits['JobRunner'], __METHOD__
);
126 // Bail out if there is too much DB lag.
127 // This check should not block as we want to try other wiki queues.
129 list( , $maxLag ) = wfGetLB( wfWikiID() )->getMaxLag();
130 if ( $maxLag >= $maxAllowedLag ) {
131 $response['reached'] = 'slave-lag-limit';
135 // Flush any pending DB writes for sanity
136 wfGetLBFactory()->commitMasterChanges();
138 // Some jobs types should not run until a certain timestamp
139 $backoffs = array(); // map of (type => UNIX expiry)
140 $backoffDeltas = array(); // map of (type => seconds)
141 $wait = 'wait'; // block to read backoffs the first time
145 $flags = JobQueueGroup
::USE_CACHE
;
146 $startTime = microtime( true ); // time since jobs started running
147 $checkLagPeriod = 1.0; // check slave lag this many seconds
148 $lastCheckTime = 1; // timestamp of last slave check
150 // Sync the persistent backoffs with concurrent runners
151 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
152 $blacklist = $noThrottle ?
array() : array_keys( $backoffs );
153 $wait = 'nowait'; // less important now
155 if ( $type === false ) {
156 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
157 } elseif ( in_array( $type, $blacklist ) ) {
158 $job = false; // requested queue in backoff state
160 $job = $group->pop( $type ); // job from a single queue
163 if ( $job ) { // found a job
164 $jType = $job->getType();
166 // Back off of certain jobs for a while (for throttling and for errors)
167 $ttw = $this->getBackoffTimeToWait( $job );
169 // Always add the delta for other runners in case the time running the
170 // job negated the backoff for each individually but not collectively.
171 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
172 ?
$backoffDeltas[$jType] +
$ttw
174 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
177 $msg = $job->toString() . " STARTING";
178 $this->logger
->info( $msg );
179 $this->debugCallback( $msg );
182 $jobStartTime = microtime( true );
185 $status = $job->run();
186 $error = $job->getLastError();
187 $this->commitMasterChanges( $job );
188 } catch ( Exception
$e ) {
189 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
191 $error = get_class( $e ) . ': ' . $e->getMessage();
192 MWExceptionHandler
::logException( $e );
194 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
195 $timeMsTotal +
= $timeMs;
197 // Mark the job as done on success or when the job cannot be retried
198 if ( $status !== false ||
!$job->allowRetries() ) {
199 $group->ack( $job ); // done
202 // Back off of certain jobs for a while (for throttling and for errors)
203 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
204 $ttw = max( $ttw, 30 ); // too many errors
205 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
206 ?
$backoffDeltas[$jType] +
$ttw
210 if ( $status === false ) {
211 $msg = $job->toString() . " t=$timeMs error={$error}";
212 $this->logger
->error( $msg );
213 $this->debugCallback( $msg );
215 $msg = $job->toString() . " t=$timeMs good";
216 $this->logger
->info( $msg );
217 $this->debugCallback( $msg );
220 $response['jobs'][] = array(
222 'status' => ( $status === false ) ?
'failed' : 'ok',
227 // Break out if we hit the job count or wall time limits...
228 if ( $maxJobs && $jobsRun >= $maxJobs ) {
229 $response['reached'] = 'job-limit';
231 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
232 $response['reached'] = 'time-limit';
236 // Don't let any of the main DB slaves get backed up.
237 // This only waits for so long before exiting and letting
238 // other wikis in the farm (on different masters) get a chance.
239 $timePassed = microtime( true ) - $lastCheckTime;
240 if ( $timePassed >= $checkLagPeriod ||
$timePassed < 0 ) {
241 if ( !wfWaitForSlaves( $lastCheckTime, false, '*', $maxAllowedLag ) ) {
242 $response['reached'] = 'slave-lag-limit';
245 $lastCheckTime = microtime( true );
247 // Don't let any queue slaves/backups fall behind
248 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
249 $group->waitForBackups();
252 // Bail if near-OOM instead of in a job
253 $this->assertMemoryOK();
255 } while ( $job ); // stop when there are no jobs
257 // Sync the persistent backoffs for the next runJobs.php pass
258 if ( $backoffDeltas ) {
259 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
262 $response['backoffs'] = $backoffs;
263 $response['elapsed'] = $timeMsTotal;
270 * @return int Seconds for this runner to avoid doing more jobs of this type
271 * @see $wgJobBackoffThrottling
273 private function getBackoffTimeToWait( Job
$job ) {
274 global $wgJobBackoffThrottling;
276 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
277 $job instanceof DuplicateJob
// no work was done
279 return 0; // not throttled
282 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
283 if ( $itemsPerSecond <= 0 ) {
284 return 0; // not throttled
288 if ( $job->workItemCount() > 0 ) {
289 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
290 // use randomized rounding
291 $seconds = floor( $exactSeconds );
292 $remainder = $exactSeconds - $seconds;
293 $seconds +
= ( mt_rand() / mt_getrandmax() < $remainder ) ?
1 : 0;
296 return (int)$seconds;
300 * Get the previous backoff expiries from persistent storage
301 * On I/O or lock acquisition failure this returns the original $backoffs.
303 * @param array $backoffs Map of (job type => UNIX timestamp)
304 * @param string $mode Lock wait mode - "wait" or "nowait"
305 * @return array Map of (job type => backoff expiry timestamp)
307 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
308 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
309 if ( is_file( $file ) ) {
310 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
311 $handle = fopen( $file, 'rb' );
312 if ( !flock( $handle, LOCK_SH |
$noblock ) ) {
314 return $backoffs; // don't wait on lock
316 $content = stream_get_contents( $handle );
317 flock( $handle, LOCK_UN
);
319 $ctime = microtime( true );
320 $cBackoffs = json_decode( $content, true ) ?
: array();
321 foreach ( $cBackoffs as $type => $timestamp ) {
322 if ( $timestamp < $ctime ) {
323 unset( $cBackoffs[$type] );
327 $cBackoffs = array();
334 * Merge the current backoff expiries from persistent storage
336 * The $deltas map is set to an empty array on success.
337 * On I/O or lock acquisition failure this returns the original $backoffs.
339 * @param array $backoffs Map of (job type => UNIX timestamp)
340 * @param array $deltas Map of (job type => seconds)
341 * @param string $mode Lock wait mode - "wait" or "nowait"
342 * @return array The new backoffs account for $backoffs and the latest file data
344 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
346 return $this->loadBackoffs( $backoffs, $mode );
349 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
350 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
351 $handle = fopen( $file, 'wb+' );
352 if ( !flock( $handle, LOCK_EX |
$noblock ) ) {
354 return $backoffs; // don't wait on lock
356 $ctime = microtime( true );
357 $content = stream_get_contents( $handle );
358 $cBackoffs = json_decode( $content, true ) ?
: array();
359 foreach ( $deltas as $type => $seconds ) {
360 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
361 ?
$cBackoffs[$type] +
$seconds
364 foreach ( $cBackoffs as $type => $timestamp ) {
365 if ( $timestamp < $ctime ) {
366 unset( $cBackoffs[$type] );
369 ftruncate( $handle, 0 );
370 fwrite( $handle, json_encode( $cBackoffs ) );
371 flock( $handle, LOCK_UN
);
380 * Make sure that this script is not too close to the memory usage limit.
381 * It is better to die in between jobs than OOM right in the middle of one.
382 * @throws MWException
384 private function assertMemoryOK() {
385 static $maxBytes = null;
386 if ( $maxBytes === null ) {
388 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
389 list( , $num, $unit ) = $m;
390 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
391 $maxBytes = $num * $conv[strtolower( $unit )];
396 $usedBytes = memory_get_usage();
397 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
398 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
403 * Log the job message
404 * @param string $msg The message to log
406 private function debugCallback( $msg ) {
407 if ( $this->debug
) {
408 call_user_func_array( $this->debug
, array( wfTimestamp( TS_DB
) . " $msg\n" ) );
413 * Commit any DB master changes from a job on all load balancers
418 private function commitMasterChanges( Job
$job ) {
419 global $wgJobSerialCommitThreshold;
421 $lb = wfGetLB( wfWikiID() );
422 if ( $wgJobSerialCommitThreshold !== false ) {
423 // Generally, there is one master connection to the local DB
424 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
430 ||
!$dbwSerial->namedLocksEnqueue()
431 ||
$dbwSerial->pendingWriteQueryDuration() < $wgJobSerialCommitThreshold
433 // Writes are all to foreign DBs, named locks don't form queues,
434 // or $wgJobSerialCommitThreshold is not reached; commit changes now
435 wfGetLBFactory()->commitMasterChanges();
439 $ms = intval( 1000 * $dbwSerial->pendingWriteQueryDuration() );
440 $msg = $job->toString() . " COMMIT ENQUEUED [{$ms}ms of writes]";
441 $this->logger
->info( $msg );
442 $this->debugCallback( $msg );
444 // Wait for an exclusive lock to commit
445 if ( !$dbwSerial->lock( 'jobrunner-serial-commit', __METHOD__
, 30 ) ) {
446 // This will trigger a rollback in the main loop
447 throw new DBError( $dbwSerial, "Timed out waiting on commit queue." );
449 // Wait for the generic slave to catch up
450 $pos = $lb->getMasterPos();
452 $lb->waitForOne( $pos );
456 // Re-ping all masters with transactions. This throws DBError if some
457 // connection died while waiting on locks/slaves, triggering a rollback.
458 wfGetLBFactory()->forEachLB( function( LoadBalancer
$lb ) use ( $fname ) {
459 $lb->forEachOpenConnection( function( DatabaseBase
$conn ) use ( $fname ) {
460 if ( $conn->writesOrCallbacksPending() ) {
461 $conn->query( "SELECT 1", $fname );
466 // Actually commit the DB master changes
467 wfGetLBFactory()->commitMasterChanges();
470 $dbwSerial->unlock( 'jobrunner-serial-commit', __METHOD__
);