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