Merge "Fix various mistakes in PHPDoc comments"
[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 // Bail out if in read-only mode
107 if ( wfReadOnly() ) {
108 $response['reached'] = 'read-only';
109 return $response;
110 }
111
112 // Catch huge single updates that lead to slave lag
113 $trxProfiler = Profiler::instance()->getTransactionProfiler();
114 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
115 $trxProfiler->setExpectations( $wgTrxProfilerLimits['JobRunner'], __METHOD__ );
116
117 // Bail out if there is too much DB lag.
118 // This check should not block as we want to try other wiki queues.
119 $maxAllowedLag = 3;
120 list( , $maxLag ) = wfGetLB( wfWikiID() )->getMaxLag();
121 if ( $maxLag >= $maxAllowedLag ) {
122 $response['reached'] = 'slave-lag-limit';
123 return $response;
124 }
125
126 $group = JobQueueGroup::singleton();
127
128 // Flush any pending DB writes for sanity
129 wfGetLBFactory()->commitAll();
130
131 // Some jobs types should not run until a certain timestamp
132 $backoffs = array(); // map of (type => UNIX expiry)
133 $backoffDeltas = array(); // map of (type => seconds)
134 $wait = 'wait'; // block to read backoffs the first time
135
136 $stats = RequestContext::getMain()->getStats();
137 $jobsPopped = 0;
138 $timeMsTotal = 0;
139 $flags = JobQueueGroup::USE_CACHE;
140 $startTime = microtime( true ); // time since jobs started running
141 $checkLagPeriod = 1.0; // check slave lag this many seconds
142 $lastCheckTime = 1; // timestamp of last slave check
143 do {
144 // Sync the persistent backoffs with concurrent runners
145 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
146 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
147 $wait = 'nowait'; // less important now
148
149 if ( $type === false ) {
150 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
151 } elseif ( in_array( $type, $blacklist ) ) {
152 $job = false; // requested queue in backoff state
153 } else {
154 $job = $group->pop( $type ); // job from a single queue
155 }
156
157 if ( $job ) { // found a job
158 $popTime = time();
159 $jType = $job->getType();
160
161 // Back off of certain jobs for a while (for throttling and for errors)
162 $ttw = $this->getBackoffTimeToWait( $job );
163 if ( $ttw > 0 ) {
164 // Always add the delta for other runners in case the time running the
165 // job negated the backoff for each individually but not collectively.
166 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
167 ? $backoffDeltas[$jType] + $ttw
168 : $ttw;
169 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
170 }
171
172 $msg = $job->toString() . " STARTING";
173 $this->logger->debug( $msg );
174 $this->debugCallback( $msg );
175
176 // Run the job...
177 $jobStartTime = microtime( true );
178 try {
179 ++$jobsPopped;
180 $status = $job->run();
181 $error = $job->getLastError();
182 $this->commitMasterChanges( $job );
183
184 DeferredUpdates::doUpdates();
185 $this->commitMasterChanges( $job );
186 } catch ( Exception $e ) {
187 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
188 $status = false;
189 $error = get_class( $e ) . ': ' . $e->getMessage();
190 MWExceptionHandler::logException( $e );
191 }
192 // Commit all outstanding connections that are in a transaction
193 // to get a fresh repeatable read snapshot on every connection.
194 // Note that jobs are still responsible for handling slave lag.
195 wfGetLBFactory()->commitAll();
196 // Clear out title cache data from prior snapshots
197 LinkCache::singleton()->clear();
198 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
199 $timeMsTotal += $timeMs;
200
201 // Record how long jobs wait before getting popped
202 $readyTs = $job->getReadyTimestamp();
203 if ( $readyTs ) {
204 $pickupDelay = $popTime - $readyTs;
205 $stats->timing( 'jobqueue.pickup_delay.all', 1000 * $pickupDelay );
206 $stats->timing( "jobqueue.pickup_delay.$jType", 1000 * $pickupDelay );
207 }
208 // Record root job age for jobs being run
209 $root = $job->getRootJobParams();
210 if ( $root['rootJobTimestamp'] ) {
211 $age = $popTime - wfTimestamp( TS_UNIX, $root['rootJobTimestamp'] );
212 $stats->timing( "jobqueue.pickup_root_age.$jType", 1000 * $age );
213 }
214 // Track the execution time for jobs
215 $stats->timing( "jobqueue.run.$jType", $timeMs );
216
217 // Mark the job as done on success or when the job cannot be retried
218 if ( $status !== false || !$job->allowRetries() ) {
219 $group->ack( $job ); // done
220 }
221
222 // Back off of certain jobs for a while (for throttling and for errors)
223 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
224 $ttw = max( $ttw, 30 ); // too many errors
225 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
226 ? $backoffDeltas[$jType] + $ttw
227 : $ttw;
228 }
229
230 if ( $status === false ) {
231 $msg = $job->toString() . " t=$timeMs error={$error}";
232 $this->logger->error( $msg );
233 $this->debugCallback( $msg );
234 } else {
235 $msg = $job->toString() . " t=$timeMs good";
236 $this->logger->info( $msg );
237 $this->debugCallback( $msg );
238 }
239
240 $response['jobs'][] = array(
241 'type' => $jType,
242 'status' => ( $status === false ) ? 'failed' : 'ok',
243 'error' => $error,
244 'time' => $timeMs
245 );
246
247 // Break out if we hit the job count or wall time limits...
248 if ( $maxJobs && $jobsPopped >= $maxJobs ) {
249 $response['reached'] = 'job-limit';
250 break;
251 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
252 $response['reached'] = 'time-limit';
253 break;
254 }
255
256 // Don't let any of the main DB slaves get backed up.
257 // This only waits for so long before exiting and letting
258 // other wikis in the farm (on different masters) get a chance.
259 $timePassed = microtime( true ) - $lastCheckTime;
260 if ( $timePassed >= $checkLagPeriod || $timePassed < 0 ) {
261 if ( !wfWaitForSlaves( $lastCheckTime, false, '*', $maxAllowedLag ) ) {
262 $response['reached'] = 'slave-lag-limit';
263 break;
264 }
265 $lastCheckTime = microtime( true );
266 }
267 // Don't let any queue slaves/backups fall behind
268 if ( $jobsPopped > 0 && ( $jobsPopped % 100 ) == 0 ) {
269 $group->waitForBackups();
270 }
271
272 // Bail if near-OOM instead of in a job
273 if ( !$this->checkMemoryOK() ) {
274 $response['reached'] = 'memory-limit';
275 break;
276 }
277 }
278 } while ( $job ); // stop when there are no jobs
279
280 // Sync the persistent backoffs for the next runJobs.php pass
281 if ( $backoffDeltas ) {
282 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
283 }
284
285 $response['backoffs'] = $backoffs;
286 $response['elapsed'] = $timeMsTotal;
287
288 return $response;
289 }
290
291 /**
292 * @param Job $job
293 * @return int Seconds for this runner to avoid doing more jobs of this type
294 * @see $wgJobBackoffThrottling
295 */
296 private function getBackoffTimeToWait( Job $job ) {
297 global $wgJobBackoffThrottling;
298
299 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
300 $job instanceof DuplicateJob // no work was done
301 ) {
302 return 0; // not throttled
303 }
304
305 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
306 if ( $itemsPerSecond <= 0 ) {
307 return 0; // not throttled
308 }
309
310 $seconds = 0;
311 if ( $job->workItemCount() > 0 ) {
312 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
313 // use randomized rounding
314 $seconds = floor( $exactSeconds );
315 $remainder = $exactSeconds - $seconds;
316 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
317 }
318
319 return (int)$seconds;
320 }
321
322 /**
323 * Get the previous backoff expiries from persistent storage
324 * On I/O or lock acquisition failure this returns the original $backoffs.
325 *
326 * @param array $backoffs Map of (job type => UNIX timestamp)
327 * @param string $mode Lock wait mode - "wait" or "nowait"
328 * @return array Map of (job type => backoff expiry timestamp)
329 */
330 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
331 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
332 if ( is_file( $file ) ) {
333 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
334 $handle = fopen( $file, 'rb' );
335 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
336 fclose( $handle );
337 return $backoffs; // don't wait on lock
338 }
339 $content = stream_get_contents( $handle );
340 flock( $handle, LOCK_UN );
341 fclose( $handle );
342 $ctime = microtime( true );
343 $cBackoffs = json_decode( $content, true ) ?: array();
344 foreach ( $cBackoffs as $type => $timestamp ) {
345 if ( $timestamp < $ctime ) {
346 unset( $cBackoffs[$type] );
347 }
348 }
349 } else {
350 $cBackoffs = array();
351 }
352
353 return $cBackoffs;
354 }
355
356 /**
357 * Merge the current backoff expiries from persistent storage
358 *
359 * The $deltas map is set to an empty array on success.
360 * On I/O or lock acquisition failure this returns the original $backoffs.
361 *
362 * @param array $backoffs Map of (job type => UNIX timestamp)
363 * @param array $deltas Map of (job type => seconds)
364 * @param string $mode Lock wait mode - "wait" or "nowait"
365 * @return array The new backoffs account for $backoffs and the latest file data
366 */
367 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
368 if ( !$deltas ) {
369 return $this->loadBackoffs( $backoffs, $mode );
370 }
371
372 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
373 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
374 $handle = fopen( $file, 'wb+' );
375 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
376 fclose( $handle );
377 return $backoffs; // don't wait on lock
378 }
379 $ctime = microtime( true );
380 $content = stream_get_contents( $handle );
381 $cBackoffs = json_decode( $content, true ) ?: array();
382 foreach ( $deltas as $type => $seconds ) {
383 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
384 ? $cBackoffs[$type] + $seconds
385 : $ctime + $seconds;
386 }
387 foreach ( $cBackoffs as $type => $timestamp ) {
388 if ( $timestamp < $ctime ) {
389 unset( $cBackoffs[$type] );
390 }
391 }
392 ftruncate( $handle, 0 );
393 fwrite( $handle, json_encode( $cBackoffs ) );
394 flock( $handle, LOCK_UN );
395 fclose( $handle );
396
397 $deltas = array();
398
399 return $cBackoffs;
400 }
401
402 /**
403 * Make sure that this script is not too close to the memory usage limit.
404 * It is better to die in between jobs than OOM right in the middle of one.
405 * @return bool
406 */
407 private function checkMemoryOK() {
408 static $maxBytes = null;
409 if ( $maxBytes === null ) {
410 $m = array();
411 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
412 list( , $num, $unit ) = $m;
413 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
414 $maxBytes = $num * $conv[strtolower( $unit )];
415 } else {
416 $maxBytes = 0;
417 }
418 }
419 $usedBytes = memory_get_usage();
420 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
421 $msg = "Detected excessive memory usage ($usedBytes/$maxBytes).";
422 $this->debugCallback( $msg );
423 $this->logger->error( $msg );
424
425 return false;
426 }
427
428 return true;
429 }
430
431 /**
432 * Log the job message
433 * @param string $msg The message to log
434 */
435 private function debugCallback( $msg ) {
436 if ( $this->debug ) {
437 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
438 }
439 }
440
441 /**
442 * Issue a commit on all masters who are currently in a transaction and have
443 * made changes to the database. It also supports sometimes waiting for the
444 * local wiki's slaves to catch up. See the documentation for
445 * $wgJobSerialCommitThreshold for more.
446 *
447 * @param Job $job
448 * @throws DBError
449 */
450 private function commitMasterChanges( Job $job ) {
451 global $wgJobSerialCommitThreshold;
452
453 $lb = wfGetLB( wfWikiID() );
454 if ( $wgJobSerialCommitThreshold !== false && $lb->getServerCount() > 1 ) {
455 // Generally, there is one master connection to the local DB
456 $dbwSerial = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
457 } else {
458 $dbwSerial = false;
459 }
460
461 if ( !$dbwSerial
462 || !$dbwSerial->namedLocksEnqueue()
463 || $dbwSerial->pendingWriteQueryDuration() < $wgJobSerialCommitThreshold
464 ) {
465 // Writes are all to foreign DBs, named locks don't form queues,
466 // or $wgJobSerialCommitThreshold is not reached; commit changes now
467 wfGetLBFactory()->commitMasterChanges();
468 return;
469 }
470
471 $ms = intval( 1000 * $dbwSerial->pendingWriteQueryDuration() );
472 $msg = $job->toString() . " COMMIT ENQUEUED [{$ms}ms of writes]";
473 $this->logger->warning( $msg );
474 $this->debugCallback( $msg );
475
476 // Wait for an exclusive lock to commit
477 if ( !$dbwSerial->lock( 'jobrunner-serial-commit', __METHOD__, 30 ) ) {
478 // This will trigger a rollback in the main loop
479 throw new DBError( $dbwSerial, "Timed out waiting on commit queue." );
480 }
481 // Wait for the generic slave to catch up
482 $pos = $lb->getMasterPos();
483 if ( $pos ) {
484 $lb->waitForOne( $pos );
485 }
486
487 $fname = __METHOD__;
488 // Re-ping all masters with transactions. This throws DBError if some
489 // connection died while waiting on locks/slaves, triggering a rollback.
490 wfGetLBFactory()->forEachLB( function( LoadBalancer $lb ) use ( $fname ) {
491 $lb->forEachOpenConnection( function( IDatabase $conn ) use ( $fname ) {
492 if ( $conn->writesOrCallbacksPending() ) {
493 $conn->query( "SELECT 1", $fname );
494 }
495 } );
496 } );
497
498 // Actually commit the DB master changes
499 wfGetLBFactory()->commitMasterChanges();
500
501 // Release the lock
502 $dbwSerial->unlock( 'jobrunner-serial-commit', __METHOD__ );
503 }
504 }