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