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