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