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 );
41 public function memoryLimit() {
42 if ( $this->hasOption( 'memory-limit' ) ) {
43 return parent
::memoryLimit();
45 // Don't eat all memory on the machine if we get a bad job.
49 public function execute() {
51 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
54 if ( $this->hasOption( 'procs' ) ) {
55 $procs = intval( $this->getOption( 'procs' ) );
56 if ( $procs < 1 ||
$procs > 1000 ) {
57 $this->error( "Invalid argument to --procs", true );
58 } elseif ( $procs != 1 ) {
59 $fc = new ForkController( $procs );
60 if ( $fc->start() != 'child' ) {
66 $type = $this->getOption( 'type', false );
67 $maxJobs = $this->getOption( 'maxjobs', false );
68 $maxTime = $this->getOption( 'maxtime', false );
71 $group = JobQueueGroup
::singleton();
72 // Handle any required periodic queue maintenance
73 $count = $group->executeReadyPeriodicTasks();
75 $this->runJobsLog( "Executed $count periodic queue task(s)." );
78 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
79 $startingBackoffs = $backoffs; // avoid unnecessary writes
80 $backoffExpireFunc = function( $t ) { return $t > time(); };
82 $jobsRun = 0; // counter
83 $flags = JobQueueGroup
::USE_CACHE
;
84 $lastTime = time(); // time since last slave check
86 if ( $type === false ) {
87 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
88 $blacklist = array_keys( $backoffs );
89 $job = $group->pop( JobQueueGroup
::TYPE_DEFAULT
, $flags, $blacklist );
91 $job = $group->pop( $type ); // job from a single queue
93 if ( $job ) { // found a job
95 $this->runJobsLog( $job->toString() . " STARTING" );
97 // Set timer to stop the job if too much CPU time is used
98 set_time_limit( $maxTime ?
: 0 );
100 wfProfileIn( __METHOD__
. '-' . get_class( $job ) );
101 $t = microtime( true );
103 $status = $job->run();
104 $error = $job->getLastError();
105 } catch ( MWException
$e ) {
106 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
108 $error = get_class( $e ) . ': ' . $e->getMessage();
109 $e->report(); // write error to STDERR and the log
111 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
112 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
116 // Mark the job as done on success or when the job cannot be retried
117 if ( $status !== false ||
!$job->allowRetries() ) {
118 $group->ack( $job ); // done
121 if ( $status === false ) {
122 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
124 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
127 // Back off of certain jobs for a while
128 $ttw = $this->getBackoffTimeToWait( $job );
130 $jType = $job->getType();
131 $backoffs[$jType] = isset( $backoffs[$jType] ) ?
$backoffs[$jType] : 0;
132 $backoffs[$jType] = max( $backoffs[$jType], time() +
$ttw );
135 // Break out if we hit the job count or wall time limits...
136 if ( $maxJobs && $jobsRun >= $maxJobs ) {
138 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
142 // Don't let any of the main DB slaves get backed up
143 $timePassed = time() - $lastTime;
144 if ( $timePassed >= 5 ||
$timePassed < 0 ) {
148 // Don't let any queue slaves/backups fall behind
149 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
150 $group->waitForBackups();
153 // Bail if near-OOM instead of in a job
154 $this->assertMemoryOK();
156 } while ( $job ); // stop when there are no jobs
157 // Sync the persistent backoffs for the next runJobs.php pass
158 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
159 if ( $backoffs !== $startingBackoffs ) {
160 $this->syncBackoffs( $backoffs );
166 * @return integer Seconds for this runner to avoid doing more jobs of this type
167 * @see $wgJobBackoffThrottling
169 private function getBackoffTimeToWait( Job
$job ) {
170 global $wgJobBackoffThrottling;
172 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ) {
173 return 0; // not throttled
175 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
176 if ( $itemsPerSecond <= 0 ) {
177 return 0; // not throttled
181 if ( $job->workItemCount() > 0 ) {
182 $seconds = floor( $job->workItemCount() / $itemsPerSecond );
183 $remainder = $job->workItemCount() %
$itemsPerSecond;
184 $seconds +
= ( mt_rand( 1, $itemsPerSecond ) <= $remainder ) ?
1 : 0;
187 return (int)$seconds;
191 * Get the previous backoff expiries from persistent storage
193 * @return array Map of (job type => backoff expiry timestamp)
195 private function loadBackoffs() {
196 $section = new ProfileSection( __METHOD__
);
199 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
200 if ( is_file( $file ) ) {
201 $handle = fopen( $file, 'rb' );
202 flock( $handle, LOCK_SH
);
203 $content = stream_get_contents( $handle );
204 flock( $handle, LOCK_UN
);
206 $backoffs = json_decode( $content, true ) ?
: array();
213 * Merge the current backoff expiries from persistent storage
215 * @param array $backoffs Map of (job type => backoff expiry timestamp)
217 private function syncBackoffs( array $backoffs ) {
218 $section = new ProfileSection( __METHOD__
);
220 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
221 $handle = fopen( $file, 'wb+' );
222 flock( $handle, LOCK_EX
);
223 $content = stream_get_contents( $handle );
224 $cBackoffs = json_decode( $content, true ) ?
: array();
225 foreach ( $backoffs as $type => $timestamp ) {
226 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ?
$cBackoffs[$type] : 0;
227 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
229 ftruncate( $handle, 0 );
230 fwrite( $handle, json_encode( $backoffs ) );
231 flock( $handle, LOCK_UN
);
236 * Make sure that this script is not too close to the memory usage limit.
237 * It is better to die in between jobs than OOM right in the middle of one.
238 * @throws MWException
240 private function assertMemoryOK() {
241 static $maxBytes = null;
242 if ( $maxBytes === null ) {
244 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
245 list( , $num, $unit ) = $m;
246 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
247 $maxBytes = $num * $conv[strtolower( $unit )];
252 $usedBytes = memory_get_usage();
253 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
254 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
259 * Log the job message
260 * @param $msg String The message to log
262 private function runJobsLog( $msg ) {
263 $this->output( wfTimestamp( TS_DB
) . " $msg\n" );
264 wfDebugLog( 'runJobs', $msg );
268 $maintClass = "RunJobs";
269 require_once RUN_MAINTENANCE_IF_MAIN
;