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