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 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
83 $startingBackoffs = $backoffs; // avoid unnecessary writes
84 $backoffExpireFunc = function ( $t ) {
88 $jobsRun = 0; // counter
90 $flags = JobQueueGroup
::USE_CACHE
;
91 $startTime = microtime( true ); // time since jobs started running
92 $lastTime = microtime( true ); // time since last slave check
94 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
95 $blacklist = $noThrottle ?
array() : array_keys( $backoffs );
96 if ( $type === false ) {
97 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
98 } elseif ( in_array( $type, $blacklist ) ) {
99 $job = false; // requested queue in backoff state
101 $job = $group->pop( $type ); // job from a single queue
103 if ( $job ) { // found a job
104 $jType = $job->getType();
106 $this->runJobsLog( $job->toString() . " STARTING" );
109 wfProfileIn( __METHOD__
. '-' . get_class( $job ) );
110 $t = microtime( true );
113 $status = $job->run();
114 $error = $job->getLastError();
115 wfGetLBFactory()->commitMasterChanges();
116 } catch ( MWException
$e ) {
117 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
119 $error = get_class( $e ) . ': ' . $e->getMessage();
120 MWExceptionHandler
::logException( $e );
122 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
123 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
124 $timeMsTotal +
= $timeMs;
126 // Mark the job as done on success or when the job cannot be retried
127 if ( $status !== false ||
!$job->allowRetries() ) {
128 $group->ack( $job ); // done
131 if ( $status === false ) {
132 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
134 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
137 $response['jobs'][] = array(
139 'status' => ( $status === false ) ?
'failed' : 'ok',
144 // Back off of certain jobs for a while (for throttling and for errors)
145 $ttw = $this->getBackoffTimeToWait( $job );
146 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
147 $ttw = max( $ttw, 30 );
150 $backoffs[$jType] = isset( $backoffs[$jType] ) ?
$backoffs[$jType] : 0;
151 $backoffs[$jType] = max( $backoffs[$jType], time() +
$ttw );
154 // Break out if we hit the job count or wall time limits...
155 if ( $maxJobs && $jobsRun >= $maxJobs ) {
156 $response['reached'] = 'job-limit';
158 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
159 $response['reached'] = 'time-limit';
163 // Don't let any of the main DB slaves get backed up
164 $timePassed = microtime( true ) - $lastTime;
165 if ( $timePassed >= 5 ||
$timePassed < 0 ) {
166 wfWaitForSlaves( $lastTime );
167 $lastTime = microtime( true );
169 // Don't let any queue slaves/backups fall behind
170 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
171 $group->waitForBackups();
174 // Bail if near-OOM instead of in a job
175 $this->assertMemoryOK();
177 } while ( $job ); // stop when there are no jobs
179 // Sync the persistent backoffs for the next runJobs.php pass
180 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
181 if ( $backoffs !== $startingBackoffs ) {
182 $this->syncBackoffs( $backoffs );
185 $response['backoffs'] = $backoffs;
186 $response['elapsed'] = $timeMsTotal;
193 * @return int Seconds for this runner to avoid doing more jobs of this type
194 * @see $wgJobBackoffThrottling
196 private function getBackoffTimeToWait( Job
$job ) {
197 global $wgJobBackoffThrottling;
199 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
200 $job instanceof DuplicateJob
// no work was done
202 return 0; // not throttled
205 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
206 if ( $itemsPerSecond <= 0 ) {
207 return 0; // not throttled
211 if ( $job->workItemCount() > 0 ) {
212 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
213 // use randomized rounding
214 $seconds = floor( $exactSeconds );
215 $remainder = $exactSeconds - $seconds;
216 $seconds +
= ( mt_rand() / mt_getrandmax() < $remainder ) ?
1 : 0;
219 return (int)$seconds;
223 * Get the previous backoff expiries from persistent storage
225 * @return array Map of (job type => backoff expiry timestamp)
227 private function loadBackoffs() {
228 $section = new ProfileSection( __METHOD__
);
231 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
232 if ( is_file( $file ) ) {
233 $handle = fopen( $file, 'rb' );
234 flock( $handle, LOCK_SH
);
235 $content = stream_get_contents( $handle );
236 flock( $handle, LOCK_UN
);
238 $backoffs = json_decode( $content, true ) ?
: array();
245 * Merge the current backoff expiries from persistent storage
247 * @param array $backoffs Map of (job type => backoff expiry timestamp)
249 private function syncBackoffs( array $backoffs ) {
250 $section = new ProfileSection( __METHOD__
);
252 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
253 $handle = fopen( $file, 'wb+' );
254 flock( $handle, LOCK_EX
);
255 $content = stream_get_contents( $handle );
256 $cBackoffs = json_decode( $content, true ) ?
: array();
257 foreach ( $backoffs as $type => $timestamp ) {
258 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ?
$cBackoffs[$type] : 0;
259 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
261 ftruncate( $handle, 0 );
262 fwrite( $handle, json_encode( $backoffs ) );
263 flock( $handle, LOCK_UN
);
268 * Make sure that this script is not too close to the memory usage limit.
269 * It is better to die in between jobs than OOM right in the middle of one.
270 * @throws MWException
272 private function assertMemoryOK() {
273 static $maxBytes = null;
274 if ( $maxBytes === null ) {
276 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
277 list( , $num, $unit ) = $m;
278 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
279 $maxBytes = $num * $conv[strtolower( $unit )];
284 $usedBytes = memory_get_usage();
285 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
286 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
291 * Log the job message
292 * @param string $msg The message to log
294 private function runJobsLog( $msg ) {
295 if ( $this->debug
) {
296 call_user_func_array( $this->debug
, array( wfTimestamp( TS_DB
) . " $msg\n" ) );
298 wfDebugLog( 'runJobs', $msg );