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 // Bail out if in read-only mode
107 if ( wfReadOnly() ) {
108 $response['reached'] = 'read-only';
112 $profiler = Profiler
::instance();
114 // Catch huge single updates that lead to slave lag
115 $trxProfiler = $profiler->getTransactionProfiler();
116 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
117 $trxProfiler->setExpectations( $wgTrxProfilerLimits['JobRunner'], __METHOD__
);
119 // Bail out if there is too much DB lag.
120 // This check should not block as we want to try other wiki queues.
122 list( , $maxLag ) = wfGetLB( wfWikiID() )->getMaxLag();
123 if ( $maxLag >= $maxAllowedLag ) {
124 $response['reached'] = 'slave-lag-limit';
128 $group = JobQueueGroup
::singleton();
130 // Flush any pending DB writes for sanity
131 wfGetLBFactory()->commitAll();
133 // Some jobs types should not run until a certain timestamp
134 $backoffs = array(); // map of (type => UNIX expiry)
135 $backoffDeltas = array(); // map of (type => seconds)
136 $wait = 'wait'; // block to read backoffs the first time
140 $flags = JobQueueGroup
::USE_CACHE
;
141 $startTime = microtime( true ); // time since jobs started running
142 $checkLagPeriod = 1.0; // check slave lag this many seconds
143 $lastCheckTime = 1; // timestamp of last slave check
145 // Sync the persistent backoffs with concurrent runners
146 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
147 $blacklist = $noThrottle ?
array() : array_keys( $backoffs );
148 $wait = 'nowait'; // less important now
150 if ( $type === false ) {
151 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
152 } elseif ( in_array( $type, $blacklist ) ) {
153 $job = false; // requested queue in backoff state
155 $job = $group->pop( $type ); // job from a single queue
158 if ( $job ) { // found a job
159 $jType = $job->getType();
161 // Back off of certain jobs for a while (for throttling and for errors)
162 $ttw = $this->getBackoffTimeToWait( $job );
164 // Always add the delta for other runners in case the time running the
165 // job negated the backoff for each individually but not collectively.
166 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
167 ?
$backoffDeltas[$jType] +
$ttw
169 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
172 $msg = $job->toString() . " STARTING";
173 $this->logger
->debug( $msg );
174 $this->debugCallback( $msg );
177 $psection = $profiler->scopedProfileIn( __METHOD__
. '-' . $jType );
178 $jobStartTime = microtime( true );
181 $status = $job->run();
182 $error = $job->getLastError();
183 $this->commitMasterChanges( $job );
185 DeferredUpdates
::doUpdates();
186 $this->commitMasterChanges( $job );
187 } catch ( Exception
$e ) {
188 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
190 $error = get_class( $e ) . ': ' . $e->getMessage();
191 MWExceptionHandler
::logException( $e );
193 // Commit all outstanding connections that are in a transaction
194 // to get a fresh repeatable read snapshot on every connection.
195 // This is important because if you have an old snapshot on the
196 // database you could run the job incorrectly. Its possible, for
197 // example, to pick up a RefreshLinksJob for a new page that isn't
198 // even visible to the snapshot. The snapshot could have been
199 // created before the page. Fresh snapshots will see the page.
200 wfGetLBFactory()->commitAll();
201 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
202 $timeMsTotal +
= $timeMs;
203 $profiler->scopedProfileOut( $psection );
205 // Mark the job as done on success or when the job cannot be retried
206 if ( $status !== false ||
!$job->allowRetries() ) {
207 $group->ack( $job ); // done
210 // Back off of certain jobs for a while (for throttling and for errors)
211 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
212 $ttw = max( $ttw, 30 ); // too many errors
213 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
214 ?
$backoffDeltas[$jType] +
$ttw
218 if ( $status === false ) {
219 $msg = $job->toString() . " t=$timeMs error={$error}";
220 $this->logger
->error( $msg );
221 $this->debugCallback( $msg );
223 $msg = $job->toString() . " t=$timeMs good";
224 $this->logger
->info( $msg );
225 $this->debugCallback( $msg );
228 $response['jobs'][] = array(
230 'status' => ( $status === false ) ?
'failed' : 'ok',
235 // Break out if we hit the job count or wall time limits...
236 if ( $maxJobs && $jobsRun >= $maxJobs ) {
237 $response['reached'] = 'job-limit';
239 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
240 $response['reached'] = 'time-limit';
244 // Don't let any of the main DB slaves get backed up.
245 // This only waits for so long before exiting and letting
246 // other wikis in the farm (on different masters) get a chance.
247 $timePassed = microtime( true ) - $lastCheckTime;
248 if ( $timePassed >= $checkLagPeriod ||
$timePassed < 0 ) {
249 if ( !wfWaitForSlaves( $lastCheckTime, false, '*', $maxAllowedLag ) ) {
250 $response['reached'] = 'slave-lag-limit';
253 $lastCheckTime = microtime( true );
255 // Don't let any queue slaves/backups fall behind
256 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
257 $group->waitForBackups();
260 // Bail if near-OOM instead of in a job
261 $this->assertMemoryOK();
263 } while ( $job ); // stop when there are no jobs
265 // Sync the persistent backoffs for the next runJobs.php pass
266 if ( $backoffDeltas ) {
267 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
270 $response['backoffs'] = $backoffs;
271 $response['elapsed'] = $timeMsTotal;
278 * @return int Seconds for this runner to avoid doing more jobs of this type
279 * @see $wgJobBackoffThrottling
281 private function getBackoffTimeToWait( Job
$job ) {
282 global $wgJobBackoffThrottling;
284 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
285 $job instanceof DuplicateJob
// no work was done
287 return 0; // not throttled
290 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
291 if ( $itemsPerSecond <= 0 ) {
292 return 0; // not throttled
296 if ( $job->workItemCount() > 0 ) {
297 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
298 // use randomized rounding
299 $seconds = floor( $exactSeconds );
300 $remainder = $exactSeconds - $seconds;
301 $seconds +
= ( mt_rand() / mt_getrandmax() < $remainder ) ?
1 : 0;
304 return (int)$seconds;
308 * Get the previous backoff expiries from persistent storage
309 * On I/O or lock acquisition failure this returns the original $backoffs.
311 * @param array $backoffs Map of (job type => UNIX timestamp)
312 * @param string $mode Lock wait mode - "wait" or "nowait"
313 * @return array Map of (job type => backoff expiry timestamp)
315 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
316 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
317 if ( is_file( $file ) ) {
318 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
319 $handle = fopen( $file, 'rb' );
320 if ( !flock( $handle, LOCK_SH |
$noblock ) ) {
322 return $backoffs; // don't wait on lock
324 $content = stream_get_contents( $handle );
325 flock( $handle, LOCK_UN
);
327 $ctime = microtime( true );
328 $cBackoffs = json_decode( $content, true ) ?
: array();
329 foreach ( $cBackoffs as $type => $timestamp ) {
330 if ( $timestamp < $ctime ) {
331 unset( $cBackoffs[$type] );
335 $cBackoffs = array();
342 * Merge the current backoff expiries from persistent storage
344 * The $deltas map is set to an empty array on success.
345 * On I/O or lock acquisition failure this returns the original $backoffs.
347 * @param array $backoffs Map of (job type => UNIX timestamp)
348 * @param array $deltas Map of (job type => seconds)
349 * @param string $mode Lock wait mode - "wait" or "nowait"
350 * @return array The new backoffs account for $backoffs and the latest file data
352 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
354 return $this->loadBackoffs( $backoffs, $mode );
357 $noblock = ( $mode === 'nowait' ) ? LOCK_NB
: 0;
358 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
359 $handle = fopen( $file, 'wb+' );
360 if ( !flock( $handle, LOCK_EX |
$noblock ) ) {
362 return $backoffs; // don't wait on lock
364 $ctime = microtime( true );
365 $content = stream_get_contents( $handle );
366 $cBackoffs = json_decode( $content, true ) ?
: array();
367 foreach ( $deltas as $type => $seconds ) {
368 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
369 ?
$cBackoffs[$type] +
$seconds
372 foreach ( $cBackoffs as $type => $timestamp ) {
373 if ( $timestamp < $ctime ) {
374 unset( $cBackoffs[$type] );
377 ftruncate( $handle, 0 );
378 fwrite( $handle, json_encode( $cBackoffs ) );
379 flock( $handle, LOCK_UN
);
388 * Make sure that this script is not too close to the memory usage limit.
389 * It is better to die in between jobs than OOM right in the middle of one.
390 * @throws MWException
392 private function assertMemoryOK() {
393 static $maxBytes = null;
394 if ( $maxBytes === null ) {
396 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
397 list( , $num, $unit ) = $m;
398 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
399 $maxBytes = $num * $conv[strtolower( $unit )];
404 $usedBytes = memory_get_usage();
405 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
406 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
411 * Log the job message
412 * @param string $msg The message to log
414 private function debugCallback( $msg ) {
415 if ( $this->debug
) {
416 call_user_func_array( $this->debug
, array( wfTimestamp( TS_DB
) . " $msg\n" ) );
421 * Issue a commit on all masters who are currently in a transaction and have
422 * made changes to the database. It also supports sometimes waiting for the
423 * local wiki's slaves to catch up. See the documentation for
424 * $wgJobSerialCommitThreshold for more.
429 private function commitMasterChanges( Job
$job ) {
430 global $wgJobSerialCommitThreshold;
432 $lb = wfGetLB( wfWikiID() );
433 if ( $wgJobSerialCommitThreshold !== false ) {
434 // Generally, there is one master connection to the local DB
435 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
441 ||
!$dbwSerial->namedLocksEnqueue()
442 ||
$dbwSerial->pendingWriteQueryDuration() < $wgJobSerialCommitThreshold
444 // Writes are all to foreign DBs, named locks don't form queues,
445 // or $wgJobSerialCommitThreshold is not reached; commit changes now
446 wfGetLBFactory()->commitMasterChanges();
450 $ms = intval( 1000 * $dbwSerial->pendingWriteQueryDuration() );
451 $msg = $job->toString() . " COMMIT ENQUEUED [{$ms}ms of writes]";
452 $this->logger
->info( $msg );
453 $this->debugCallback( $msg );
455 // Wait for an exclusive lock to commit
456 if ( !$dbwSerial->lock( 'jobrunner-serial-commit', __METHOD__
, 30 ) ) {
457 // This will trigger a rollback in the main loop
458 throw new DBError( $dbwSerial, "Timed out waiting on commit queue." );
460 // Wait for the generic slave to catch up
461 $pos = $lb->getMasterPos();
463 $lb->waitForOne( $pos );
467 // Re-ping all masters with transactions. This throws DBError if some
468 // connection died while waiting on locks/slaves, triggering a rollback.
469 wfGetLBFactory()->forEachLB( function( LoadBalancer
$lb ) use ( $fname ) {
470 $lb->forEachOpenConnection( function( DatabaseBase
$conn ) use ( $fname ) {
471 if ( $conn->writesOrCallbacksPending() ) {
472 $conn->query( "SELECT 1", $fname );
477 // Actually commit the DB master changes
478 wfGetLBFactory()->commitMasterChanges();
481 $dbwSerial->unlock( 'jobrunner-serial-commit', __METHOD__
);