* Add a $count argument to wfIncrStats(), to allow it to increase the count by more...
[lhc/web/wiklou.git] / includes / job / JobQueue.php
1 <?php
2 /**
3 * Job queue base code
4 *
5 * @file
6 * @defgroup JobQueue JobQueue
7 */
8
9 if ( !defined( 'MEDIAWIKI' ) ) {
10 die( "This file is part of MediaWiki, it is not a valid entry point\n" );
11 }
12
13 /**
14 * Class to both describe a background job and handle jobs.
15 *
16 * @ingroup JobQueue
17 */
18 abstract class Job {
19
20 /**
21 * @var Title
22 */
23 var $title;
24
25 var $command,
26 $params,
27 $id,
28 $removeDuplicates,
29 $error;
30
31 /*-------------------------------------------------------------------------
32 * Abstract functions
33 *------------------------------------------------------------------------*/
34
35 /**
36 * Run the job
37 * @return boolean success
38 */
39 abstract function run();
40
41 /*-------------------------------------------------------------------------
42 * Static functions
43 *------------------------------------------------------------------------*/
44
45 /**
46 * Pop a job of a certain type. This tries less hard than pop() to
47 * actually find a job; it may be adversely affected by concurrent job
48 * runners.
49 */
50 static function pop_type( $type ) {
51 wfProfilein( __METHOD__ );
52
53 $dbw = wfGetDB( DB_MASTER );
54
55 $row = $dbw->selectRow(
56 'job',
57 '*',
58 array( 'job_cmd' => $type ),
59 __METHOD__,
60 array( 'LIMIT' => 1 )
61 );
62
63 if ( $row === false ) {
64 wfProfileOut( __METHOD__ );
65 return false;
66 }
67
68 /* Ensure we "own" this row */
69 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
70 $affected = $dbw->affectedRows();
71
72 if ( $affected == 0 ) {
73 wfProfileOut( __METHOD__ );
74 return false;
75 }
76
77 wfIncrStats( 'job-pop' );
78 $namespace = $row->job_namespace;
79 $dbkey = $row->job_title;
80 $title = Title::makeTitleSafe( $namespace, $dbkey );
81 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ),
82 $row->job_id );
83
84 $dbw->delete( 'job', $job->insertFields(), __METHOD__ );
85 $dbw->commit();
86
87 wfProfileOut( __METHOD__ );
88 return $job;
89 }
90
91 /**
92 * Pop a job off the front of the queue
93 *
94 * @param $offset Integer: Number of jobs to skip
95 * @return Job or false if there's no jobs
96 */
97 static function pop( $offset = 0 ) {
98 wfProfileIn( __METHOD__ );
99
100 $dbr = wfGetDB( DB_SLAVE );
101
102 /* Get a job from the slave, start with an offset,
103 scan full set afterwards, avoid hitting purged rows
104
105 NB: If random fetch previously was used, offset
106 will always be ahead of few entries
107 */
108
109 $row = $dbr->selectRow( 'job', '*', "job_id >= ${offset}", __METHOD__,
110 array( 'ORDER BY' => 'job_id', 'LIMIT' => 1 ) );
111
112 // Refetching without offset is needed as some of job IDs could have had delayed commits
113 // and have lower IDs than jobs already executed, blame concurrency :)
114 //
115 if ( $row === false ) {
116 if ( $offset != 0 ) {
117 $row = $dbr->selectRow( 'job', '*', '', __METHOD__,
118 array( 'ORDER BY' => 'job_id', 'LIMIT' => 1 ) );
119 }
120
121 if ( $row === false ) {
122 wfProfileOut( __METHOD__ );
123 return false;
124 }
125 }
126
127 // Try to delete it from the master
128 $dbw = wfGetDB( DB_MASTER );
129 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
130 $affected = $dbw->affectedRows();
131 $dbw->commit();
132
133 if ( !$affected ) {
134 // Failed, someone else beat us to it
135 // Try getting a random row
136 $row = $dbw->selectRow( 'job', array( 'MIN(job_id) as minjob',
137 'MAX(job_id) as maxjob' ), '1=1', __METHOD__ );
138 if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
139 // No jobs to get
140 wfProfileOut( __METHOD__ );
141 return false;
142 }
143 // Get the random row
144 $row = $dbw->selectRow( 'job', '*',
145 'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
146 if ( $row === false ) {
147 // Random job gone before we got the chance to select it
148 // Give up
149 wfProfileOut( __METHOD__ );
150 return false;
151 }
152 // Delete the random row
153 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
154 $affected = $dbw->affectedRows();
155 $dbw->commit();
156
157 if ( !$affected ) {
158 // Random job gone before we exclusively deleted it
159 // Give up
160 wfProfileOut( __METHOD__ );
161 return false;
162 }
163 }
164
165 // If execution got to here, there's a row in $row that has been deleted from the database
166 // by this thread. Hence the concurrent pop was successful.
167 wfIncrStats( 'job-pop' );
168 $namespace = $row->job_namespace;
169 $dbkey = $row->job_title;
170 $title = Title::makeTitleSafe( $namespace, $dbkey );
171 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );
172
173 // Remove any duplicates it may have later in the queue
174 // Deadlock prone section
175 $dbw->begin();
176 $dbw->delete( 'job', $job->insertFields(), __METHOD__ );
177 $dbw->commit();
178
179 wfProfileOut( __METHOD__ );
180 return $job;
181 }
182
183 /**
184 * Create the appropriate object to handle a specific job
185 *
186 * @param $command String: Job command
187 * @param $title Title: Associated title
188 * @param $params Array: Job parameters
189 * @param $id Int: Job identifier
190 * @return Job
191 */
192 static function factory( $command, $title, $params = false, $id = 0 ) {
193 global $wgJobClasses;
194 if( isset( $wgJobClasses[$command] ) ) {
195 $class = $wgJobClasses[$command];
196 return new $class( $title, $params, $id );
197 }
198 throw new MWException( "Invalid job command `{$command}`" );
199 }
200
201 static function makeBlob( $params ) {
202 if ( $params !== false ) {
203 return serialize( $params );
204 } else {
205 return '';
206 }
207 }
208
209 static function extractBlob( $blob ) {
210 if ( (string)$blob !== '' ) {
211 return unserialize( $blob );
212 } else {
213 return false;
214 }
215 }
216
217 /**
218 * Batch-insert a group of jobs into the queue.
219 * This will be wrapped in a transaction with a forced commit.
220 *
221 * This may add duplicate at insert time, but they will be
222 * removed later on, when the first one is popped.
223 *
224 * @param $jobs array of Job objects
225 */
226 static function batchInsert( $jobs ) {
227 if( !count( $jobs ) ) {
228 return;
229 }
230 $dbw = wfGetDB( DB_MASTER );
231 $rows = array();
232 foreach( $jobs as $job ) {
233 $rows[] = $job->insertFields();
234 if ( count( $rows ) >= 50 ) {
235 # Do a small transaction to avoid slave lag
236 $dbw->begin();
237 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
238 $dbw->commit();
239 $rows = array();
240 }
241 }
242 if ( $rows ) {
243 wfIncrStats( 'job-insert', count( $rows ) );
244 $dbw->begin();
245 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
246 $dbw->commit();
247 }
248 }
249
250 /*-------------------------------------------------------------------------
251 * Non-static functions
252 *------------------------------------------------------------------------*/
253
254 /**
255 * @param $command
256 * @param $title
257 * @param $params array
258 * @param int $id
259 */
260 function __construct( $command, $title, $params = false, $id = 0 ) {
261 $this->command = $command;
262 $this->title = $title;
263 $this->params = $params;
264 $this->id = $id;
265
266 // A bit of premature generalisation
267 // Oh well, the whole class is premature generalisation really
268 $this->removeDuplicates = true;
269 }
270
271 /**
272 * Insert a single job into the queue.
273 * @return bool true on success
274 */
275 function insert() {
276 $fields = $this->insertFields();
277
278 $dbw = wfGetDB( DB_MASTER );
279
280 if ( $this->removeDuplicates ) {
281 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
282 if ( $dbw->numRows( $res ) ) {
283 return;
284 }
285 }
286 wfIncrStats( 'job-insert' );
287 return $dbw->insert( 'job', $fields, __METHOD__ );
288 }
289
290 protected function insertFields() {
291 $dbw = wfGetDB( DB_MASTER );
292 return array(
293 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
294 'job_cmd' => $this->command,
295 'job_namespace' => $this->title->getNamespace(),
296 'job_title' => $this->title->getDBkey(),
297 'job_params' => Job::makeBlob( $this->params )
298 );
299 }
300
301 function toString() {
302 $paramString = '';
303 if ( $this->params ) {
304 foreach ( $this->params as $key => $value ) {
305 if ( $paramString != '' ) {
306 $paramString .= ' ';
307 }
308 $paramString .= "$key=$value";
309 }
310 }
311
312 if ( is_object( $this->title ) ) {
313 $s = "{$this->command} " . $this->title->getPrefixedDBkey();
314 if ( $paramString !== '' ) {
315 $s .= ' ' . $paramString;
316 }
317 return $s;
318 } else {
319 return "{$this->command} $paramString";
320 }
321 }
322
323 protected function setLastError( $error ) {
324 $this->error = $error;
325 }
326
327 function getLastError() {
328 return $this->error;
329 }
330 }