Show the revision list immediately on "umerge" log action links
[lhc/web/wiklou.git] / includes / jobqueue / JobRunner.php
1 <?php
2 /**
3 * Job queue runner utility methods
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 JobQueue
22 */
23
24 /**
25 * Job queue runner utility methods
26 *
27 * @ingroup JobQueue
28 * @since 1.24
29 */
30 class JobRunner {
31 /** @var callable|null Debug output handler */
32 protected $debug;
33
34 /**
35 * @param callable $debug Optional debug output handler
36 */
37 public function setDebugHandler( $debug ) {
38 $this->debug = $debug;
39 }
40
41 /**
42 * Run jobs of the specified number/type for the specified time
43 *
44 * The response map has a 'job' field that lists status of each job, including:
45 * - type : the job type
46 * - status : ok/failed
47 * - error : any error message string
48 * - time : the job run time in ms
49 * The response map also has:
50 * - backoffs : the (job type => seconds) map of backoff times
51 * - elapsed : the total time spent running tasks in ms
52 * - reached : the reason the script finished, one of (none-ready, job-limit, time-limit)
53 *
54 * This method outputs status information only if a debug handler was set.
55 * Any exceptions are caught and logged, but are not reported as output.
56 *
57 * @param array $options Map of parameters:
58 * - type : the job type (or false for the default types)
59 * - maxJobs : maximum number of jobs to run
60 * - maxTime : maximum time in seconds before stopping
61 * - throttle : whether to respect job backoff configuration
62 * @return array Summary response that can easily be JSON serialized
63 */
64 public function run( array $options ) {
65 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
66
67 $type = isset( $options['type'] ) ? $options['type'] : false;
68 $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false;
69 $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false;
70 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
71
72 $group = JobQueueGroup::singleton();
73 // Handle any required periodic queue maintenance
74 $count = $group->executeReadyPeriodicTasks();
75 if ( $count > 0 ) {
76 $this->runJobsLog( "Executed $count periodic queue task(s)." );
77 }
78
79 // Flush any pending DB writes for sanity
80 wfGetLBFactory()->commitMasterChanges();
81
82 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
83 $startingBackoffs = $backoffs; // avoid unnecessary writes
84 $backoffExpireFunc = function ( $t ) {
85 return $t > time();
86 };
87
88 $jobsRun = 0; // counter
89 $timeMsTotal = 0;
90 $flags = JobQueueGroup::USE_CACHE;
91 $startTime = microtime( true ); // time since jobs started running
92 $lastTime = microtime( true ); // time since last slave check
93 do {
94 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
95 $blacklist = $noThrottle ? array() : array_keys( $backoffs );
96 if ( $type === false ) {
97 $job = $group->pop( JobQueueGroup::TYPE_DEFAULT, $flags, $blacklist );
98 } elseif ( in_array( $type, $blacklist ) ) {
99 $job = false; // requested queue in backoff state
100 } else {
101 $job = $group->pop( $type ); // job from a single queue
102 }
103 if ( $job ) { // found a job
104 $jType = $job->getType();
105
106 $this->runJobsLog( $job->toString() . " STARTING" );
107
108 // Run the job...
109 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
110 $t = microtime( true );
111 try {
112 ++$jobsRun;
113 $status = $job->run();
114 $error = $job->getLastError();
115 wfGetLBFactory()->commitMasterChanges();
116 } catch ( MWException $e ) {
117 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
118 $status = false;
119 $error = get_class( $e ) . ': ' . $e->getMessage();
120 MWExceptionHandler::logException( $e );
121 }
122 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
123 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
124 $timeMsTotal += $timeMs;
125
126 // Mark the job as done on success or when the job cannot be retried
127 if ( $status !== false || !$job->allowRetries() ) {
128 $group->ack( $job ); // done
129 }
130
131 if ( $status === false ) {
132 $this->runJobsLog( $job->toString() . " t=$timeMs error={$error}" );
133 } else {
134 $this->runJobsLog( $job->toString() . " t=$timeMs good" );
135 }
136
137 $response['jobs'][] = array(
138 'type' => $jType,
139 'status' => ( $status === false ) ? 'failed' : 'ok',
140 'error' => $error,
141 'time' => $timeMs
142 );
143
144 // Back off of certain jobs for a while (for throttling and for errors)
145 $ttw = $this->getBackoffTimeToWait( $job );
146 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
147 $ttw = max( $ttw, 30 );
148 }
149 if ( $ttw > 0 ) {
150 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
151 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
152 }
153
154 // Break out if we hit the job count or wall time limits...
155 if ( $maxJobs && $jobsRun >= $maxJobs ) {
156 $response['reached'] = 'job-limit';
157 break;
158 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
159 $response['reached'] = 'time-limit';
160 break;
161 }
162
163 // Don't let any of the main DB slaves get backed up
164 $timePassed = microtime( true ) - $lastTime;
165 if ( $timePassed >= 5 || $timePassed < 0 ) {
166 wfWaitForSlaves( $lastTime );
167 $lastTime = microtime( true );
168 }
169 // Don't let any queue slaves/backups fall behind
170 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
171 $group->waitForBackups();
172 }
173
174 // Bail if near-OOM instead of in a job
175 $this->assertMemoryOK();
176 }
177 } while ( $job ); // stop when there are no jobs
178
179 // Sync the persistent backoffs for the next runJobs.php pass
180 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
181 if ( $backoffs !== $startingBackoffs ) {
182 $this->syncBackoffs( $backoffs );
183 }
184
185 $response['backoffs'] = $backoffs;
186 $response['elapsed'] = $timeMsTotal;
187
188 return $response;
189 }
190
191 /**
192 * @param Job $job
193 * @return int Seconds for this runner to avoid doing more jobs of this type
194 * @see $wgJobBackoffThrottling
195 */
196 private function getBackoffTimeToWait( Job $job ) {
197 global $wgJobBackoffThrottling;
198
199 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
200 $job instanceof DuplicateJob // no work was done
201 ) {
202 return 0; // not throttled
203 }
204
205 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
206 if ( $itemsPerSecond <= 0 ) {
207 return 0; // not throttled
208 }
209
210 $seconds = 0;
211 if ( $job->workItemCount() > 0 ) {
212 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
213 // use randomized rounding
214 $seconds = floor( $exactSeconds );
215 $remainder = $exactSeconds - $seconds;
216 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
217 }
218
219 return (int)$seconds;
220 }
221
222 /**
223 * Get the previous backoff expiries from persistent storage
224 *
225 * @return array Map of (job type => backoff expiry timestamp)
226 */
227 private function loadBackoffs() {
228 $section = new ProfileSection( __METHOD__ );
229
230 $backoffs = array();
231 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
232 if ( is_file( $file ) ) {
233 $handle = fopen( $file, 'rb' );
234 flock( $handle, LOCK_SH );
235 $content = stream_get_contents( $handle );
236 flock( $handle, LOCK_UN );
237 fclose( $handle );
238 $backoffs = json_decode( $content, true ) ?: array();
239 }
240
241 return $backoffs;
242 }
243
244 /**
245 * Merge the current backoff expiries from persistent storage
246 *
247 * @param array $backoffs Map of (job type => backoff expiry timestamp)
248 */
249 private function syncBackoffs( array $backoffs ) {
250 $section = new ProfileSection( __METHOD__ );
251
252 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
253 $handle = fopen( $file, 'wb+' );
254 flock( $handle, LOCK_EX );
255 $content = stream_get_contents( $handle );
256 $cBackoffs = json_decode( $content, true ) ?: array();
257 foreach ( $backoffs as $type => $timestamp ) {
258 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
259 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
260 }
261 ftruncate( $handle, 0 );
262 fwrite( $handle, json_encode( $backoffs ) );
263 flock( $handle, LOCK_UN );
264 fclose( $handle );
265 }
266
267 /**
268 * Make sure that this script is not too close to the memory usage limit.
269 * It is better to die in between jobs than OOM right in the middle of one.
270 * @throws MWException
271 */
272 private function assertMemoryOK() {
273 static $maxBytes = null;
274 if ( $maxBytes === null ) {
275 $m = array();
276 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
277 list( , $num, $unit ) = $m;
278 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
279 $maxBytes = $num * $conv[strtolower( $unit )];
280 } else {
281 $maxBytes = 0;
282 }
283 }
284 $usedBytes = memory_get_usage();
285 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
286 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
287 }
288 }
289
290 /**
291 * Log the job message
292 * @param string $msg The message to log
293 */
294 private function runJobsLog( $msg ) {
295 if ( $this->debug ) {
296 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
297 }
298 wfDebugLog( 'runJobs', $msg );
299 }
300 }