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