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