Merge "Introducing pp_sortkey."
[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 = time(); // 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 // Set timer to stop the job if too much CPU time is used
105 set_time_limit( $maxTime ? : 0 );
106 // Run the job...
107 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
108 $t = microtime( true );
109 try {
110 $status = $job->run();
111 $error = $job->getLastError();
112 } catch ( MWException $e ) {
113 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
114 $status = false;
115 $error = get_class( $e ) . ': ' . $e->getMessage();
116 $e->report(); // write error to STDERR and the log
117 }
118 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
119 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
120 // Disable the timer
121 set_time_limit( 0 );
122
123 // Mark the job as done on success or when the job cannot be retried
124 if ( $status !== false || !$job->allowRetries() ) {
125 $group->ack( $job ); // done
126 }
127
128 if ( $status === false ) {
129 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
130 } else {
131 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
132 }
133
134 // Back off of certain jobs for a while
135 $ttw = $this->getBackoffTimeToWait( $job );
136 if ( $ttw > 0 ) {
137 $jType = $job->getType();
138 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
139 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
140 }
141
142 // Break out if we hit the job count or wall time limits...
143 if ( $maxJobs && $jobsRun >= $maxJobs ) {
144 break;
145 } elseif ( $maxTime && ( time() - $startTime ) > $maxTime ) {
146 break;
147 }
148
149 // Don't let any of the main DB slaves get backed up
150 $timePassed = time() - $lastTime;
151 if ( $timePassed >= 5 || $timePassed < 0 ) {
152 wfWaitForSlaves();
153 $lastTime = time();
154 }
155 // Don't let any queue slaves/backups fall behind
156 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
157 $group->waitForBackups();
158 }
159
160 // Bail if near-OOM instead of in a job
161 $this->assertMemoryOK();
162 }
163 } while ( $job ); // stop when there are no jobs
164 // Sync the persistent backoffs for the next runJobs.php pass
165 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
166 if ( $backoffs !== $startingBackoffs ) {
167 $this->syncBackoffs( $backoffs );
168 }
169 }
170
171 /**
172 * @param Job $job
173 * @return int Seconds for this runner to avoid doing more jobs of this type
174 * @see $wgJobBackoffThrottling
175 */
176 private function getBackoffTimeToWait( Job $job ) {
177 global $wgJobBackoffThrottling;
178
179 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ) {
180 return 0; // not throttled
181 }
182 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
183 if ( $itemsPerSecond <= 0 ) {
184 return 0; // not throttled
185 }
186
187 $seconds = 0;
188 if ( $job->workItemCount() > 0 ) {
189 $seconds = floor( $job->workItemCount() / $itemsPerSecond );
190 $remainder = $job->workItemCount() % $itemsPerSecond;
191 $seconds += ( mt_rand( 1, $itemsPerSecond ) <= $remainder ) ? 1 : 0;
192 }
193
194 return (int)$seconds;
195 }
196
197 /**
198 * Get the previous backoff expiries from persistent storage
199 *
200 * @return array Map of (job type => backoff expiry timestamp)
201 */
202 private function loadBackoffs() {
203 $section = new ProfileSection( __METHOD__ );
204
205 $backoffs = array();
206 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
207 if ( is_file( $file ) ) {
208 $handle = fopen( $file, 'rb' );
209 flock( $handle, LOCK_SH );
210 $content = stream_get_contents( $handle );
211 flock( $handle, LOCK_UN );
212 fclose( $handle );
213 $backoffs = json_decode( $content, true ) ? : array();
214 }
215
216 return $backoffs;
217 }
218
219 /**
220 * Merge the current backoff expiries from persistent storage
221 *
222 * @param array $backoffs Map of (job type => backoff expiry timestamp)
223 */
224 private function syncBackoffs( array $backoffs ) {
225 $section = new ProfileSection( __METHOD__ );
226
227 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
228 $handle = fopen( $file, 'wb+' );
229 flock( $handle, LOCK_EX );
230 $content = stream_get_contents( $handle );
231 $cBackoffs = json_decode( $content, true ) ? : array();
232 foreach ( $backoffs as $type => $timestamp ) {
233 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
234 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
235 }
236 ftruncate( $handle, 0 );
237 fwrite( $handle, json_encode( $backoffs ) );
238 flock( $handle, LOCK_UN );
239 fclose( $handle );
240 }
241
242 /**
243 * Make sure that this script is not too close to the memory usage limit.
244 * It is better to die in between jobs than OOM right in the middle of one.
245 * @throws MWException
246 */
247 private function assertMemoryOK() {
248 static $maxBytes = null;
249 if ( $maxBytes === null ) {
250 $m = array();
251 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
252 list( , $num, $unit ) = $m;
253 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
254 $maxBytes = $num * $conv[strtolower( $unit )];
255 } else {
256 $maxBytes = 0;
257 }
258 }
259 $usedBytes = memory_get_usage();
260 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
261 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
262 }
263 }
264
265 /**
266 * Log the job message
267 * @param string $msg The message to log
268 */
269 private function runJobsLog( $msg ) {
270 $this->output( wfTimestamp( TS_DB ) . " $msg\n" );
271 wfDebugLog( 'runJobs', $msg );
272 }
273 }
274
275 $maintClass = "RunJobs";
276 require_once RUN_MAINTENANCE_IF_MAIN;