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 $profiler = Profiler
::instance();
123 // Catch huge single updates that lead to slave lag
124 $trxProfiler = $profiler->getTransactionProfiler();
125 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
126 $trxProfiler->setExpectations( $wgTrxProfilerLimits['JobRunner'], __METHOD__
);
128 // Bail out if there is too much DB lag.
129 // This check should not block as we want to try other wiki queues.
131 list( , $maxLag ) = wfGetLB( wfWikiID() )->getMaxLag();
132 if ( $maxLag >= $maxAllowedLag ) {
133 $response['reached'] = 'slave-lag-limit';
137 // Flush any pending DB writes for sanity
138 wfGetLBFactory()->commitMasterChanges();
140 // Some jobs types should not run until a certain timestamp
141 $backoffs = array(); // map of (type => UNIX expiry)
142 $backoffDeltas = array(); // map of (type => seconds)
143 $wait = 'wait'; // block to read backoffs the first time
147 $flags = JobQueueGroup
::USE_CACHE
;
148 $startTime = microtime( true ); // time since jobs started running
149 $checkLagPeriod = 1.0; // check slave lag this many seconds
150 $lastCheckTime = 1; // timestamp of last slave check
152 // Sync the persistent backoffs with concurrent runners
153 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
154 $blacklist = $noThrottle ?
array() : array_keys( $backoffs );
155 $wait = 'nowait'; // less important now
157 if ( $type === false ) {
158 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
159 } elseif ( in_array( $type, $blacklist ) ) {
160 $job = false; // requested queue in backoff state
162 $job = $group->pop( $type ); // job from a single queue
165 if ( $job ) { // found a job
166 $jType = $job->getType();
168 // Back off of certain jobs for a while (for throttling and for errors)
169 $ttw = $this->getBackoffTimeToWait( $job );
171 // Always add the delta for other runners in case the time running the
172 // job negated the backoff for each individually but not collectively.
173 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
174 ?
$backoffDeltas[$jType] +
$ttw
176 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
179 $msg = $job->toString() . " STARTING";
180 $this->logger
->debug( $msg );
181 $this->debugCallback( $msg );
184 $psection = $profiler->scopedProfileIn( __METHOD__
. '-' . $jType );
185 $jobStartTime = microtime( true );
188 $status = $job->run();
189 $error = $job->getLastError();
190 $this->commitMasterChanges( $job );
191 } catch ( Exception
$e ) {
192 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
194 $error = get_class( $e ) . ': ' . $e->getMessage();
195 MWExceptionHandler
::logException( $e );
197 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
198 $timeMsTotal +
= $timeMs;
199 $profiler->scopedProfileOut( $psection );
201 // Mark the job as done on success or when the job cannot be retried
202 if ( $status !== false ||
!$job->allowRetries() ) {
203 $group->ack( $job ); // done
206 // Back off of certain jobs for a while (for throttling and for errors)
207 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
208 $ttw = max( $ttw, 30 ); // too many errors
209 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
210 ?
$backoffDeltas[$jType] +
$ttw
214 if ( $status === false ) {
215 $msg = $job->toString() . " t=$timeMs error={$error}";
216 $this->logger
->error( $msg );
217 $this->debugCallback( $msg );
219 $msg = $job->toString() . " t=$timeMs good";
220 $this->logger
->info( $msg );
221 $this->debugCallback( $msg );
224 $response['jobs'][] = array(
226 'status' => ( $status === false ) ?
'failed' : 'ok',
231 // Break out if we hit the job count or wall time limits...
232 if ( $maxJobs && $jobsRun >= $maxJobs ) {
233 $response['reached'] = 'job-limit';
235 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
236 $response['reached'] = 'time-limit';
240 // Don't let any of the main DB slaves get backed up.
241 // This only waits for so long before exiting and letting
242 // other wikis in the farm (on different masters) get a chance.
243 $timePassed = microtime( true ) - $lastCheckTime;
244 if ( $timePassed >= $checkLagPeriod ||
$timePassed < 0 ) {
245 if ( !wfWaitForSlaves( $lastCheckTime, false, '*', $maxAllowedLag ) ) {
246 $response['reached'] = 'slave-lag-limit';
249 $lastCheckTime = microtime( true );
251 // Don't let any queue slaves/backups fall behind
252 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
253 $group->waitForBackups();
256 // Bail if near-OOM instead of in a job
257 $this->assertMemoryOK();
259 } while ( $job ); // stop when there are no jobs
261 // Sync the persistent backoffs for the next runJobs.php pass
262 if ( $backoffDeltas ) {
263 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
266 $response['backoffs'] = $backoffs;
267 $response['elapsed'] = $timeMsTotal;
274 * @return int Seconds for this runner to avoid doing more jobs of this type
275 * @see $wgJobBackoffThrottling
277 private function getBackoffTimeToWait( Job
$job ) {
278 global $wgJobBackoffThrottling;
280 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
281 $job instanceof DuplicateJob
// no work was done
283 return 0; // not throttled
286 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
287 if ( $itemsPerSecond <= 0 ) {
288 return 0; // not throttled
292 if ( $job->workItemCount() > 0 ) {
293 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
294 // use randomized rounding
295 $seconds = floor( $exactSeconds );
296 $remainder = $exactSeconds - $seconds;
297 $seconds +
= ( mt_rand() / mt_getrandmax() < $remainder ) ?
1 : 0;
300 return (int)$seconds;
304 * Get the previous backoff expiries from persistent storage
305 * On I/O or lock acquisition failure this returns the original $backoffs.
307 * @param array $backoffs Map of (job type => UNIX timestamp)
308 * @param string $mode Lock wait mode - "wait" or "nowait"
309 * @return array Map of (job type => backoff expiry timestamp)
311 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
312 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
313 if ( is_file( $file ) ) {
314 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
315 $handle = fopen( $file, 'rb' );
316 if ( !flock( $handle, LOCK_SH |
$noblock ) ) {
318 return $backoffs; // don't wait on lock
320 $content = stream_get_contents( $handle );
321 flock( $handle, LOCK_UN
);
323 $ctime = microtime( true );
324 $cBackoffs = json_decode( $content, true ) ?
: array();
325 foreach ( $cBackoffs as $type => $timestamp ) {
326 if ( $timestamp < $ctime ) {
327 unset( $cBackoffs[$type] );
331 $cBackoffs = array();
338 * Merge the current backoff expiries from persistent storage
340 * The $deltas map is set to an empty array on success.
341 * On I/O or lock acquisition failure this returns the original $backoffs.
343 * @param array $backoffs Map of (job type => UNIX timestamp)
344 * @param array $deltas Map of (job type => seconds)
345 * @param string $mode Lock wait mode - "wait" or "nowait"
346 * @return array The new backoffs account for $backoffs and the latest file data
348 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
350 return $this->loadBackoffs( $backoffs, $mode );
353 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
354 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
355 $handle = fopen( $file, 'wb+' );
356 if ( !flock( $handle, LOCK_EX |
$noblock ) ) {
358 return $backoffs; // don't wait on lock
360 $ctime = microtime( true );
361 $content = stream_get_contents( $handle );
362 $cBackoffs = json_decode( $content, true ) ?
: array();
363 foreach ( $deltas as $type => $seconds ) {
364 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
365 ?
$cBackoffs[$type] +
$seconds
368 foreach ( $cBackoffs as $type => $timestamp ) {
369 if ( $timestamp < $ctime ) {
370 unset( $cBackoffs[$type] );
373 ftruncate( $handle, 0 );
374 fwrite( $handle, json_encode( $cBackoffs ) );
375 flock( $handle, LOCK_UN
);
384 * Make sure that this script is not too close to the memory usage limit.
385 * It is better to die in between jobs than OOM right in the middle of one.
386 * @throws MWException
388 private function assertMemoryOK() {
389 static $maxBytes = null;
390 if ( $maxBytes === null ) {
392 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
393 list( , $num, $unit ) = $m;
394 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
395 $maxBytes = $num * $conv[strtolower( $unit )];
400 $usedBytes = memory_get_usage();
401 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
402 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
407 * Log the job message
408 * @param string $msg The message to log
410 private function debugCallback( $msg ) {
411 if ( $this->debug
) {
412 call_user_func_array( $this->debug
, array( wfTimestamp( TS_DB
) . " $msg\n" ) );
417 * Commit any DB master changes from a job on all load balancers
422 private function commitMasterChanges( Job
$job ) {
423 global $wgJobSerialCommitThreshold;
425 $lb = wfGetLB( wfWikiID() );
426 if ( $wgJobSerialCommitThreshold !== false ) {
427 // Generally, there is one master connection to the local DB
428 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
434 ||
!$dbwSerial->namedLocksEnqueue()
435 ||
$dbwSerial->pendingWriteQueryDuration() < $wgJobSerialCommitThreshold
437 // Writes are all to foreign DBs, named locks don't form queues,
438 // or $wgJobSerialCommitThreshold is not reached; commit changes now
439 wfGetLBFactory()->commitMasterChanges();
443 $ms = intval( 1000 * $dbwSerial->pendingWriteQueryDuration() );
444 $msg = $job->toString() . " COMMIT ENQUEUED [{$ms}ms of writes]";
445 $this->logger
->info( $msg );
446 $this->debugCallback( $msg );
448 // Wait for an exclusive lock to commit
449 if ( !$dbwSerial->lock( 'jobrunner-serial-commit', __METHOD__
, 30 ) ) {
450 // This will trigger a rollback in the main loop
451 throw new DBError( $dbwSerial, "Timed out waiting on commit queue." );
453 // Wait for the generic slave to catch up
454 $pos = $lb->getMasterPos();
456 $lb->waitForOne( $pos );
460 // Re-ping all masters with transactions. This throws DBError if some
461 // connection died while waiting on locks/slaves, triggering a rollback.
462 wfGetLBFactory()->forEachLB( function( LoadBalancer
$lb ) use ( $fname ) {
463 $lb->forEachOpenConnection( function( DatabaseBase
$conn ) use ( $fname ) {
464 if ( $conn->writesOrCallbacksPending() ) {
465 $conn->query( "SELECT 1", $fname );
470 // Actually commit the DB master changes
471 wfGetLBFactory()->commitMasterChanges();
474 $dbwSerial->unlock( 'jobrunner-serial-commit', __METHOD__
);