Merge "DatabaseMssql: Don't duplicate body of makeList()"
[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 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26
27 /**
28 * Job queue runner utility methods
29 *
30 * @ingroup JobQueue
31 * @since 1.24
32 */
33 class JobRunner implements LoggerAwareInterface {
34 /** @var callable|null Debug output handler */
35 protected $debug;
36
37 /**
38 * @param callable $debug Optional debug output handler
39 */
40 public function setDebugHandler( $debug ) {
41 $this->debug = $debug;
42 }
43
44 /**
45 * @var LoggerInterface $logger
46 */
47 protected $logger;
48
49 /**
50 * @param LoggerInterface $logger
51 */
52 public function setLogger( LoggerInterface $logger ) {
53 $this->logger = $logger;
54 }
55
56 /**
57 * @param LoggerInterface $logger
58 */
59 public function __construct( LoggerInterface $logger = null ) {
60 if ( $logger === null ) {
61 $logger = MWLoggerFactory::getInstance( 'runJobs' );
62 }
63 $this->setLogger( $logger );
64 }
65
66 /**
67 * Run jobs of the specified number/type for the specified time
68 *
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)
78 *
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.
81 *
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
88 */
89 public function run( array $options ) {
90 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
91
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'];
96
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 );
104 }
105
106 // Bail out if in read-only mode
107 if ( wfReadOnly() ) {
108 $response['reached'] = 'read-only';
109 return $response;
110 }
111
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;
117 }
118
119 // Flush any pending DB writes for sanity
120 wfGetLBFactory()->commitMasterChanges();
121
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
126
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
139
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
146 }
147
148 if ( $job ) { // found a job
149 $jType = $job->getType();
150
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 );
160 }
161
162 $msg = $job->toString() . " STARTING";
163 $this->logger->info( $msg );
164 $this->debugCallback( $msg );
165
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 );
178 }
179 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
180 $timeMsTotal += $timeMs;
181
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
185 }
186
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;
193 }
194
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 );
203 }
204
205 $response['jobs'][] = array(
206 'type' => $jType,
207 'status' => ( $status === false ) ? 'failed' : 'ok',
208 'error' => $error,
209 'time' => $timeMs
210 );
211
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;
219 }
220
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;
229 }
230 $lastTime = microtime( true );
231 }
232 // Don't let any queue slaves/backups fall behind
233 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
234 $group->waitForBackups();
235 }
236
237 // Bail if near-OOM instead of in a job
238 $this->assertMemoryOK();
239 }
240 } while ( $job ); // stop when there are no jobs
241
242 // Sync the persistent backoffs for the next runJobs.php pass
243 if ( $backoffDeltas ) {
244 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
245 }
246
247 $response['backoffs'] = $backoffs;
248 $response['elapsed'] = $timeMsTotal;
249
250 return $response;
251 }
252
253 /**
254 * @param Job $job
255 * @return int Seconds for this runner to avoid doing more jobs of this type
256 * @see $wgJobBackoffThrottling
257 */
258 private function getBackoffTimeToWait( Job $job ) {
259 global $wgJobBackoffThrottling;
260
261 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
262 $job instanceof DuplicateJob // no work was done
263 ) {
264 return 0; // not throttled
265 }
266
267 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
268 if ( $itemsPerSecond <= 0 ) {
269 return 0; // not throttled
270 }
271
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;
279 }
280
281 return (int)$seconds;
282 }
283
284 /**
285 * Get the previous backoff expiries from persistent storage
286 * On I/O or lock acquisition failure this returns the original $backoffs.
287 *
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)
291 */
292 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
293
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
301 }
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] );
310 }
311 }
312 } else {
313 $cBackoffs = array();
314 }
315
316 return $cBackoffs;
317 }
318
319 /**
320 * Merge the current backoff expiries from persistent storage
321 *
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.
324 *
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
329 */
330 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
331
332 if ( !$deltas ) {
333 return $this->loadBackoffs( $backoffs, $mode );
334 }
335
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
342 }
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;
350 }
351 foreach ( $cBackoffs as $type => $timestamp ) {
352 if ( $timestamp < $ctime ) {
353 unset( $cBackoffs[$type] );
354 }
355 }
356 ftruncate( $handle, 0 );
357 fwrite( $handle, json_encode( $cBackoffs ) );
358 flock( $handle, LOCK_UN );
359 fclose( $handle );
360
361 $deltas = array();
362
363 return $cBackoffs;
364 }
365
366 /**
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
370 */
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;
381 }
382 }
383 $usedBytes = memory_get_usage();
384 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
385 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
386 }
387 }
388
389 /**
390 * Log the job message
391 * @param string $msg The message to log
392 */
393 private function debugCallback( $msg ) {
394 if ( $this->debug ) {
395 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
396 }
397 }
398 }