Merge "Remove two unused constants from EditPage.php"
[lhc/web/wiklou.git] / maintenance / runJobs.php
1 <?php
2 /**
3 * Run pending jobs.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24 require_once __DIR__ . '/Maintenance.php';
25
26 /**
27 * Maintenance script that runs pending jobs.
28 *
29 * @ingroup Maintenance
30 */
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 );
40 }
41
42 public function memoryLimit() {
43 if ( $this->hasOption( 'memory-limit' ) ) {
44 return parent::memoryLimit();
45 }
46
47 // Don't eat all memory on the machine if we get a bad job.
48 return "150M";
49 }
50
51 public function execute() {
52 if ( wfReadOnly() ) {
53 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
54 }
55
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' ) {
63 exit( 0 );
64 }
65 }
66 }
67
68 $type = $this->getOption( 'type', false );
69 $maxJobs = $this->getOption( 'maxjobs', false );
70 $maxTime = $this->getOption( 'maxtime', false );
71 $noThrottle = $this->hasOption( 'nothrottle' );
72 $startTime = time();
73
74 $group = JobQueueGroup::singleton();
75 // Handle any required periodic queue maintenance
76 $count = $group->executeReadyPeriodicTasks();
77 if ( $count > 0 ) {
78 $this->runJobsLog( "Executed $count periodic queue task(s)." );
79 }
80
81 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
82 $startingBackoffs = $backoffs; // avoid unnecessary writes
83 $backoffExpireFunc = function ( $t ) {
84 return $t > time();
85 };
86
87 $jobsRun = 0; // counter
88 $flags = JobQueueGroup::USE_CACHE;
89 $lastTime = microtime( true ); // time since last slave check
90 do {
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
97 } else {
98 $job = $group->pop( $type ); // job from a single queue
99 }
100 if ( $job ) { // found a job
101 ++$jobsRun;
102 $this->runJobsLog( $job->toString() . " STARTING" );
103
104 // Run the job...
105 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
106 $t = microtime( true );
107 try {
108 $status = $job->run();
109 $error = $job->getLastError();
110 } catch ( MWException $e ) {
111 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
112 $status = false;
113 $error = get_class( $e ) . ': ' . $e->getMessage();
114 $e->report(); // write error to STDERR and the log
115 }
116 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
117 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
118
119 // Mark the job as done on success or when the job cannot be retried
120 if ( $status !== false || !$job->allowRetries() ) {
121 $group->ack( $job ); // done
122 }
123
124 if ( $status === false ) {
125 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
126 } else {
127 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
128 }
129
130 // Back off of certain jobs for a while (for throttling and for errors)
131 $ttw = $this->getBackoffTimeToWait( $job );
132 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
133 $ttw = max( $ttw, 30 );
134 }
135 if ( $ttw > 0 ) {
136 $jType = $job->getType();
137 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
138 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
139 }
140
141 // Break out if we hit the job count or wall time limits...
142 if ( $maxJobs && $jobsRun >= $maxJobs ) {
143 break;
144 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
145 break;
146 }
147
148 // Don't let any of the main DB slaves get backed up
149 $timePassed = microtime( true ) - $lastTime;
150 if ( $timePassed >= 5 || $timePassed < 0 ) {
151 wfWaitForSlaves( $lastTime );
152 $lastTime = microtime( true );
153 }
154 // Don't let any queue slaves/backups fall behind
155 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
156 $group->waitForBackups();
157 }
158
159 // Bail if near-OOM instead of in a job
160 $this->assertMemoryOK();
161 }
162 } while ( $job ); // stop when there are no jobs
163 // Sync the persistent backoffs for the next runJobs.php pass
164 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
165 if ( $backoffs !== $startingBackoffs ) {
166 $this->syncBackoffs( $backoffs );
167 }
168 }
169
170 /**
171 * @param Job $job
172 * @return int Seconds for this runner to avoid doing more jobs of this type
173 * @see $wgJobBackoffThrottling
174 */
175 private function getBackoffTimeToWait( Job $job ) {
176 global $wgJobBackoffThrottling;
177
178 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
179 $job instanceof DuplicateJob // no work was done
180 ) {
181 return 0; // not throttled
182 }
183
184 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
185 if ( $itemsPerSecond <= 0 ) {
186 return 0; // not throttled
187 }
188
189 $seconds = 0;
190 if ( $job->workItemCount() > 0 ) {
191 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
192 // use randomized rounding
193 $seconds = floor( $exactSeconds );
194 $remainder = $exactSeconds - $seconds;
195 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
196 }
197
198 return (int)$seconds;
199 }
200
201 /**
202 * Get the previous backoff expiries from persistent storage
203 *
204 * @return array Map of (job type => backoff expiry timestamp)
205 */
206 private function loadBackoffs() {
207 $section = new ProfileSection( __METHOD__ );
208
209 $backoffs = array();
210 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
211 if ( is_file( $file ) ) {
212 $handle = fopen( $file, 'rb' );
213 flock( $handle, LOCK_SH );
214 $content = stream_get_contents( $handle );
215 flock( $handle, LOCK_UN );
216 fclose( $handle );
217 $backoffs = json_decode( $content, true ) ? : array();
218 }
219
220 return $backoffs;
221 }
222
223 /**
224 * Merge the current backoff expiries from persistent storage
225 *
226 * @param array $backoffs Map of (job type => backoff expiry timestamp)
227 */
228 private function syncBackoffs( array $backoffs ) {
229 $section = new ProfileSection( __METHOD__ );
230
231 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
232 $handle = fopen( $file, 'wb+' );
233 flock( $handle, LOCK_EX );
234 $content = stream_get_contents( $handle );
235 $cBackoffs = json_decode( $content, true ) ? : array();
236 foreach ( $backoffs as $type => $timestamp ) {
237 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
238 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
239 }
240 ftruncate( $handle, 0 );
241 fwrite( $handle, json_encode( $backoffs ) );
242 flock( $handle, LOCK_UN );
243 fclose( $handle );
244 }
245
246 /**
247 * Make sure that this script is not too close to the memory usage limit.
248 * It is better to die in between jobs than OOM right in the middle of one.
249 * @throws MWException
250 */
251 private function assertMemoryOK() {
252 static $maxBytes = null;
253 if ( $maxBytes === null ) {
254 $m = array();
255 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
256 list( , $num, $unit ) = $m;
257 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
258 $maxBytes = $num * $conv[strtolower( $unit )];
259 } else {
260 $maxBytes = 0;
261 }
262 }
263 $usedBytes = memory_get_usage();
264 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
265 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
266 }
267 }
268
269 /**
270 * Log the job message
271 * @param string $msg The message to log
272 */
273 private function runJobsLog( $msg ) {
274 $this->output( wfTimestamp( TS_DB ) . " $msg\n" );
275 wfDebugLog( 'runJobs', $msg );
276 }
277 }
278
279 $maintClass = "RunJobs";
280 require_once RUN_MAINTENANCE_IF_MAIN;