CologneBlue rewrite: remove hard dependency on SkinLegacy, kill Quickbar nonsense
[lhc/web/wiklou.git] / includes / job / Job.php
1 <?php
2 /**
3 * Job queue base code.
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 * @defgroup JobQueue JobQueue
22 */
23
24 /**
25 * Class to both describe a background job and handle jobs.
26 *
27 * @ingroup JobQueue
28 */
29 abstract class Job {
30
31 /**
32 * @var Title
33 */
34 var $title;
35
36 var $command,
37 $params,
38 $id,
39 $removeDuplicates,
40 $error;
41
42 /*-------------------------------------------------------------------------
43 * Abstract functions
44 *------------------------------------------------------------------------*/
45
46 /**
47 * Run the job
48 * @return boolean success
49 */
50 abstract function run();
51
52 /*-------------------------------------------------------------------------
53 * Static functions
54 *------------------------------------------------------------------------*/
55
56 /**
57 * Pop a job of a certain type. This tries less hard than pop() to
58 * actually find a job; it may be adversely affected by concurrent job
59 * runners.
60 *
61 * @param $type string
62 *
63 * @return Job
64 */
65 static function pop_type( $type ) {
66 wfProfilein( __METHOD__ );
67
68 $dbw = wfGetDB( DB_MASTER );
69
70 $dbw->begin( __METHOD__ );
71
72 $row = $dbw->selectRow(
73 'job',
74 '*',
75 array( 'job_cmd' => $type ),
76 __METHOD__,
77 array( 'LIMIT' => 1, 'FOR UPDATE' )
78 );
79
80 if ( $row === false ) {
81 $dbw->commit( __METHOD__ );
82 wfProfileOut( __METHOD__ );
83 return false;
84 }
85
86 /* Ensure we "own" this row */
87 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
88 $affected = $dbw->affectedRows();
89 $dbw->commit( __METHOD__ );
90
91 if ( $affected == 0 ) {
92 wfProfileOut( __METHOD__ );
93 return false;
94 }
95
96 wfIncrStats( 'job-pop' );
97 $namespace = $row->job_namespace;
98 $dbkey = $row->job_title;
99 $title = Title::makeTitleSafe( $namespace, $dbkey );
100 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ),
101 $row->job_id );
102
103 $job->removeDuplicates();
104
105 wfProfileOut( __METHOD__ );
106 return $job;
107 }
108
109 /**
110 * Pop a job off the front of the queue
111 *
112 * @param $offset Integer: Number of jobs to skip
113 * @return Job or false if there's no jobs
114 */
115 static function pop( $offset = 0 ) {
116 wfProfileIn( __METHOD__ );
117
118 $dbr = wfGetDB( DB_SLAVE );
119
120 /* Get a job from the slave, start with an offset,
121 scan full set afterwards, avoid hitting purged rows
122
123 NB: If random fetch previously was used, offset
124 will always be ahead of few entries
125 */
126
127 $conditions = self::defaultQueueConditions();
128
129 $offset = intval( $offset );
130 $options = array( 'ORDER BY' => 'job_id', 'USE INDEX' => 'PRIMARY' );
131
132 $row = $dbr->selectRow( 'job', '*',
133 array_merge( $conditions, array( "job_id >= $offset" ) ),
134 __METHOD__,
135 $options
136 );
137
138 // Refetching without offset is needed as some of job IDs could have had delayed commits
139 // and have lower IDs than jobs already executed, blame concurrency :)
140 //
141 if ( $row === false ) {
142 if ( $offset != 0 ) {
143 $row = $dbr->selectRow( 'job', '*', $conditions, __METHOD__, $options );
144 }
145
146 if ( $row === false ) {
147 wfProfileOut( __METHOD__ );
148 return false;
149 }
150 }
151
152 // Try to delete it from the master
153 $dbw = wfGetDB( DB_MASTER );
154 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
155 $affected = $dbw->affectedRows();
156
157 if ( !$affected ) {
158 // Failed, someone else beat us to it
159 // Try getting a random row
160 $row = $dbw->selectRow( 'job', array( 'minjob' => 'MIN(job_id)',
161 'maxjob' => 'MAX(job_id)' ), '1=1', __METHOD__ );
162 if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
163 // No jobs to get
164 wfProfileOut( __METHOD__ );
165 return false;
166 }
167 // Get the random row
168 $row = $dbw->selectRow( 'job', '*',
169 'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
170 if ( $row === false ) {
171 // Random job gone before we got the chance to select it
172 // Give up
173 wfProfileOut( __METHOD__ );
174 return false;
175 }
176 // Delete the random row
177 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
178 $affected = $dbw->affectedRows();
179
180 if ( !$affected ) {
181 // Random job gone before we exclusively deleted it
182 // Give up
183 wfProfileOut( __METHOD__ );
184 return false;
185 }
186 }
187
188 // If execution got to here, there's a row in $row that has been deleted from the database
189 // by this thread. Hence the concurrent pop was successful.
190 wfIncrStats( 'job-pop' );
191 $namespace = $row->job_namespace;
192 $dbkey = $row->job_title;
193 $title = Title::makeTitleSafe( $namespace, $dbkey );
194
195 if ( is_null( $title ) ) {
196 wfProfileOut( __METHOD__ );
197 return false;
198 }
199
200 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );
201
202 // Remove any duplicates it may have later in the queue
203 $job->removeDuplicates();
204
205 wfProfileOut( __METHOD__ );
206 return $job;
207 }
208
209 /**
210 * Create the appropriate object to handle a specific job
211 *
212 * @param $command String: Job command
213 * @param $title Title: Associated title
214 * @param $params Array|bool: Job parameters
215 * @param $id Int: Job identifier
216 * @throws MWException
217 * @return Job
218 */
219 static function factory( $command, Title $title, $params = false, $id = 0 ) {
220 global $wgJobClasses;
221 if( isset( $wgJobClasses[$command] ) ) {
222 $class = $wgJobClasses[$command];
223 return new $class( $title, $params, $id );
224 }
225 throw new MWException( "Invalid job command `{$command}`" );
226 }
227
228 /**
229 * @param $params
230 * @return string
231 */
232 static function makeBlob( $params ) {
233 if ( $params !== false ) {
234 return serialize( $params );
235 } else {
236 return '';
237 }
238 }
239
240 /**
241 * @param $blob
242 * @return bool|mixed
243 */
244 static function extractBlob( $blob ) {
245 if ( (string)$blob !== '' ) {
246 return unserialize( $blob );
247 } else {
248 return false;
249 }
250 }
251
252 /**
253 * Batch-insert a group of jobs into the queue.
254 * This will be wrapped in a transaction with a forced commit.
255 *
256 * This may add duplicate at insert time, but they will be
257 * removed later on, when the first one is popped.
258 *
259 * @param $jobs array of Job objects
260 */
261 static function batchInsert( $jobs ) {
262 if ( !count( $jobs ) ) {
263 return;
264 }
265 $dbw = wfGetDB( DB_MASTER );
266 $rows = array();
267
268 /**
269 * @var $job Job
270 */
271 foreach ( $jobs as $job ) {
272 $rows[] = $job->insertFields();
273 if ( count( $rows ) >= 50 ) {
274 # Do a small transaction to avoid slave lag
275 $dbw->begin( __METHOD__ );
276 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
277 $dbw->commit( __METHOD__ );
278 $rows = array();
279 }
280 }
281 if ( $rows ) { // last chunk
282 $dbw->begin( __METHOD__ );
283 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
284 $dbw->commit( __METHOD__ );
285 }
286 wfIncrStats( 'job-insert', count( $jobs ) );
287 }
288
289 /**
290 * Insert a group of jobs into the queue.
291 *
292 * Same as batchInsert() but does not commit and can thus
293 * be rolled-back as part of a larger transaction. However,
294 * large batches of jobs can cause slave lag.
295 *
296 * @param $jobs array of Job objects
297 */
298 static function safeBatchInsert( $jobs ) {
299 if ( !count( $jobs ) ) {
300 return;
301 }
302 $dbw = wfGetDB( DB_MASTER );
303 $rows = array();
304 foreach ( $jobs as $job ) {
305 $rows[] = $job->insertFields();
306 if ( count( $rows ) >= 500 ) {
307 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
308 $rows = array();
309 }
310 }
311 if ( $rows ) { // last chunk
312 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
313 }
314 wfIncrStats( 'job-insert', count( $jobs ) );
315 }
316
317
318 /**
319 * SQL conditions to apply on most JobQueue queries
320 *
321 * Whenever we exclude jobs types from the default queue, we want to make
322 * sure that queries to the job queue actually ignore them.
323 *
324 * @return array SQL conditions suitable for Database:: methods
325 */
326 static function defaultQueueConditions( ) {
327 global $wgJobTypesExcludedFromDefaultQueue;
328 $conditions = array();
329 if ( count( $wgJobTypesExcludedFromDefaultQueue ) > 0 ) {
330 $dbr = wfGetDB( DB_SLAVE );
331 foreach ( $wgJobTypesExcludedFromDefaultQueue as $cmdType ) {
332 $conditions[] = "job_cmd != " . $dbr->addQuotes( $cmdType );
333 }
334 }
335 return $conditions;
336 }
337
338 /*-------------------------------------------------------------------------
339 * Non-static functions
340 *------------------------------------------------------------------------*/
341
342 /**
343 * @param $command
344 * @param $title
345 * @param $params array|bool
346 * @param $id int
347 */
348 function __construct( $command, $title, $params = false, $id = 0 ) {
349 $this->command = $command;
350 $this->title = $title;
351 $this->params = $params;
352 $this->id = $id;
353
354 // A bit of premature generalisation
355 // Oh well, the whole class is premature generalisation really
356 $this->removeDuplicates = true;
357 }
358
359 /**
360 * Insert a single job into the queue.
361 * @return bool true on success
362 */
363 function insert() {
364 $fields = $this->insertFields();
365
366 $dbw = wfGetDB( DB_MASTER );
367
368 if ( $this->removeDuplicates ) {
369 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
370 if ( $dbw->numRows( $res ) ) {
371 return true;
372 }
373 }
374 wfIncrStats( 'job-insert' );
375 return $dbw->insert( 'job', $fields, __METHOD__ );
376 }
377
378 /**
379 * @return array
380 */
381 protected function insertFields() {
382 $dbw = wfGetDB( DB_MASTER );
383 return array(
384 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
385 'job_cmd' => $this->command,
386 'job_namespace' => $this->title->getNamespace(),
387 'job_title' => $this->title->getDBkey(),
388 'job_timestamp' => $dbw->timestamp(),
389 'job_params' => Job::makeBlob( $this->params )
390 );
391 }
392
393 /**
394 * Remove jobs in the job queue which are duplicates of this job.
395 * This is deadlock-prone and so starts its own transaction.
396 */
397 function removeDuplicates() {
398 if ( !$this->removeDuplicates ) {
399 return;
400 }
401
402 $fields = $this->insertFields();
403 unset( $fields['job_id'] );
404 $dbw = wfGetDB( DB_MASTER );
405 $dbw->begin( __METHOD__ );
406 $dbw->delete( 'job', $fields, __METHOD__ );
407 $affected = $dbw->affectedRows();
408 $dbw->commit( __METHOD__ );
409 if ( $affected ) {
410 wfIncrStats( 'job-dup-delete', $affected );
411 }
412 }
413
414 /**
415 * @return string
416 */
417 function toString() {
418 $paramString = '';
419 if ( $this->params ) {
420 foreach ( $this->params as $key => $value ) {
421 if ( $paramString != '' ) {
422 $paramString .= ' ';
423 }
424 $paramString .= "$key=$value";
425 }
426 }
427
428 if ( is_object( $this->title ) ) {
429 $s = "{$this->command} " . $this->title->getPrefixedDBkey();
430 if ( $paramString !== '' ) {
431 $s .= ' ' . $paramString;
432 }
433 return $s;
434 } else {
435 return "{$this->command} $paramString";
436 }
437 }
438
439 protected function setLastError( $error ) {
440 $this->error = $error;
441 }
442
443 function getLastError() {
444 return $this->error;
445 }
446 }