Fix hook situation for Skin::doEditSectionLink
[mediawiki.git] / includes / jobqueue / JobRunner.php
blob091e648d7a261531278efcf598eea97a583fa9b1
1 <?php
2 /**
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
20 * @file
21 * @ingroup JobQueue
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
27 /**
28 * Job queue runner utility methods
30 * @ingroup JobQueue
31 * @since 1.24
33 class JobRunner implements LoggerAwareInterface {
34 /** @var callable|null Debug output handler */
35 protected $debug;
37 /**
38 * @param callable $debug Optional debug output handler
40 public function setDebugHandler( $debug ) {
41 $this->debug = $debug;
44 /**
45 * @var LoggerInterface $logger
47 protected $logger;
49 /**
50 * @param LoggerInterface $logger
52 public function setLogger( LoggerInterface $logger ) {
53 $this->logger = $logger;
56 /**
57 * @param LoggerInterface $logger
59 public function __construct( LoggerInterface $logger = null ) {
60 if ( $logger === null ) {
61 $logger = MWLoggerFactory::getInstance( 'runJobs' );
63 $this->setLogger( $logger );
66 /**
67 * Run jobs of the specified number/type for the specified time
69 * The response map has a 'job' field that lists status of each job, including:
70 * - type : the job type
71 * - status : ok/failed
72 * - error : any error message string
73 * - time : the job run time in ms
74 * The response map also has:
75 * - backoffs : the (job type => seconds) map of backoff times
76 * - elapsed : the total time spent running tasks in ms
77 * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit)
79 * This method outputs status information only if a debug handler was set.
80 * Any exceptions are caught and logged, but are not reported as output.
82 * @param array $options Map of parameters:
83 * - type : the job type (or false for the default types)
84 * - maxJobs : maximum number of jobs to run
85 * - maxTime : maximum time in seconds before stopping
86 * - throttle : whether to respect job backoff configuration
87 * @return array Summary response that can easily be JSON serialized
89 public function run( array $options ) {
90 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
92 $type = isset( $options['type'] ) ? $options['type'] : false;
93 $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false;
94 $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false;
95 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
97 $group = JobQueueGroup::singleton();
98 // Handle any required periodic queue maintenance
99 $count = $group->executeReadyPeriodicTasks();
100 if ( $count > 0 ) {
101 $msg = "Executed $count periodic queue task(s).";
102 $this->logger->debug( $msg );
103 $this->debugCallback( $msg );
106 // Bail out if in read-only mode
107 if ( wfReadOnly() ) {
108 $response['reached'] = 'read-only';
109 return $response;
112 // Bail out if there is too much DB lag
113 list( , $maxLag ) = wfGetLBFactory()->getMainLB( wfWikiID() )->getMaxLag();
114 if ( $maxLag >= 5 ) {
115 $response['reached'] = 'slave-lag-limit';
116 return $response;
119 // Flush any pending DB writes for sanity
120 wfGetLBFactory()->commitMasterChanges();
122 // Some jobs types should not run until a certain timestamp
123 $backoffs = array(); // map of (type => UNIX expiry)
124 $backoffDeltas = array(); // map of (type => seconds)
125 $wait = 'wait'; // block to read backoffs the first time
127 $jobsRun = 0;
128 $timeMsTotal = 0;
129 $flags = JobQueueGroup::USE_CACHE;
130 $checkPeriod = 5.0; // seconds
131 $checkPhase = mt_rand( 0, 1000 * $checkPeriod ) / 1000; // avoid stampedes
132 $startTime = microtime( true ); // time since jobs started running
133 $lastTime = microtime( true ) - $checkPhase; // time since last slave check
134 do {
135 // Sync the persistent backoffs with concurrent runners
136 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
137 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
138 $wait = 'nowait'; // less important now
140 if ( $type === false ) {
141 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
142 } elseif ( in_array( $type, $blacklist ) ) {
143 $job = false; // requested queue in backoff state
144 } else {
145 $job = $group->pop( $type ); // job from a single queue
148 if ( $job ) { // found a job
149 $jType = $job->getType();
151 // Back off of certain jobs for a while (for throttling and for errors)
152 $ttw = $this->getBackoffTimeToWait( $job );
153 if ( $ttw > 0 ) {
154 // Always add the delta for other runners in case the time running the
155 // job negated the backoff for each individually but not collectively.
156 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
157 ? $backoffDeltas[$jType] + $ttw
158 : $ttw;
159 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
162 $msg = $job->toString() . " STARTING";
163 $this->logger->info( $msg );
164 $this->debugCallback( $msg );
166 // Run the job...
167 $jobStartTime = microtime( true );
168 try {
169 ++$jobsRun;
170 $status = $job->run();
171 $error = $job->getLastError();
172 wfGetLBFactory()->commitMasterChanges();
173 } catch ( Exception $e ) {
174 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
175 $status = false;
176 $error = get_class( $e ) . ': ' . $e->getMessage();
177 MWExceptionHandler::logException( $e );
179 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
180 $timeMsTotal += $timeMs;
182 // Mark the job as done on success or when the job cannot be retried
183 if ( $status !== false || !$job->allowRetries() ) {
184 $group->ack( $job ); // done
187 // Back off of certain jobs for a while (for throttling and for errors)
188 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
189 $ttw = max( $ttw, 30 ); // too many errors
190 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
191 ? $backoffDeltas[$jType] + $ttw
192 : $ttw;
195 if ( $status === false ) {
196 $msg = $job->toString() . " t=$timeMs error={$error}";
197 $this->logger->error( $msg );
198 $this->debugCallback( $msg );
199 } else {
200 $msg = $job->toString() . " t=$timeMs good";
201 $this->logger->info( $msg );
202 $this->debugCallback( $msg );
205 $response['jobs'][] = array(
206 'type' => $jType,
207 'status' => ( $status === false ) ? 'failed' : 'ok',
208 'error' => $error,
209 'time' => $timeMs
212 // Break out if we hit the job count or wall time limits...
213 if ( $maxJobs && $jobsRun >= $maxJobs ) {
214 $response['reached'] = 'job-limit';
215 break;
216 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
217 $response['reached'] = 'time-limit';
218 break;
221 // Don't let any of the main DB slaves get backed up.
222 // This only waits for so long before exiting and letting
223 // other wikis in the farm (on different masters) get a chance.
224 $timePassed = microtime( true ) - $lastTime;
225 if ( $timePassed >= 5 || $timePassed < 0 ) {
226 if ( !wfWaitForSlaves( $lastTime, false, '*', 5 ) ) {
227 $response['reached'] = 'slave-lag-limit';
228 break;
230 $lastTime = microtime( true );
232 // Don't let any queue slaves/backups fall behind
233 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
234 $group->waitForBackups();
237 // Bail if near-OOM instead of in a job
238 $this->assertMemoryOK();
240 } while ( $job ); // stop when there are no jobs
242 // Sync the persistent backoffs for the next runJobs.php pass
243 if ( $backoffDeltas ) {
244 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
247 $response['backoffs'] = $backoffs;
248 $response['elapsed'] = $timeMsTotal;
250 return $response;
254 * @param Job $job
255 * @return int Seconds for this runner to avoid doing more jobs of this type
256 * @see $wgJobBackoffThrottling
258 private function getBackoffTimeToWait( Job $job ) {
259 global $wgJobBackoffThrottling;
261 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
262 $job instanceof DuplicateJob // no work was done
264 return 0; // not throttled
267 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
268 if ( $itemsPerSecond <= 0 ) {
269 return 0; // not throttled
272 $seconds = 0;
273 if ( $job->workItemCount() > 0 ) {
274 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
275 // use randomized rounding
276 $seconds = floor( $exactSeconds );
277 $remainder = $exactSeconds - $seconds;
278 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
281 return (int)$seconds;
285 * Get the previous backoff expiries from persistent storage
286 * On I/O or lock acquisition failure this returns the original $backoffs.
288 * @param array $backoffs Map of (job type => UNIX timestamp)
289 * @param string $mode Lock wait mode - "wait" or "nowait"
290 * @return array Map of (job type => backoff expiry timestamp)
292 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
294 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
295 if ( is_file( $file ) ) {
296 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
297 $handle = fopen( $file, 'rb' );
298 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
299 fclose( $handle );
300 return $backoffs; // don't wait on lock
302 $content = stream_get_contents( $handle );
303 flock( $handle, LOCK_UN );
304 fclose( $handle );
305 $ctime = microtime( true );
306 $cBackoffs = json_decode( $content, true ) ?: array();
307 foreach ( $cBackoffs as $type => $timestamp ) {
308 if ( $timestamp < $ctime ) {
309 unset( $cBackoffs[$type] );
312 } else {
313 $cBackoffs = array();
316 return $cBackoffs;
320 * Merge the current backoff expiries from persistent storage
322 * The $deltas map is set to an empty array on success.
323 * On I/O or lock acquisition failure this returns the original $backoffs.
325 * @param array $backoffs Map of (job type => UNIX timestamp)
326 * @param array $deltas Map of (job type => seconds)
327 * @param string $mode Lock wait mode - "wait" or "nowait"
328 * @return array The new backoffs account for $backoffs and the latest file data
330 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
332 if ( !$deltas ) {
333 return $this->loadBackoffs( $backoffs, $mode );
336 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
337 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
338 $handle = fopen( $file, 'wb+' );
339 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
340 fclose( $handle );
341 return $backoffs; // don't wait on lock
343 $ctime = microtime( true );
344 $content = stream_get_contents( $handle );
345 $cBackoffs = json_decode( $content, true ) ?: array();
346 foreach ( $deltas as $type => $seconds ) {
347 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
348 ? $cBackoffs[$type] + $seconds
349 : $ctime + $seconds;
351 foreach ( $cBackoffs as $type => $timestamp ) {
352 if ( $timestamp < $ctime ) {
353 unset( $cBackoffs[$type] );
356 ftruncate( $handle, 0 );
357 fwrite( $handle, json_encode( $cBackoffs ) );
358 flock( $handle, LOCK_UN );
359 fclose( $handle );
361 $deltas = array();
363 return $cBackoffs;
367 * Make sure that this script is not too close to the memory usage limit.
368 * It is better to die in between jobs than OOM right in the middle of one.
369 * @throws MWException
371 private function assertMemoryOK() {
372 static $maxBytes = null;
373 if ( $maxBytes === null ) {
374 $m = array();
375 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
376 list( , $num, $unit ) = $m;
377 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
378 $maxBytes = $num * $conv[strtolower( $unit )];
379 } else {
380 $maxBytes = 0;
383 $usedBytes = memory_get_usage();
384 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
385 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
390 * Log the job message
391 * @param string $msg The message to log
393 private function debugCallback( $msg ) {
394 if ( $this->debug ) {
395 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );