f7d5fc07e7db8aa4c3c35f69d0340185437e8094
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 ) {
107 $error = get_class( $e ) . ': ' . $e->getMessage();
108 $e->report(); // write error to STDERR and the log
110 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
111 wfProfileOut( __METHOD__
. '-' . get_class( $job ) );
115 // Mark the job as done on success or when the job cannot be retried
116 if ( $status !== false ||
!$job->allowRetries() ) {
117 $group->ack( $job ); // done
120 if ( $status === false ) {
121 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
123 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
126 // Back off of certain jobs for a while
127 $ttw = $this->getBackoffTimeToWait( $job );
129 $jType = $job->getType();
130 $backoffs[$jType] = isset( $backoffs[$jType] ) ?
$backoffs[$jType] : 0;
131 $backoffs[$jType] = max( $backoffs[$jType], time() +
$ttw );
134 // Break out if we hit the job count or wall time limits...
135 if ( $maxJobs && $jobsRun >= $maxJobs ) {
137 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
141 // Don't let any of the main DB slaves get backed up
142 $timePassed = time() - $lastTime;
143 if ( $timePassed >= 5 ||
$timePassed < 0 ) {
147 // Don't let any queue slaves/backups fall behind
148 if ( $jobsRun > 0 && ( $jobsRun %
100 ) == 0 ) {
149 $group->waitForBackups();
152 // Bail if near-OOM instead of in a job
153 $this->assertMemoryOK();
155 } while ( $job ); // stop when there are no jobs
156 // Sync the persistent backoffs for the next runJobs.php pass
157 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
158 if ( $backoffs !== $startingBackoffs ) {
159 $this->syncBackoffs( $backoffs );
165 * @return integer Seconds for this runner to avoid doing more jobs of this type
166 * @see $wgJobBackoffThrottling
168 private function getBackoffTimeToWait( Job
$job ) {
169 global $wgJobBackoffThrottling;
171 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ) {
172 return 0; // not throttled
174 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
175 if ( $itemsPerSecond <= 0 ) {
176 return 0; // not throttled
180 if ( $job->workItemCount() > 0 ) {
181 $seconds = floor( $job->workItemCount() / $itemsPerSecond );
182 $remainder = $job->workItemCount() %
$itemsPerSecond;
183 $seconds +
= ( mt_rand( 1, $itemsPerSecond ) <= $remainder ) ?
1 : 0;
186 return (int)$seconds;
190 * Get the previous backoff expiries from persistent storage
192 * @return array Map of (job type => backoff expiry timestamp)
194 private function loadBackoffs() {
195 $section = new ProfileSection( __METHOD__
);
198 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
199 if ( is_file( $file ) ) {
200 $handle = fopen( $file, 'rb' );
201 flock( $handle, LOCK_SH
);
202 $content = stream_get_contents( $handle );
203 flock( $handle, LOCK_UN
);
205 $backoffs = json_decode( $content, true ) ?
: array();
212 * Merge the current backoff expiries from persistent storage
214 * @param array $backoffs Map of (job type => backoff expiry timestamp)
216 private function syncBackoffs( array $backoffs ) {
217 $section = new ProfileSection( __METHOD__
);
219 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
220 $handle = fopen( $file, 'wb+' );
221 flock( $handle, LOCK_EX
);
222 $content = stream_get_contents( $handle );
223 $cBackoffs = json_decode( $content, true ) ?
: array();
224 foreach ( $backoffs as $type => $timestamp ) {
225 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ?
$cBackoffs[$type] : 0;
226 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
228 ftruncate( $handle, 0 );
229 fwrite( $handle, json_encode( $backoffs ) );
230 flock( $handle, LOCK_UN
);
235 * Make sure that this script is not too close to the memory usage limit.
236 * It is better to die in between jobs than OOM right in the middle of one.
237 * @throws MWException
239 private function assertMemoryOK() {
240 static $maxBytes = null;
241 if ( $maxBytes === null ) {
243 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
244 list( , $num, $unit ) = $m;
245 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
246 $maxBytes = $num * $conv[strtolower( $unit )];
251 $usedBytes = memory_get_usage();
252 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
253 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
258 * Log the job message
259 * @param $msg String The message to log
261 private function runJobsLog( $msg ) {
262 $this->output( wfTimestamp( TS_DB
) . " $msg\n" );
263 wfDebugLog( 'runJobs', $msg );
267 $maintClass = "RunJobs";
268 require_once RUN_MAINTENANCE_IF_MAIN
;