Implement extension registration from an extension.json file
[mediawiki.git] / includes / jobqueue / JobRunner.php
blob8e8d69370bec3010115a25e179572068c71be313
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 /**
25 * Job queue runner utility methods
27 * @ingroup JobQueue
28 * @since 1.24
30 class JobRunner {
31 /** @var callable|null Debug output handler */
32 protected $debug;
34 /**
35 * @param callable $debug Optional debug output handler
37 public function setDebugHandler( $debug ) {
38 $this->debug = $debug;
41 /**
42 * Run jobs of the specified number/type for the specified time
44 * The response map has a 'job' field that lists status of each job, including:
45 * - type : the job type
46 * - status : ok/failed
47 * - error : any error message string
48 * - time : the job run time in ms
49 * The response map also has:
50 * - backoffs : the (job type => seconds) map of backoff times
51 * - elapsed : the total time spent running tasks in ms
52 * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit)
54 * This method outputs status information only if a debug handler was set.
55 * Any exceptions are caught and logged, but are not reported as output.
57 * @param array $options Map of parameters:
58 * - type : the job type (or false for the default types)
59 * - maxJobs : maximum number of jobs to run
60 * - maxTime : maximum time in seconds before stopping
61 * - throttle : whether to respect job backoff configuration
62 * @return array Summary response that can easily be JSON serialized
64 public function run( array $options ) {
65 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
67 $type = isset( $options['type'] ) ? $options['type'] : false;
68 $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false;
69 $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false;
70 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
72 $group = JobQueueGroup::singleton();
73 // Handle any required periodic queue maintenance
74 $count = $group->executeReadyPeriodicTasks();
75 if ( $count > 0 ) {
76 $this->runJobsLog( "Executed $count periodic queue task(s)." );
79 // Bail out if there is too much DB lag
80 list( , $maxLag ) = wfGetLBFactory()->getMainLB( wfWikiID() )->getMaxLag();
81 if ( $maxLag >= 5 ) {
82 $response['reached'] = 'slave-lag-limit';
83 return $response;
86 // Flush any pending DB writes for sanity
87 wfGetLBFactory()->commitMasterChanges();
89 // Some jobs types should not run until a certain timestamp
90 $backoffs = array(); // map of (type => UNIX expiry)
91 $backoffDeltas = array(); // map of (type => seconds)
92 $wait = 'wait'; // block to read backoffs the first time
94 $jobsRun = 0;
95 $timeMsTotal = 0;
96 $flags = JobQueueGroup::USE_CACHE;
97 $checkPeriod = 5.0; // seconds
98 $checkPhase = mt_rand( 0, 1000 * $checkPeriod ) / 1000; // avoid stampedes
99 $startTime = microtime( true ); // time since jobs started running
100 $lastTime = microtime( true ) - $checkPhase; // time since last slave check
101 do {
102 // Sync the persistent backoffs with concurrent runners
103 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
104 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
105 $wait = 'nowait'; // less important now
107 if ( $type === false ) {
108 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
109 } elseif ( in_array( $type, $blacklist ) ) {
110 $job = false; // requested queue in backoff state
111 } else {
112 $job = $group->pop( $type ); // job from a single queue
115 if ( $job ) { // found a job
116 $jType = $job->getType();
118 // Back off of certain jobs for a while (for throttling and for errors)
119 $ttw = $this->getBackoffTimeToWait( $job );
120 if ( $ttw > 0 ) {
121 // Always add the delta for other runners in case the time running the
122 // job negated the backoff for each individually but not collectively.
123 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
124 ? $backoffDeltas[$jType] + $ttw
125 : $ttw;
126 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
129 $this->runJobsLog( $job->toString() . " STARTING" );
131 // Run the job...
132 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
133 $jobStartTime = microtime( true );
134 try {
135 ++$jobsRun;
136 $status = $job->run();
137 $error = $job->getLastError();
138 wfGetLBFactory()->commitMasterChanges();
139 } catch ( MWException $e ) {
140 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
141 $status = false;
142 $error = get_class( $e ) . ': ' . $e->getMessage();
143 MWExceptionHandler::logException( $e );
145 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
146 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
147 $timeMsTotal += $timeMs;
149 // Mark the job as done on success or when the job cannot be retried
150 if ( $status !== false || !$job->allowRetries() ) {
151 $group->ack( $job ); // done
154 // Back off of certain jobs for a while (for throttling and for errors)
155 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
156 $ttw = max( $ttw, 30 ); // too many errors
157 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
158 ? $backoffDeltas[$jType] + $ttw
159 : $ttw;
162 if ( $status === false ) {
163 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
164 } else {
165 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
168 $response['jobs'][] = array(
169 'type' => $jType,
170 'status' => ( $status === false ) ? 'failed' : 'ok',
171 'error' => $error,
172 'time' => $timeMs
175 // Break out if we hit the job count or wall time limits...
176 if ( $maxJobs && $jobsRun >= $maxJobs ) {
177 $response['reached'] = 'job-limit';
178 break;
179 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
180 $response['reached'] = 'time-limit';
181 break;
184 // Don't let any of the main DB slaves get backed up.
185 // This only waits for so long before exiting and letting
186 // other wikis in the farm (on different masters) get a chance.
187 $timePassed = microtime( true ) - $lastTime;
188 if ( $timePassed >= 5 || $timePassed < 0 ) {
189 if ( !wfWaitForSlaves( $lastTime, false, '*', 5 ) ) {
190 $response['reached'] = 'slave-lag-limit';
191 break;
193 $lastTime = microtime( true );
195 // Don't let any queue slaves/backups fall behind
196 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
197 $group->waitForBackups();
200 // Bail if near-OOM instead of in a job
201 $this->assertMemoryOK();
203 } while ( $job ); // stop when there are no jobs
205 // Sync the persistent backoffs for the next runJobs.php pass
206 if ( $backoffDeltas ) {
207 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
210 $response['backoffs'] = $backoffs;
211 $response['elapsed'] = $timeMsTotal;
213 return $response;
217 * @param Job $job
218 * @return int Seconds for this runner to avoid doing more jobs of this type
219 * @see $wgJobBackoffThrottling
221 private function getBackoffTimeToWait( Job $job ) {
222 global $wgJobBackoffThrottling;
224 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
225 $job instanceof DuplicateJob // no work was done
227 return 0; // not throttled
230 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
231 if ( $itemsPerSecond <= 0 ) {
232 return 0; // not throttled
235 $seconds = 0;
236 if ( $job->workItemCount() > 0 ) {
237 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
238 // use randomized rounding
239 $seconds = floor( $exactSeconds );
240 $remainder = $exactSeconds - $seconds;
241 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
244 return (int)$seconds;
248 * Get the previous backoff expiries from persistent storage
249 * On I/O or lock acquisition failure this returns the original $backoffs.
251 * @param array $backoffs Map of (job type => UNIX timestamp)
252 * @param string $mode Lock wait mode - "wait" or "nowait"
253 * @return array Map of (job type => backoff expiry timestamp)
255 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
257 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
258 if ( is_file( $file ) ) {
259 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
260 $handle = fopen( $file, 'rb' );
261 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
262 fclose( $handle );
263 return $backoffs; // don't wait on lock
265 $content = stream_get_contents( $handle );
266 flock( $handle, LOCK_UN );
267 fclose( $handle );
268 $ctime = microtime( true );
269 $cBackoffs = json_decode( $content, true ) ?: array();
270 foreach ( $cBackoffs as $type => $timestamp ) {
271 if ( $timestamp < $ctime ) {
272 unset( $cBackoffs[$type] );
275 } else {
276 $cBackoffs = array();
279 return $cBackoffs;
283 * Merge the current backoff expiries from persistent storage
285 * The $deltas map is set to an empty array on success.
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 array $deltas Map of (job type => seconds)
290 * @param string $mode Lock wait mode - "wait" or "nowait"
291 * @return array The new backoffs account for $backoffs and the latest file data
293 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
295 if ( !$deltas ) {
296 return $this->loadBackoffs( $backoffs, $mode );
299 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
300 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
301 $handle = fopen( $file, 'wb+' );
302 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
303 fclose( $handle );
304 return $backoffs; // don't wait on lock
306 $ctime = microtime( true );
307 $content = stream_get_contents( $handle );
308 $cBackoffs = json_decode( $content, true ) ?: array();
309 foreach ( $deltas as $type => $seconds ) {
310 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
311 ? $cBackoffs[$type] + $seconds
312 : $ctime + $seconds;
314 foreach ( $cBackoffs as $type => $timestamp ) {
315 if ( $timestamp < $ctime ) {
316 unset( $cBackoffs[$type] );
319 ftruncate( $handle, 0 );
320 fwrite( $handle, json_encode( $cBackoffs ) );
321 flock( $handle, LOCK_UN );
322 fclose( $handle );
324 $deltas = array();
326 return $cBackoffs;
330 * Make sure that this script is not too close to the memory usage limit.
331 * It is better to die in between jobs than OOM right in the middle of one.
332 * @throws MWException
334 private function assertMemoryOK() {
335 static $maxBytes = null;
336 if ( $maxBytes === null ) {
337 $m = array();
338 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
339 list( , $num, $unit ) = $m;
340 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
341 $maxBytes = $num * $conv[strtolower( $unit )];
342 } else {
343 $maxBytes = 0;
346 $usedBytes = memory_get_usage();
347 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
348 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
353 * Log the job message
354 * @param string $msg The message to log
356 private function runJobsLog( $msg ) {
357 if ( $this->debug ) {
358 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
360 wfDebugLog( 'runJobs', $msg );