Made JobRunner avoid slave lag more aggressively
[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 * @param callable $debug Optional debug output handler
40 */
41 public function setDebugHandler( $debug ) {
42 $this->debug = $debug;
43 }
44
45 /**
46 * @var LoggerInterface $logger
47 */
48 protected $logger;
49
50 /**
51 * @param LoggerInterface $logger
52 */
53 public function setLogger( LoggerInterface $logger ) {
54 $this->logger = $logger;
55 }
56
57 /**
58 * @param LoggerInterface $logger
59 */
60 public function __construct( LoggerInterface $logger = null ) {
61 if ( $logger === null ) {
62 $logger = LoggerFactory::getInstance( 'runJobs' );
63 }
64 $this->setLogger( $logger );
65 }
66
67 /**
68 * Run jobs of the specified number/type for the specified time
69 *
70 * The response map has a 'job' field that lists status of each job, including:
71 * - type : the job type
72 * - status : ok/failed
73 * - error : any error message string
74 * - time : the job run time in ms
75 * The response map also has:
76 * - backoffs : the (job type => seconds) map of backoff times
77 * - elapsed : the total time spent running tasks in ms
78 * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit)
79 *
80 * This method outputs status information only if a debug handler was set.
81 * Any exceptions are caught and logged, but are not reported as output.
82 *
83 * @param array $options Map of parameters:
84 * - type : the job type (or false for the default types)
85 * - maxJobs : maximum number of jobs to run
86 * - maxTime : maximum time in seconds before stopping
87 * - throttle : whether to respect job backoff configuration
88 * @return array Summary response that can easily be JSON serialized
89 */
90 public function run( array $options ) {
91 global $wgJobClasses;
92
93 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
94
95 $type = isset( $options['type'] ) ? $options['type'] : false;
96 $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false;
97 $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false;
98 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
99
100 if ( $type !== false && !isset( $wgJobClasses[$type] ) ) {
101 $response['reached'] = 'none-possible';
102 return $response;
103 }
104
105 $group = JobQueueGroup::singleton();
106 // Handle any required periodic queue maintenance
107 $count = $group->executeReadyPeriodicTasks();
108 if ( $count > 0 ) {
109 $msg = "Executed $count periodic queue task(s).";
110 $this->logger->debug( $msg );
111 $this->debugCallback( $msg );
112 }
113
114 // Bail out if in read-only mode
115 if ( wfReadOnly() ) {
116 $response['reached'] = 'read-only';
117 return $response;
118 }
119
120 // Catch huge single updates that lead to slave lag
121 $trxProfiler = Profiler::instance()->getTransactionProfiler();
122 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
123 $trxProfiler->setExpectation( 'maxAffected', 500, __METHOD__ );
124
125 // Bail out if there is too much DB lag
126 list( , $maxLag ) = wfGetLBFactory()->getMainLB( wfWikiID() )->getMaxLag();
127 if ( $maxLag >= 5 ) {
128 $response['reached'] = 'slave-lag-limit';
129 return $response;
130 }
131
132 // Flush any pending DB writes for sanity
133 wfGetLBFactory()->commitMasterChanges();
134
135 // Some jobs types should not run until a certain timestamp
136 $backoffs = array(); // map of (type => UNIX expiry)
137 $backoffDeltas = array(); // map of (type => seconds)
138 $wait = 'wait'; // block to read backoffs the first time
139
140 $jobsRun = 0;
141 $timeMsTotal = 0;
142 $flags = JobQueueGroup::USE_CACHE;
143 $checkPeriod = 5.0; // seconds
144 $checkPhase = mt_rand( 0, 1000 * $checkPeriod ) / 1000; // avoid stampedes
145 $startTime = microtime( true ); // time since jobs started running
146 $lastTime = microtime( true ) - $checkPhase; // time since last slave check
147 do {
148 // Sync the persistent backoffs with concurrent runners
149 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
150 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
151 $wait = 'nowait'; // less important now
152
153 if ( $type === false ) {
154 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
155 } elseif ( in_array( $type, $blacklist ) ) {
156 $job = false; // requested queue in backoff state
157 } else {
158 $job = $group->pop( $type ); // job from a single queue
159 }
160
161 if ( $job ) { // found a job
162 $jType = $job->getType();
163
164 // Back off of certain jobs for a while (for throttling and for errors)
165 $ttw = $this->getBackoffTimeToWait( $job );
166 if ( $ttw > 0 ) {
167 // Always add the delta for other runners in case the time running the
168 // job negated the backoff for each individually but not collectively.
169 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
170 ? $backoffDeltas[$jType] + $ttw
171 : $ttw;
172 $backoffs = $this->syncBackoffDeltas( $backoffs, $backoffDeltas, $wait );
173 }
174
175 $msg = $job->toString() . " STARTING";
176 $this->logger->info( $msg );
177 $this->debugCallback( $msg );
178
179 // Run the job...
180 $jobStartTime = microtime( true );
181 try {
182 ++$jobsRun;
183 $status = $job->run();
184 $error = $job->getLastError();
185 wfGetLBFactory()->commitMasterChanges();
186 } catch ( Exception $e ) {
187 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
188 $status = false;
189 $error = get_class( $e ) . ': ' . $e->getMessage();
190 MWExceptionHandler::logException( $e );
191 }
192 $timeMs = intval( ( microtime( true ) - $jobStartTime ) * 1000 );
193 $timeMsTotal += $timeMs;
194
195 // Mark the job as done on success or when the job cannot be retried
196 if ( $status !== false || !$job->allowRetries() ) {
197 $group->ack( $job ); // done
198 }
199
200 // Back off of certain jobs for a while (for throttling and for errors)
201 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
202 $ttw = max( $ttw, 30 ); // too many errors
203 $backoffDeltas[$jType] = isset( $backoffDeltas[$jType] )
204 ? $backoffDeltas[$jType] + $ttw
205 : $ttw;
206 }
207
208 if ( $status === false ) {
209 $msg = $job->toString() . " t=$timeMs error={$error}";
210 $this->logger->error( $msg );
211 $this->debugCallback( $msg );
212 } else {
213 $msg = $job->toString() . " t=$timeMs good";
214 $this->logger->info( $msg );
215 $this->debugCallback( $msg );
216 }
217
218 $response['jobs'][] = array(
219 'type' => $jType,
220 'status' => ( $status === false ) ? 'failed' : 'ok',
221 'error' => $error,
222 'time' => $timeMs
223 );
224
225 // Break out if we hit the job count or wall time limits...
226 if ( $maxJobs && $jobsRun >= $maxJobs ) {
227 $response['reached'] = 'job-limit';
228 break;
229 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
230 $response['reached'] = 'time-limit';
231 break;
232 }
233
234 // Don't let any of the main DB slaves get backed up.
235 // This only waits for so long before exiting and letting
236 // other wikis in the farm (on different masters) get a chance.
237 $timePassed = microtime( true ) - $lastTime;
238 if ( $timePassed >= 3 || $timePassed < 0 ) {
239 if ( !wfWaitForSlaves( $lastTime, false, '*', 5 ) ) {
240 $response['reached'] = 'slave-lag-limit';
241 break;
242 }
243 $lastTime = microtime( true );
244 }
245 // Don't let any queue slaves/backups fall behind
246 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
247 $group->waitForBackups();
248 }
249
250 // Bail if near-OOM instead of in a job
251 $this->assertMemoryOK();
252 }
253 } while ( $job ); // stop when there are no jobs
254
255 // Sync the persistent backoffs for the next runJobs.php pass
256 if ( $backoffDeltas ) {
257 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
258 }
259
260 $response['backoffs'] = $backoffs;
261 $response['elapsed'] = $timeMsTotal;
262
263 return $response;
264 }
265
266 /**
267 * @param Job $job
268 * @return int Seconds for this runner to avoid doing more jobs of this type
269 * @see $wgJobBackoffThrottling
270 */
271 private function getBackoffTimeToWait( Job $job ) {
272 global $wgJobBackoffThrottling;
273
274 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
275 $job instanceof DuplicateJob // no work was done
276 ) {
277 return 0; // not throttled
278 }
279
280 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
281 if ( $itemsPerSecond <= 0 ) {
282 return 0; // not throttled
283 }
284
285 $seconds = 0;
286 if ( $job->workItemCount() > 0 ) {
287 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
288 // use randomized rounding
289 $seconds = floor( $exactSeconds );
290 $remainder = $exactSeconds - $seconds;
291 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
292 }
293
294 return (int)$seconds;
295 }
296
297 /**
298 * Get the previous backoff expiries from persistent storage
299 * On I/O or lock acquisition failure this returns the original $backoffs.
300 *
301 * @param array $backoffs Map of (job type => UNIX timestamp)
302 * @param string $mode Lock wait mode - "wait" or "nowait"
303 * @return array Map of (job type => backoff expiry timestamp)
304 */
305 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
306
307 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
308 if ( is_file( $file ) ) {
309 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
310 $handle = fopen( $file, 'rb' );
311 if ( !flock( $handle, LOCK_SH | $noblock ) ) {
312 fclose( $handle );
313 return $backoffs; // don't wait on lock
314 }
315 $content = stream_get_contents( $handle );
316 flock( $handle, LOCK_UN );
317 fclose( $handle );
318 $ctime = microtime( true );
319 $cBackoffs = json_decode( $content, true ) ?: array();
320 foreach ( $cBackoffs as $type => $timestamp ) {
321 if ( $timestamp < $ctime ) {
322 unset( $cBackoffs[$type] );
323 }
324 }
325 } else {
326 $cBackoffs = array();
327 }
328
329 return $cBackoffs;
330 }
331
332 /**
333 * Merge the current backoff expiries from persistent storage
334 *
335 * The $deltas map is set to an empty array on success.
336 * On I/O or lock acquisition failure this returns the original $backoffs.
337 *
338 * @param array $backoffs Map of (job type => UNIX timestamp)
339 * @param array $deltas Map of (job type => seconds)
340 * @param string $mode Lock wait mode - "wait" or "nowait"
341 * @return array The new backoffs account for $backoffs and the latest file data
342 */
343 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
344
345 if ( !$deltas ) {
346 return $this->loadBackoffs( $backoffs, $mode );
347 }
348
349 $noblock = ( $mode === 'nowait' ) ? LOCK_NB : 0;
350 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
351 $handle = fopen( $file, 'wb+' );
352 if ( !flock( $handle, LOCK_EX | $noblock ) ) {
353 fclose( $handle );
354 return $backoffs; // don't wait on lock
355 }
356 $ctime = microtime( true );
357 $content = stream_get_contents( $handle );
358 $cBackoffs = json_decode( $content, true ) ?: array();
359 foreach ( $deltas as $type => $seconds ) {
360 $cBackoffs[$type] = isset( $cBackoffs[$type] ) && $cBackoffs[$type] >= $ctime
361 ? $cBackoffs[$type] + $seconds
362 : $ctime + $seconds;
363 }
364 foreach ( $cBackoffs as $type => $timestamp ) {
365 if ( $timestamp < $ctime ) {
366 unset( $cBackoffs[$type] );
367 }
368 }
369 ftruncate( $handle, 0 );
370 fwrite( $handle, json_encode( $cBackoffs ) );
371 flock( $handle, LOCK_UN );
372 fclose( $handle );
373
374 $deltas = array();
375
376 return $cBackoffs;
377 }
378
379 /**
380 * Make sure that this script is not too close to the memory usage limit.
381 * It is better to die in between jobs than OOM right in the middle of one.
382 * @throws MWException
383 */
384 private function assertMemoryOK() {
385 static $maxBytes = null;
386 if ( $maxBytes === null ) {
387 $m = array();
388 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
389 list( , $num, $unit ) = $m;
390 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
391 $maxBytes = $num * $conv[strtolower( $unit )];
392 } else {
393 $maxBytes = 0;
394 }
395 }
396 $usedBytes = memory_get_usage();
397 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
398 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
399 }
400 }
401
402 /**
403 * Log the job message
404 * @param string $msg The message to log
405 */
406 private function debugCallback( $msg ) {
407 if ( $this->debug ) {
408 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
409 }
410 }
411 }