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