Merge "Make users API cache mode public if blockinfo is not queried"
[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 // Don't eat all memory on the machine if we get a bad job.
47 return "150M";
48 }
49
50 public function execute() {
51 if ( wfReadOnly() ) {
52 $this->error( "Unable to run jobs; the wiki is in read-only mode.", 1 ); // die
53 }
54
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 );
63 }
64 }
65 }
66
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();
72
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)." );
78 }
79
80 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
81 $startingBackoffs = $backoffs; // avoid unnecessary writes
82 $backoffExpireFunc = function ( $t ) {
83 return $t > time();
84 };
85
86 $jobsRun = 0; // counter
87 $flags = JobQueueGroup::USE_CACHE;
88 $lastTime = time(); // time since last slave check
89 do {
90 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
91 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
92 if ( $type === false ) {
93 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
94 } elseif ( in_array( $type, $blacklist ) ) {
95 $job = false; // requested queue in backoff state
96 } else {
97 $job = $group->pop( $type ); // job from a single queue
98 }
99 if ( $job ) { // found a job
100 ++$jobsRun;
101 $this->runJobsLog( $job->toString() . " STARTING" );
102
103 // Set timer to stop the job if too much CPU time is used
104 set_time_limit( $maxTime ?: 0 );
105 // Run the job...
106 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
107 $t = microtime( true );
108 try {
109 $status = $job->run();
110 $error = $job->getLastError();
111 } catch ( MWException $e ) {
112 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
113 $status = false;
114 $error = get_class( $e ) . ': ' . $e->getMessage();
115 $e->report(); // write error to STDERR and the log
116 }
117 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
118 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
119 // Disable the timer
120 set_time_limit( 0 );
121
122 // Mark the job as done on success or when the job cannot be retried
123 if ( $status !== false || !$job->allowRetries() ) {
124 $group->ack( $job ); // done
125 }
126
127 if ( $status === false ) {
128 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
129 } else {
130 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
131 }
132
133 // Back off of certain jobs for a while
134 $ttw = $this->getBackoffTimeToWait( $job );
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 = time() - $lastTime;
150 if ( $timePassed >= 5 || $timePassed < 0 ) {
151 wfWaitForSlaves();
152 $lastTime = time();
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 return 0; // not throttled
180 }
181 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
182 if ( $itemsPerSecond <= 0 ) {
183 return 0; // not throttled
184 }
185
186 $seconds = 0;
187 if ( $job->workItemCount() > 0 ) {
188 $seconds = floor( $job->workItemCount() / $itemsPerSecond );
189 $remainder = $job->workItemCount() % $itemsPerSecond;
190 $seconds += ( mt_rand( 1, $itemsPerSecond ) <= $remainder ) ? 1 : 0;
191 }
192
193 return (int)$seconds;
194 }
195
196 /**
197 * Get the previous backoff expiries from persistent storage
198 *
199 * @return array Map of (job type => backoff expiry timestamp)
200 */
201 private function loadBackoffs() {
202 $section = new ProfileSection( __METHOD__ );
203
204 $backoffs = array();
205 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
206 if ( is_file( $file ) ) {
207 $handle = fopen( $file, 'rb' );
208 flock( $handle, LOCK_SH );
209 $content = stream_get_contents( $handle );
210 flock( $handle, LOCK_UN );
211 fclose( $handle );
212 $backoffs = json_decode( $content, true ) ?: array();
213 }
214
215 return $backoffs;
216 }
217
218 /**
219 * Merge the current backoff expiries from persistent storage
220 *
221 * @param array $backoffs Map of (job type => backoff expiry timestamp)
222 */
223 private function syncBackoffs( array $backoffs ) {
224 $section = new ProfileSection( __METHOD__ );
225
226 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
227 $handle = fopen( $file, 'wb+' );
228 flock( $handle, LOCK_EX );
229 $content = stream_get_contents( $handle );
230 $cBackoffs = json_decode( $content, true ) ?: array();
231 foreach ( $backoffs as $type => $timestamp ) {
232 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
233 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
234 }
235 ftruncate( $handle, 0 );
236 fwrite( $handle, json_encode( $backoffs ) );
237 flock( $handle, LOCK_UN );
238 fclose( $handle );
239 }
240
241 /**
242 * Make sure that this script is not too close to the memory usage limit.
243 * It is better to die in between jobs than OOM right in the middle of one.
244 * @throws MWException
245 */
246 private function assertMemoryOK() {
247 static $maxBytes = null;
248 if ( $maxBytes === null ) {
249 $m = array();
250 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
251 list( , $num, $unit ) = $m;
252 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
253 $maxBytes = $num * $conv[strtolower( $unit )];
254 } else {
255 $maxBytes = 0;
256 }
257 }
258 $usedBytes = memory_get_usage();
259 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
260 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
261 }
262 }
263
264 /**
265 * Log the job message
266 * @param string $msg The message to log
267 */
268 private function runJobsLog( $msg ) {
269 $this->output( wfTimestamp( TS_DB ) . " $msg\n" );
270 wfDebugLog( 'runJobs', $msg );
271 }
272 }
273
274 $maintClass = "RunJobs";
275 require_once RUN_MAINTENANCE_IF_MAIN;