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