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