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