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