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
21 * @ingroup Maintenance
24 require_once __DIR__
. '/Maintenance.php';
27 * Maintenance script that runs pending jobs.
29 * @ingroup Maintenance
31 class RunJobs
extends Maintenance
{
32 public function __construct() {
33 parent
::__construct();
34 $this->mDescription
= "Run pending jobs";
35 $this->addOption( 'maxjobs', 'Maximum number of jobs to run', false, true );
36 $this->addOption( 'maxtime', 'Maximum amount of wall-clock time', false, true );
37 $this->addOption( 'type', 'Type of job to run', false, true );
38 $this->addOption( 'procs', 'Number of processes to use', false, true );
39 $this->addOption( 'nothrottle', 'Ignore job throttling configuration', false, false );
42 public function memoryLimit() {
43 if ( $this->hasOption( 'memory-limit' ) ) {
44 return parent
::memoryLimit();
47 // Don't eat all memory on the machine if we get a bad job.
51 public function execute() {
53 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
56 if ( $this->hasOption( 'procs' ) ) {
57 $procs = intval( $this->getOption( 'procs' ) );
58 if ( $procs < 1 ||
$procs > 1000 ) {
59 $this->error( "Invalid argument to --procs", true );
60 } elseif ( $procs != 1 ) {
61 $fc = new ForkController( $procs );
62 if ( $fc->start() != 'child' ) {
68 $type = $this->getOption( 'type', false );
69 $maxJobs = $this->getOption( 'maxjobs', false );
70 $maxTime = $this->getOption( 'maxtime', false );
71 $noThrottle = $this->hasOption( 'nothrottle' );
74 $group = JobQueueGroup
::singleton();
75 // Handle any required periodic queue maintenance
76 $count = $group->executeReadyPeriodicTasks();
78 $this->runJobsLog( "Executed $count periodic queue task(s)." );
81 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
82 $startingBackoffs = $backoffs; // avoid unnecessary writes
83 $backoffExpireFunc = function ( $t ) {
87 $jobsRun = 0; // counter
88 $flags = JobQueueGroup
::USE_CACHE
;
89 $lastTime = time(); // time since last slave check
91 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
92 $blacklist = $noThrottle ?
array() : array_keys( $backoffs );
93 if ( $type === false ) {
94 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
95 } elseif ( in_array( $type, $blacklist ) ) {
96 $job = false; // requested queue in backoff state
98 $job = $group->pop( $type ); // job from a single queue
100 if ( $job ) { // found a job
102 $this->runJobsLog( $job->toString() . " STARTING" );
104 // Set timer to stop the job if too much CPU time is used
105 set_time_limit( $maxTime ?
: 0 );
107 wfProfileIn( __METHOD__
. '-' . get_class( $job ) );
108 $t = microtime( true );
110 $status = $job->run();
111 $error = $job->getLastError();
112 } catch ( MWException
$e ) {
113 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
115 $error = get_class( $e ) . ': ' . $e->getMessage();
116 $e->report(); // write error to STDERR and the log
118 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
119 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
123 // Mark the job as done on success or when the job cannot be retried
124 if ( $status !== false ||
!$job->allowRetries() ) {
125 $group->ack( $job ); // done
128 if ( $status === false ) {
129 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
131 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
134 // Back off of certain jobs for a while (for throttling and for errors)
135 $ttw = $this->getBackoffTimeToWait( $job );
136 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
137 $ttw = max( $ttw, 30 );
140 $jType = $job->getType();
141 $backoffs[$jType] = isset( $backoffs[$jType] ) ?
$backoffs[$jType] : 0;
142 $backoffs[$jType] = max( $backoffs[$jType], time() +
$ttw );
145 // Break out if we hit the job count or wall time limits...
146 if ( $maxJobs && $jobsRun >= $maxJobs ) {
148 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
152 // Don't let any of the main DB slaves get backed up
153 $timePassed = time() - $lastTime;
154 if ( $timePassed >= 5 ||
$timePassed < 0 ) {
158 // Don't let any queue slaves/backups fall behind
159 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
160 $group->waitForBackups();
163 // Bail if near-OOM instead of in a job
164 $this->assertMemoryOK();
166 } while ( $job ); // stop when there are no jobs
167 // Sync the persistent backoffs for the next runJobs.php pass
168 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
169 if ( $backoffs !== $startingBackoffs ) {
170 $this->syncBackoffs( $backoffs );
176 * @return int Seconds for this runner to avoid doing more jobs of this type
177 * @see $wgJobBackoffThrottling
179 private function getBackoffTimeToWait( Job
$job ) {
180 global $wgJobBackoffThrottling;
182 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
183 $job instanceof DuplicateJob
// no work was done
185 return 0; // not throttled
188 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
189 if ( $itemsPerSecond <= 0 ) {
190 return 0; // not throttled
194 if ( $job->workItemCount() > 0 ) {
195 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
196 // use randomized rounding
197 $seconds = floor( $exactSeconds );
198 $remainder = $exactSeconds - $seconds;
199 $seconds +
= ( mt_rand() / mt_getrandmax() < $remainder ) ?
1 : 0;
202 return (int)$seconds;
206 * Get the previous backoff expiries from persistent storage
208 * @return array Map of (job type => backoff expiry timestamp)
210 private function loadBackoffs() {
211 $section = new ProfileSection( __METHOD__
);
214 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
215 if ( is_file( $file ) ) {
216 $handle = fopen( $file, 'rb' );
217 flock( $handle, LOCK_SH
);
218 $content = stream_get_contents( $handle );
219 flock( $handle, LOCK_UN
);
221 $backoffs = json_decode( $content, true ) ?
: array();
228 * Merge the current backoff expiries from persistent storage
230 * @param array $backoffs Map of (job type => backoff expiry timestamp)
232 private function syncBackoffs( array $backoffs ) {
233 $section = new ProfileSection( __METHOD__
);
235 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
236 $handle = fopen( $file, 'wb+' );
237 flock( $handle, LOCK_EX
);
238 $content = stream_get_contents( $handle );
239 $cBackoffs = json_decode( $content, true ) ?
: array();
240 foreach ( $backoffs as $type => $timestamp ) {
241 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ?
$cBackoffs[$type] : 0;
242 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
244 ftruncate( $handle, 0 );
245 fwrite( $handle, json_encode( $backoffs ) );
246 flock( $handle, LOCK_UN
);
251 * Make sure that this script is not too close to the memory usage limit.
252 * It is better to die in between jobs than OOM right in the middle of one.
253 * @throws MWException
255 private function assertMemoryOK() {
256 static $maxBytes = null;
257 if ( $maxBytes === null ) {
259 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
260 list( , $num, $unit ) = $m;
261 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
262 $maxBytes = $num * $conv[strtolower( $unit )];
267 $usedBytes = memory_get_usage();
268 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
269 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
274 * Log the job message
275 * @param string $msg The message to log
277 private function runJobsLog( $msg ) {
278 $this->output( wfTimestamp( TS_DB
) . " $msg\n" );
279 wfDebugLog( 'runJobs', $msg );
283 $maintClass = "RunJobs";
284 require_once RUN_MAINTENANCE_IF_MAIN
;