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