SpecialTrackingCategories: Read from the extension registry
[lhc/web/wiklou.git] / includes / jobqueue / JobRunner.php
1 <?php
2 /**
3 * Job queue runner utility methods
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup JobQueue
22 */
23
24 /**
25 * Job queue runner utility methods
26 *
27 * @ingroup JobQueue
28 * @since 1.24
29 */
30 class JobRunner {
31 /** @var callable|null Debug output handler */
32 protected $debug;
33
34 /**
35 * @param callable $debug Optional debug output handler
36 */
37 public function setDebugHandler( $debug ) {
38 $this->debug = $debug;
39 }
40
41 /**
42 * Run jobs of the specified number/type for the specified time
43 *
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)
53 *
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.
56 *
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
63 */
64 public function run( array $options ) {
65 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
66
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'];
71
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)." );
77 }
78
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;
84 }
85
86 // Flush any pending DB writes for sanity
87 wfGetLBFactory()->commitMasterChanges();
88
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
93
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
106
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
113 }
114
115 if ( $job ) { // found a job
116 $jType = $job->getType();
117
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 );
127 }
128
129 $this->runJobsLog( $job->toString() . " STARTING" );
130
131 // Run the job...
132 $jobStartTime = microtime( true );
133 try {
134 ++$jobsRun;
135 $status = $job->run();
136 $error = $job->getLastError();
137 wfGetLBFactory()->commitMasterChanges();
138 } catch ( Exception $e ) {
139 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
140 $status = false;
141 $error = get_class( $e ) . ': ' . $e->getMessage();
142 MWExceptionHandler::logException( $e );
143 }
144 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
145 $timeMsTotal += $timeMs;
146
147 // Mark the job as done on success or when the job cannot be retried
148 if ( $status !== false || !$job->allowRetries() ) {
149 $group->ack( $job ); // done
150 }
151
152 // Back off of certain jobs for a while (for throttling and for errors)
153 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
154 $ttw = max( $ttw, 30 ); // too many errors
155 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
156 ? $backoffDeltas[$jType] + $ttw
157 : $ttw;
158 }
159
160 if ( $status === false ) {
161 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
162 } else {
163 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
164 }
165
166 $response['jobs'][] = array(
167 'type' => $jType,
168 'status' => ( $status === false ) ? 'failed' : 'ok',
169 'error' => $error,
170 'time' => $timeMs
171 );
172
173 // Break out if we hit the job count or wall time limits...
174 if ( $maxJobs && $jobsRun >= $maxJobs ) {
175 $response['reached'] = 'job-limit';
176 break;
177 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
178 $response['reached'] = 'time-limit';
179 break;
180 }
181
182 // Don't let any of the main DB slaves get backed up.
183 // This only waits for so long before exiting and letting
184 // other wikis in the farm (on different masters) get a chance.
185 $timePassed = microtime( true ) - $lastTime;
186 if ( $timePassed >= 5 || $timePassed < 0 ) {
187 if ( !wfWaitForSlaves( $lastTime, false, '*', 5 ) ) {
188 $response['reached'] = 'slave-lag-limit';
189 break;
190 }
191 $lastTime = microtime( true );
192 }
193 // Don't let any queue slaves/backups fall behind
194 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
195 $group->waitForBackups();
196 }
197
198 // Bail if near-OOM instead of in a job
199 $this->assertMemoryOK();
200 }
201 } while ( $job ); // stop when there are no jobs
202
203 // Sync the persistent backoffs for the next runJobs.php pass
204 if ( $backoffDeltas ) {
205 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
206 }
207
208 $response['backoffs'] = $backoffs;
209 $response['elapsed'] = $timeMsTotal;
210
211 return $response;
212 }
213
214 /**
215 * @param Job $job
216 * @return int Seconds for this runner to avoid doing more jobs of this type
217 * @see $wgJobBackoffThrottling
218 */
219 private function getBackoffTimeToWait( Job $job ) {
220 global $wgJobBackoffThrottling;
221
222 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
223 $job instanceof DuplicateJob // no work was done
224 ) {
225 return 0; // not throttled
226 }
227
228 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
229 if ( $itemsPerSecond <= 0 ) {
230 return 0; // not throttled
231 }
232
233 $seconds = 0;
234 if ( $job->workItemCount() > 0 ) {
235 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
236 // use randomized rounding
237 $seconds = floor( $exactSeconds );
238 $remainder = $exactSeconds - $seconds;
239 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
240 }
241
242 return (int)$seconds;
243 }
244
245 /**
246 * Get the previous backoff expiries from persistent storage
247 * On I/O or lock acquisition failure this returns the original $backoffs.
248 *
249 * @param array $backoffs Map of (job type => UNIX timestamp)
250 * @param string $mode Lock wait mode - "wait" or "nowait"
251 * @return array Map of (job type => backoff expiry timestamp)
252 */
253 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
254
255 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
256 if ( is_file( $file ) ) {
257 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
258 $handle = fopen( $file, 'rb' );
259 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
260 fclose( $handle );
261 return $backoffs; // don't wait on lock
262 }
263 $content = stream_get_contents( $handle );
264 flock( $handle, LOCK_UN );
265 fclose( $handle );
266 $ctime = microtime( true );
267 $cBackoffs = json_decode( $content, true ) ?: array();
268 foreach ( $cBackoffs as $type => $timestamp ) {
269 if ( $timestamp < $ctime ) {
270 unset( $cBackoffs[$type] );
271 }
272 }
273 } else {
274 $cBackoffs = array();
275 }
276
277 return $cBackoffs;
278 }
279
280 /**
281 * Merge the current backoff expiries from persistent storage
282 *
283 * The $deltas map is set to an empty array on success.
284 * On I/O or lock acquisition failure this returns the original $backoffs.
285 *
286 * @param array $backoffs Map of (job type => UNIX timestamp)
287 * @param array $deltas Map of (job type => seconds)
288 * @param string $mode Lock wait mode - "wait" or "nowait"
289 * @return array The new backoffs account for $backoffs and the latest file data
290 */
291 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
292
293 if ( !$deltas ) {
294 return $this->loadBackoffs( $backoffs, $mode );
295 }
296
297 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
298 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
299 $handle = fopen( $file, 'wb+' );
300 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
301 fclose( $handle );
302 return $backoffs; // don't wait on lock
303 }
304 $ctime = microtime( true );
305 $content = stream_get_contents( $handle );
306 $cBackoffs = json_decode( $content, true ) ?: array();
307 foreach ( $deltas as $type => $seconds ) {
308 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
309 ? $cBackoffs[$type] + $seconds
310 : $ctime + $seconds;
311 }
312 foreach ( $cBackoffs as $type => $timestamp ) {
313 if ( $timestamp < $ctime ) {
314 unset( $cBackoffs[$type] );
315 }
316 }
317 ftruncate( $handle, 0 );
318 fwrite( $handle, json_encode( $cBackoffs ) );
319 flock( $handle, LOCK_UN );
320 fclose( $handle );
321
322 $deltas = array();
323
324 return $cBackoffs;
325 }
326
327 /**
328 * Make sure that this script is not too close to the memory usage limit.
329 * It is better to die in between jobs than OOM right in the middle of one.
330 * @throws MWException
331 */
332 private function assertMemoryOK() {
333 static $maxBytes = null;
334 if ( $maxBytes === null ) {
335 $m = array();
336 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
337 list( , $num, $unit ) = $m;
338 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
339 $maxBytes = $num * $conv[strtolower( $unit )];
340 } else {
341 $maxBytes = 0;
342 }
343 }
344 $usedBytes = memory_get_usage();
345 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
346 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
347 }
348 }
349
350 /**
351 * Log the job message
352 * @param string $msg The message to log
353 */
354 private function runJobsLog( $msg ) {
355 if ( $this->debug ) {
356 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
357 }
358 wfDebugLog( 'runJobs', $msg );
359 }
360 }