Group E-mail settings stuff in Setup.php
[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
58 * @return array Summary response that can easily be JSON serialized
59 */
60 public function run( array $options ) {
61 $response = array( 'jobs' => array(), 'reached' => 'none-ready' );
62
63 $type = isset( $options['type'] ) ? $options['type'] : false;
64 $maxJobs = isset( $options['maxJobs'] ) ? $options['maxJobs'] : false;
65 $maxTime = isset( $options['maxTime'] ) ? $options['maxTime'] : false;
66 $noThrottle = isset( $options['throttle'] ) && !$options['throttle'];
67
68 $group = JobQueueGroup::singleton();
69 // Handle any required periodic queue maintenance
70 $count = $group->executeReadyPeriodicTasks();
71 if ( $count > 0 ) {
72 $this->runJobsLog( "Executed $count periodic queue task(s)." );
73 }
74
75 // Flush any pending DB writes for sanity
76 wfGetLBFactory()->commitMasterChanges();
77
78 $backoffs = $this->loadBackoffs(); // map of (type => UNIX expiry)
79 $startingBackoffs = $backoffs; // avoid unnecessary writes
80 $backoffExpireFunc = function ( $t ) {
81 return $t > time();
82 };
83
84 $jobsRun = 0; // counter
85 $timeMsTotal = 0;
86 $flags = JobQueueGroup::USE_CACHE;
87 $startTime = microtime( true ); // time since jobs started running
88 $lastTime = microtime( true ); // 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 $jType = $job->getType();
101
102 $this->runJobsLog( $job->toString() . " STARTING" );
103
104 // Run the job...
105 wfProfileIn( __METHOD__ . '-' . get_class( $job ) );
106 $t = microtime( true );
107 try {
108 ++$jobsRun;
109 $status = $job->run();
110 $error = $job->getLastError();
111 wfGetLBFactory()->commitMasterChanges();
112 } catch ( MWException $e ) {
113 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
114 $status = false;
115 $error = get_class( $e ) . ': ' . $e->getMessage();
116 MWExceptionHandler::logException( $e );
117 }
118 $timeMs = intval( ( microtime( true ) - $t ) * 1000 );
119 wfProfileOut( __METHOD__ . '-' . get_class( $job ) );
120 $timeMsTotal += $timeMs;
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 $response['jobs'][] = array(
134 'type' => $jType,
135 'status' => ( $status === false ) ? 'failed' : 'ok',
136 'error' => $error,
137 'time' => $timeMs
138 );
139
140 // Back off of certain jobs for a while (for throttling and for errors)
141 $ttw = $this->getBackoffTimeToWait( $job );
142 if ( $status === false && mt_rand( 0, 49 ) == 0 ) {
143 $ttw = max( $ttw, 30 );
144 }
145 if ( $ttw > 0 ) {
146 $backoffs[$jType] = isset( $backoffs[$jType] ) ? $backoffs[$jType] : 0;
147 $backoffs[$jType] = max( $backoffs[$jType], time() + $ttw );
148 }
149
150 // Break out if we hit the job count or wall time limits...
151 if ( $maxJobs && $jobsRun >= $maxJobs ) {
152 $response['reached'] = 'job-limit';
153 break;
154 } elseif ( $maxTime && ( microtime( true ) - $startTime ) > $maxTime ) {
155 $response['reached'] = 'time-limit';
156 break;
157 }
158
159 // Don't let any of the main DB slaves get backed up
160 $timePassed = microtime( true ) - $lastTime;
161 if ( $timePassed >= 5 || $timePassed < 0 ) {
162 wfWaitForSlaves( $lastTime );
163 $lastTime = microtime( true );
164 }
165 // Don't let any queue slaves/backups fall behind
166 if ( $jobsRun > 0 && ( $jobsRun % 100 ) == 0 ) {
167 $group->waitForBackups();
168 }
169
170 // Bail if near-OOM instead of in a job
171 $this->assertMemoryOK();
172 }
173 } while ( $job ); // stop when there are no jobs
174
175 // Sync the persistent backoffs for the next runJobs.php pass
176 $backoffs = array_filter( $backoffs, $backoffExpireFunc );
177 if ( $backoffs !== $startingBackoffs ) {
178 $this->syncBackoffs( $backoffs );
179 }
180
181 $response['backoffs'] = $backoffs;
182 $response['elapsed'] = $timeMsTotal;
183
184 return $response;
185 }
186
187 /**
188 * @param Job $job
189 * @return int Seconds for this runner to avoid doing more jobs of this type
190 * @see $wgJobBackoffThrottling
191 */
192 private function getBackoffTimeToWait( Job $job ) {
193 global $wgJobBackoffThrottling;
194
195 if ( !isset( $wgJobBackoffThrottling[$job->getType()] ) ||
196 $job instanceof DuplicateJob // no work was done
197 ) {
198 return 0; // not throttled
199 }
200
201 $itemsPerSecond = $wgJobBackoffThrottling[$job->getType()];
202 if ( $itemsPerSecond <= 0 ) {
203 return 0; // not throttled
204 }
205
206 $seconds = 0;
207 if ( $job->workItemCount() > 0 ) {
208 $exactSeconds = $job->workItemCount() / $itemsPerSecond;
209 // use randomized rounding
210 $seconds = floor( $exactSeconds );
211 $remainder = $exactSeconds - $seconds;
212 $seconds += ( mt_rand() / mt_getrandmax() < $remainder ) ? 1 : 0;
213 }
214
215 return (int)$seconds;
216 }
217
218 /**
219 * Get the previous backoff expiries from persistent storage
220 *
221 * @return array Map of (job type => backoff expiry timestamp)
222 */
223 private function loadBackoffs() {
224 $section = new ProfileSection( __METHOD__ );
225
226 $backoffs = array();
227 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
228 if ( is_file( $file ) ) {
229 $handle = fopen( $file, 'rb' );
230 flock( $handle, LOCK_SH );
231 $content = stream_get_contents( $handle );
232 flock( $handle, LOCK_UN );
233 fclose( $handle );
234 $backoffs = json_decode( $content, true ) ? : array();
235 }
236
237 return $backoffs;
238 }
239
240 /**
241 * Merge the current backoff expiries from persistent storage
242 *
243 * @param array $backoffs Map of (job type => backoff expiry timestamp)
244 */
245 private function syncBackoffs( array $backoffs ) {
246 $section = new ProfileSection( __METHOD__ );
247
248 $file = wfTempDir() . '/mw-runJobs-backoffs.json';
249 $handle = fopen( $file, 'wb+' );
250 flock( $handle, LOCK_EX );
251 $content = stream_get_contents( $handle );
252 $cBackoffs = json_decode( $content, true ) ? : array();
253 foreach ( $backoffs as $type => $timestamp ) {
254 $cBackoffs[$type] = isset( $cBackoffs[$type] ) ? $cBackoffs[$type] : 0;
255 $cBackoffs[$type] = max( $cBackoffs[$type], $backoffs[$type] );
256 }
257 ftruncate( $handle, 0 );
258 fwrite( $handle, json_encode( $backoffs ) );
259 flock( $handle, LOCK_UN );
260 fclose( $handle );
261 }
262
263 /**
264 * Make sure that this script is not too close to the memory usage limit.
265 * It is better to die in between jobs than OOM right in the middle of one.
266 * @throws MWException
267 */
268 private function assertMemoryOK() {
269 static $maxBytes = null;
270 if ( $maxBytes === null ) {
271 $m = array();
272 if ( preg_match( '!^(\d+)(k|m|g|)$!i', ini_get( 'memory_limit' ), $m ) ) {
273 list( , $num, $unit ) = $m;
274 $conv = array( 'g' => 1073741824, 'm' => 1048576, 'k' => 1024, '' => 1 );
275 $maxBytes = $num * $conv[strtolower( $unit )];
276 } else {
277 $maxBytes = 0;
278 }
279 }
280 $usedBytes = memory_get_usage();
281 if ( $maxBytes && $usedBytes >= 0.95 * $maxBytes ) {
282 throw new MWException( "Detected excessive memory usage ($usedBytes/$maxBytes)." );
283 }
284 }
285
286 /**
287 * Log the job message
288 * @param string $msg The message to log
289 */
290 private function runJobsLog( $msg ) {
291 if ( $this->debug ) {
292 call_user_func_array( $this->debug, array( wfTimestamp( TS_DB ) . " $msg\n" ) );
293 }
294 wfDebugLog( 'runJobs', $msg );
295 }
296 }