Merge "Remove unused 'prefs-beta' message"
[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 }
40
41 public function memoryLimit() {
42 if ( $this->hasOption( 'memory-limit' ) ) {
43 return parent::memoryLimit();
44 }
45 // Don't eat all memory on the machine if we get a bad job.
46 return "150M";
47 }
48
49 public function execute() {
50 if ( wfReadOnly() ) {
51 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
52 }
53
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' ) {
61 exit( 0 );
62 }
63 }
64 }
65
66 $type = $this->getOption( 'type', false );
67 $maxJobs = $this->getOption( 'maxjobs', false );
68 $maxTime = $this->getOption( 'maxtime', false );
69 $startTime = time();
70
71 $group = JobQueueGroup::singleton();
72 // Handle any required periodic queue maintenance
73 $count = $group->executeReadyPeriodicTasks();
74 if ( $count > 0 ) {
75 $this->runJobsLog( "Executed $count periodic queue task(s)." );
76 }
77
78 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
79 $startingBackoffs = $backoffs; // avoid unnecessary writes
80 $backoffExpireFunc = function( $t ) { return $t > time(); };
81
82 $jobsRun = 0; // counter
83 $flags = JobQueueGroup::USE_CACHE;
84 $lastTime = time(); // time since last slave check
85 do {
86 if ( $type === false ) {
87 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
88 $blacklist = array_keys( $backoffs );
89 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
90 } else {
91 $job = $group->pop( $type ); // job from a single queue
92 }
93 if ( $job ) { // found a job
94 ++$jobsRun;
95 $this->runJobsLog( $job->toString() . " STARTING" );
96
97 // Set timer to stop the job if too much CPU time is used
98 set_time_limit( $maxTime ?: 0 );
99 // Run the job...
100 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
101 $t = microtime( true );
102 try {
103 $status = $job->run();
104 $error = $job->getLastError();
105 } catch ( MWException $e ) {
106 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
107 $status = false;
108 $error = get_class( $e ) . ': ' . $e->getMessage();
109 $e->report(); // write error to STDERR and the log
110 }
111 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
112 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
113 // Disable the timer
114 set_time_limit( 0 );
115
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
119 }
120
121 if ( $status === false ) {
122 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
123 } else {
124 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
125 }
126
127 // Back off of certain jobs for a while
128 $ttw = $this->getBackoffTimeToWait( $job );
129 if ( $ttw > 0 ) {
130 $jType = $job->getType();
131 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
132 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
133 }
134
135 // Break out if we hit the job count or wall time limits...
136 if ( $maxJobs && $jobsRun >= $maxJobs ) {
137 break;
138 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
139 break;
140 }
141
142 // Don't let any of the main DB slaves get backed up
143 $timePassed = time() - $lastTime;
144 if ( $timePassed >= 5 || $timePassed < 0 ) {
145 wfWaitForSlaves();
146 $lastTime = time();
147 }
148 // Don't let any queue slaves/backups fall behind
149 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
150 $group->waitForBackups();
151 }
152
153 // Bail if near-OOM instead of in a job
154 $this->assertMemoryOK();
155 }
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 );
161 }
162 }
163
164 /**
165 * @param Job $job
166 * @return integer Seconds for this runner to avoid doing more jobs of this type
167 * @see $wgJobBackoffThrottling
168 */
169 private function getBackoffTimeToWait( Job $job ) {
170 global $wgJobBackoffThrottling;
171
172 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ) {
173 return 0; // not throttled
174 }
175 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
176 if ( $itemsPerSecond <= 0 ) {
177 return 0; // not throttled
178 }
179
180 $seconds = 0;
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;
185 }
186
187 return (int)$seconds;
188 }
189
190 /**
191 * Get the previous backoff expiries from persistent storage
192 *
193 * @return array Map of (job type => backoff expiry timestamp)
194 */
195 private function loadBackoffs() {
196 $section = new ProfileSection( __METHOD__ );
197
198 $backoffs = array();
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 );
205 fclose( $handle );
206 $backoffs = json_decode( $content, true ) ?: array();
207 }
208
209 return $backoffs;
210 }
211
212 /**
213 * Merge the current backoff expiries from persistent storage
214 *
215 * @param array $backoffs Map of (job type => backoff expiry timestamp)
216 */
217 private function syncBackoffs( array $backoffs ) {
218 $section = new ProfileSection( __METHOD__ );
219
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] );
228 }
229 ftruncate( $handle, 0 );
230 fwrite( $handle, json_encode( $backoffs ) );
231 flock( $handle, LOCK_UN );
232 fclose( $handle );
233 }
234
235 /**
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
239 */
240 private function assertMemoryOK() {
241 static $maxBytes = null;
242 if ( $maxBytes === null ) {
243 $m = array();
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 )];
248 } else {
249 $maxBytes = 0;
250 }
251 }
252 $usedBytes = memory_get_usage();
253 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
254 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
255 }
256 }
257
258 /**
259 * Log the job message
260 * @param $msg String The message to log
261 */
262 private function runJobsLog( $msg ) {
263 $this->output( wfTimestamp( TS_DB ) . " $msg\n" );
264 wfDebugLog( 'runJobs', $msg );
265 }
266 }
267
268 $maintClass = "RunJobs";
269 require_once RUN_MAINTENANCE_IF_MAIN;