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