3 * Job queue runner utility methods
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.
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.
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
25 * Job queue runner utility methods
31 /** @var callable|null Debug output handler */
35 * @param callable $debug Optional debug output handler
37 public function setDebugHandler( $debug ) {
38 $this->debug
= $debug;
42 * Run jobs of the specified number/type for the specified time
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)
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.
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
64 public function run( array $options ) {
65 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
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'];
72 $group = JobQueueGroup
::singleton();
73 // Handle any required periodic queue maintenance
74 $count = $group->executeReadyPeriodicTasks();
76 $this->runJobsLog( "Executed $count periodic queue task(s)." );
79 // Flush any pending DB writes for sanity
80 wfGetLBFactory()->commitMasterChanges();
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 ) {
89 $jobsRun = 0; // counter
91 $flags = JobQueueGroup
::USE_CACHE
;
92 $sTime = microtime( true ); // time since jobs started running
93 $lastTime = microtime( true ); // time since last slave check
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
102 $job = $group->pop( $type ); // job from a single queue
104 if ( $job ) { // found a job
105 $jType = $job->getType();
107 $this->runJobsLog( $job->toString() . " STARTING" );
110 wfProfileIn( __METHOD__
. '-' . get_class( $job ) );
111 $sTime = microtime( true );
114 $status = $job->run();
115 $error = $job->getLastError();
116 wfGetLBFactory()->commitMasterChanges();
117 } catch ( MWException
$e ) {
118 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
120 $error = get_class( $e ) . ': ' . $e->getMessage();
121 MWExceptionHandler
::logException( $e );
123 $timeMs = intval( ( microtime( true ) - $sTime ) * 1000 );
124 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
125 $timeMsTotal +
= $timeMs;
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
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
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
145 // Sync the persistent backoffs with concurrent runners
146 $backoffs = $backoffDeltas
147 ?
$this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'nowait' )
148 : $this->loadBackoffs( $backoffs, 'nowait' );
150 if ( $status === false ) {
151 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
153 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
156 $response['jobs'][] = array(
158 'status' => ( $status === false ) ?
'failed' : 'ok',
163 // Break out if we hit the job count or wall time limits...
164 if ( $maxJobs && $jobsRun >= $maxJobs ) {
165 $response['reached'] = 'job-limit';
167 } elseif ( $maxTime && ( microtime( true ) - $sTime ) > $maxTime ) {
168 $response['reached'] = 'time-limit';
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 );
178 // Don't let any queue slaves/backups fall behind
179 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
180 $group->waitForBackups();
183 // Bail if near-OOM instead of in a job
184 $this->assertMemoryOK();
186 } while ( $job ); // stop when there are no jobs
188 // Sync the persistent backoffs for the next runJobs.php pass
189 if ( $backoffDeltas ) {
190 $this->syncBackoffDeltas( $backoffs, $backoffDeltas, 'wait' );
193 $response['backoffs'] = $backoffs;
194 $response['elapsed'] = $timeMsTotal;
201 * @return int Seconds for this runner to avoid doing more jobs of this type
202 * @see $wgJobBackoffThrottling
204 private function getBackoffTimeToWait( Job
$job ) {
205 global $wgJobBackoffThrottling;
207 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
208 $job instanceof DuplicateJob
// no work was done
210 return 0; // not throttled
213 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
214 if ( $itemsPerSecond <= 0 ) {
215 return 0; // not throttled
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;
227 return (int)$seconds;
231 * Get the previous backoff expiries from persistent storage
232 * On I/O or lock acquisition failure this returns the original $backoffs.
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)
238 private function loadBackoffs( array $backoffs, $mode = 'wait' ) {
239 $section = new ProfileSection( __METHOD__
);
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 ) ) {
247 return $backoffs; // don't wait on lock
249 $content = stream_get_contents( $handle );
250 flock( $handle, LOCK_UN
);
252 $backoffs = json_decode( $content, true ) ?
: array();
261 * Merge the current backoff expiries from persistent storage
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.
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
271 private function syncBackoffDeltas( array $backoffs, array &$deltas, $mode = 'wait' ) {
272 $section = new ProfileSection( __METHOD__
);
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 ) ) {
280 return $backoffs; // don't wait on lock
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
289 ftruncate( $handle, 0 );
290 fwrite( $handle, json_encode( $cBackoffs ) );
291 flock( $handle, LOCK_UN
);
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
304 private function assertMemoryOK() {
305 static $maxBytes = null;
306 if ( $maxBytes === null ) {
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 )];
316 $usedBytes = memory_get_usage();
317 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
318 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
323 * Log the job message
324 * @param string $msg The message to log
326 private function runJobsLog( $msg ) {
327 if ( $this->debug
) {
328 call_user_func_array( $this->debug
, array( wfTimestamp( TS_DB
) . " $msg\n" ) );
330 wfDebugLog( 'runJobs', $msg );