ef0f08789000bbf367132f2532cef28775b888b5
[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 in read-only mode
80 if ( wfReadOnly() ) {
81 $response['reached'] = 'read-only';
82 return $response;
83 }
84
85 // Bail out if there is too much DB lag
86 list( , $maxLag ) = wfGetLBFactory()->getMainLB( wfWikiID() )->getMaxLag();
87 if ( $maxLag >= 5 ) {
88 $response['reached'] = 'slave-lag-limit';
89 return $response;
90 }
91
92 // Flush any pending DB writes for sanity
93 wfGetLBFactory()->commitMasterChanges();
94
95 // Some jobs types should not run until a certain timestamp
96 $backoffs = array(); // map of (type => UNIX expiry)
97 $backoffDeltas = array(); // map of (type => seconds)
98 $wait = 'wait'; // block to read backoffs the first time
99
100 $jobsRun = 0;
101 $timeMsTotal = 0;
102 $flags = JobQueueGroup::USE_CACHE;
103 $checkPeriod = 5.0; // seconds
104 $checkPhase = mt_rand( 0, 1000 * $checkPeriod ) / 1000; // avoid stampedes
105 $startTime = microtime( true ); // time since jobs started running
106 $lastTime = microtime( true ) - $checkPhase; // time since last slave check
107 do {
108 // Sync the persistent backoffs with concurrent runners
109 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
110 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
111 $wait = 'nowait'; // less important now
112
113 if ( $type === false ) {
114 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
115 } elseif ( in_array( $type, $blacklist ) ) {
116 $job = false; // requested queue in backoff state
117 } else {
118 $job = $group->pop( $type ); // job from a single queue
119 }
120
121 if ( $job ) { // found a job
122 $jType = $job->getType();
123
124 // Back off of certain jobs for a while (for throttling and for errors)
125 $ttw = $this->getBackoffTimeToWait( $job );
126 if ( $ttw > 0 ) {
127 // Always add the delta for other runners in case the time running the
128 // job negated the backoff for each individually but not collectively.
129 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
130 ? $backoffDeltas[$jType] + $ttw
131 : $ttw;
132 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
133 }
134
135 $this->runJobsLog( $job->toString() . " STARTING" );
136
137 // Run the job...
138 $jobStartTime = microtime( true );
139 try {
140 ++$jobsRun;
141 $status = $job->run();
142 $error = $job->getLastError();
143 wfGetLBFactory()->commitMasterChanges();
144 } catch ( Exception $e ) {
145 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
146 $status = false;
147 $error = get_class( $e ) . ': ' . $e->getMessage();
148 MWExceptionHandler::logException( $e );
149 }
150 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
151 $timeMsTotal += $timeMs;
152
153 // Mark the job as done on success or when the job cannot be retried
154 if ( $status !== false || !$job->allowRetries() ) {
155 $group->ack( $job ); // done
156 }
157
158 // Back off of certain jobs for a while (for throttling and for errors)
159 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
160 $ttw = max( $ttw, 30 ); // too many errors
161 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
162 ? $backoffDeltas[$jType] + $ttw
163 : $ttw;
164 }
165
166 if ( $status === false ) {
167 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
168 } else {
169 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
170 }
171
172 $response['jobs'][] = array(
173 'type' => $jType,
174 'status' => ( $status === false ) ? 'failed' : 'ok',
175 'error' => $error,
176 'time' => $timeMs
177 );
178
179 // Break out if we hit the job count or wall time limits...
180 if ( $maxJobs && $jobsRun >= $maxJobs ) {
181 $response['reached'] = 'job-limit';
182 break;
183 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
184 $response['reached'] = 'time-limit';
185 break;
186 }
187
188 // Don't let any of the main DB slaves get backed up.
189 // This only waits for so long before exiting and letting
190 // other wikis in the farm (on different masters) get a chance.
191 $timePassed = microtime( true ) - $lastTime;
192 if ( $timePassed >= 5 || $timePassed < 0 ) {
193 if ( !wfWaitForSlaves( $lastTime, false, '*', 5 ) ) {
194 $response['reached'] = 'slave-lag-limit';
195 break;
196 }
197 $lastTime = microtime( true );
198 }
199 // Don't let any queue slaves/backups fall behind
200 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
201 $group->waitForBackups();
202 }
203
204 // Bail if near-OOM instead of in a job
205 $this->assertMemoryOK();
206 }
207 } while ( $job ); // stop when there are no jobs
208
209 // Sync the persistent backoffs for the next runJobs.php pass
210 if ( $backoffDeltas ) {
211 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
212 }
213
214 $response['backoffs'] = $backoffs;
215 $response['elapsed'] = $timeMsTotal;
216
217 return $response;
218 }
219
220 /**
221 * @param Job $job
222 * @return int Seconds for this runner to avoid doing more jobs of this type
223 * @see $wgJobBackoffThrottling
224 */
225 private function getBackoffTimeToWait( Job $job ) {
226 global $wgJobBackoffThrottling;
227
228 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
229 $job instanceof DuplicateJob // no work was done
230 ) {
231 return 0; // not throttled
232 }
233
234 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
235 if ( $itemsPerSecond <= 0 ) {
236 return 0; // not throttled
237 }
238
239 $seconds = 0;
240 if ( $job->workItemCount() > 0 ) {
241 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
242 // use randomized rounding
243 $seconds = floor( $exactSeconds );
244 $remainder = $exactSeconds - $seconds;
245 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
246 }
247
248 return (int)$seconds;
249 }
250
251 /**
252 * Get the previous backoff expiries from persistent storage
253 * On I/O or lock acquisition failure this returns the original $backoffs.
254 *
255 * @param array $backoffs Map of (job type => UNIX timestamp)
256 * @param string $mode Lock wait mode - "wait" or "nowait"
257 * @return array Map of (job type => backoff expiry timestamp)
258 */
259 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
260
261 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
262 if ( is_file( $file ) ) {
263 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
264 $handle = fopen( $file, 'rb' );
265 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
266 fclose( $handle );
267 return $backoffs; // don't wait on lock
268 }
269 $content = stream_get_contents( $handle );
270 flock( $handle, LOCK_UN );
271 fclose( $handle );
272 $ctime = microtime( true );
273 $cBackoffs = json_decode( $content, true ) ?: array();
274 foreach ( $cBackoffs as $type => $timestamp ) {
275 if ( $timestamp < $ctime ) {
276 unset( $cBackoffs[$type] );
277 }
278 }
279 } else {
280 $cBackoffs = array();
281 }
282
283 return $cBackoffs;
284 }
285
286 /**
287 * Merge the current backoff expiries from persistent storage
288 *
289 * The $deltas map is set to an empty array on success.
290 * On I/O or lock acquisition failure this returns the original $backoffs.
291 *
292 * @param array $backoffs Map of (job type => UNIX timestamp)
293 * @param array $deltas Map of (job type => seconds)
294 * @param string $mode Lock wait mode - "wait" or "nowait"
295 * @return array The new backoffs account for $backoffs and the latest file data
296 */
297 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
298
299 if ( !$deltas ) {
300 return $this->loadBackoffs( $backoffs, $mode );
301 }
302
303 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
304 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
305 $handle = fopen( $file, 'wb+' );
306 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
307 fclose( $handle );
308 return $backoffs; // don't wait on lock
309 }
310 $ctime = microtime( true );
311 $content = stream_get_contents( $handle );
312 $cBackoffs = json_decode( $content, true ) ?: array();
313 foreach ( $deltas as $type => $seconds ) {
314 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
315 ? $cBackoffs[$type] + $seconds
316 : $ctime + $seconds;
317 }
318 foreach ( $cBackoffs as $type => $timestamp ) {
319 if ( $timestamp < $ctime ) {
320 unset( $cBackoffs[$type] );
321 }
322 }
323 ftruncate( $handle, 0 );
324 fwrite( $handle, json_encode( $cBackoffs ) );
325 flock( $handle, LOCK_UN );
326 fclose( $handle );
327
328 $deltas = array();
329
330 return $cBackoffs;
331 }
332
333 /**
334 * Make sure that this script is not too close to the memory usage limit.
335 * It is better to die in between jobs than OOM right in the middle of one.
336 * @throws MWException
337 */
338 private function assertMemoryOK() {
339 static $maxBytes = null;
340 if ( $maxBytes === null ) {
341 $m = array();
342 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
343 list( , $num, $unit ) = $m;
344 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
345 $maxBytes = $num * $conv[strtolower( $unit )];
346 } else {
347 $maxBytes = 0;
348 }
349 }
350 $usedBytes = memory_get_usage();
351 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
352 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
353 }
354 }
355
356 /**
357 * Log the job message
358 * @param string $msg The message to log
359 */
360 private function runJobsLog( $msg ) {
361 if ( $this->debug ) {
362 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
363 }
364 wfDebugLog( 'runJobs', $msg );
365 }
366 }