Merge "Remove #bodyContent { width: 100%; }"
[mediawiki.git] / maintenance / runJobs.php
blobdc9c7632a66cf55c9a86bbba6254c40384e8310d
1 <?php
2 /**
3 * Run pending jobs.
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
20 * @file
21 * @ingroup Maintenance
24 require_once __DIR__ . '/Maintenance.php';
26 /**
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();
46 // Don't eat all memory on the machine if we get a bad job.
47 return "150M";
50 public function execute() {
51 if ( wfReadOnly() ) {
52 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
55 if ( $this->hasOption( 'procs' ) ) {
56 $procs = intval( $this->getOption( 'procs' ) );
57 if ( $procs < 1 || $procs > 1000 ) {
58 $this->error( "Invalid argument to --procs", true );
59 } elseif ( $procs != 1 ) {
60 $fc = new ForkController( $procs );
61 if ( $fc->start() != 'child' ) {
62 exit( 0 );
67 $type = $this->getOption( 'type', false );
68 $maxJobs = $this->getOption( 'maxjobs', false );
69 $maxTime = $this->getOption( 'maxtime', false );
70 $noThrottle = $this->hasOption( 'nothrottle' );
71 $startTime = time();
73 $group = JobQueueGroup::singleton();
74 // Handle any required periodic queue maintenance
75 $count = $group->executeReadyPeriodicTasks();
76 if ( $count > 0 ) {
77 $this->runJobsLog( "Executed $count periodic queue task(s)." );
80 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
81 $startingBackoffs = $backoffs; // avoid unnecessary writes
82 $backoffExpireFunc = function( $t ) { return $t > time(); };
84 $jobsRun = 0; // counter
85 $flags = JobQueueGroup::USE_CACHE;
86 $lastTime = time(); // time since last slave check
87 do {
88 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
89 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
90 if ( $type === false ) {
91 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
92 } elseif ( in_array( $type, $blacklist ) ) {
93 $job = false; // requested queue in backoff state
94 } else {
95 $job = $group->pop( $type ); // job from a single queue
97 if ( $job ) { // found a job
98 ++$jobsRun;
99 $this->runJobsLog( $job->toString() . " STARTING" );
101 // Set timer to stop the job if too much CPU time is used
102 set_time_limit( $maxTime ?: 0 );
103 // Run the job...
104 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
105 $t = microtime( true );
106 try {
107 $status = $job->run();
108 $error = $job->getLastError();
109 } catch ( MWException $e ) {
110 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
111 $status = false;
112 $error = get_class( $e ) . ': ' . $e->getMessage();
113 $e->report(); // write error to STDERR and the log
115 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
116 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
117 // Disable the timer
118 set_time_limit( 0 );
120 // Mark the job as done on success or when the job cannot be retried
121 if ( $status !== false || !$job->allowRetries() ) {
122 $group->ack( $job ); // done
125 if ( $status === false ) {
126 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
127 } else {
128 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
131 // Back off of certain jobs for a while
132 $ttw = $this->getBackoffTimeToWait( $job );
133 if ( $ttw > 0 ) {
134 $jType = $job->getType();
135 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
136 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
139 // Break out if we hit the job count or wall time limits...
140 if ( $maxJobs && $jobsRun >= $maxJobs ) {
141 break;
142 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
143 break;
146 // Don't let any of the main DB slaves get backed up
147 $timePassed = time() - $lastTime;
148 if ( $timePassed >= 5 || $timePassed < 0 ) {
149 wfWaitForSlaves();
150 $lastTime = time();
152 // Don't let any queue slaves/backups fall behind
153 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
154 $group->waitForBackups();
157 // Bail if near-OOM instead of in a job
158 $this->assertMemoryOK();
160 } while ( $job ); // stop when there are no jobs
161 // Sync the persistent backoffs for the next runJobs.php pass
162 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
163 if ( $backoffs !== $startingBackoffs ) {
164 $this->syncBackoffs( $backoffs );
169 * @param Job $job
170 * @return integer Seconds for this runner to avoid doing more jobs of this type
171 * @see $wgJobBackoffThrottling
173 private function getBackoffTimeToWait( Job $job ) {
174 global $wgJobBackoffThrottling;
176 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ) {
177 return 0; // not throttled
179 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
180 if ( $itemsPerSecond <= 0 ) {
181 return 0; // not throttled
184 $seconds = 0;
185 if ( $job->workItemCount() > 0 ) {
186 $seconds = floor( $job->workItemCount() / $itemsPerSecond );
187 $remainder = $job->workItemCount() % $itemsPerSecond;
188 $seconds += ( mt_rand( 1, $itemsPerSecond ) <= $remainder ) ? 1 : 0;
191 return (int)$seconds;
195 * Get the previous backoff expiries from persistent storage
197 * @return array Map of (job type => backoff expiry timestamp)
199 private function loadBackoffs() {
200 $section = new ProfileSection( __METHOD__ );
202 $backoffs = array();
203 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
204 if ( is_file( $file ) ) {
205 $handle = fopen( $file, 'rb' );
206 flock( $handle, LOCK_SH );
207 $content = stream_get_contents( $handle );
208 flock( $handle, LOCK_UN );
209 fclose( $handle );
210 $backoffs = json_decode( $content, true ) ?: array();
213 return $backoffs;
217 * Merge the current backoff expiries from persistent storage
219 * @param array $backoffs Map of (job type => backoff expiry timestamp)
221 private function syncBackoffs( array $backoffs ) {
222 $section = new ProfileSection( __METHOD__ );
224 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
225 $handle = fopen( $file, 'wb+' );
226 flock( $handle, LOCK_EX );
227 $content = stream_get_contents( $handle );
228 $cBackoffs = json_decode( $content, true ) ?: array();
229 foreach ( $backoffs as $type => $timestamp ) {
230 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
231 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
233 ftruncate( $handle, 0 );
234 fwrite( $handle, json_encode( $backoffs ) );
235 flock( $handle, LOCK_UN );
236 fclose( $handle );
240 * Make sure that this script is not too close to the memory usage limit.
241 * It is better to die in between jobs than OOM right in the middle of one.
242 * @throws MWException
244 private function assertMemoryOK() {
245 static $maxBytes = null;
246 if ( $maxBytes === null ) {
247 $m = array();
248 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
249 list( , $num, $unit ) = $m;
250 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
251 $maxBytes = $num * $conv[strtolower( $unit )];
252 } else {
253 $maxBytes = 0;
256 $usedBytes = memory_get_usage();
257 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
258 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
263 * Log the job message
264 * @param $msg String The message to log
266 private function runJobsLog( $msg ) {
267 $this->output( wfTimestamp( TS_DB ) . " $msg\n" );
268 wfDebugLog( 'runJobs', $msg );
272 $maintClass = "RunJobs";
273 require_once RUN_MAINTENANCE_IF_MAIN;