Last few svn property fixes
[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 $namespace = $row->job_namespace;
78 $dbkey = $row->job_title;
79 $title = Title::makeTitleSafe( $namespace, $dbkey );
80 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ),
81 $row->job_id );
82
83 $dbw->delete( 'job', $job->insertFields(), __METHOD__ );
84 $dbw->commit();
85
86 wfProfileOut( __METHOD__ );
87 return $job;
88 }
89
90 /**
91 * Pop a job off the front of the queue
92 *
93 * @param $offset Integer: Number of jobs to skip
94 * @return Job or false if there's no jobs
95 */
96 static function pop( $offset = 0 ) {
97 wfProfileIn( __METHOD__ );
98
99 $dbr = wfGetDB( DB_SLAVE );
100
101 /* Get a job from the slave, start with an offset,
102 scan full set afterwards, avoid hitting purged rows
103
104 NB: If random fetch previously was used, offset
105 will always be ahead of few entries
106 */
107
108 $row = $dbr->selectRow( 'job', '*', "job_id >= ${offset}", __METHOD__,
109 array( 'ORDER BY' => 'job_id', 'LIMIT' => 1 ) );
110
111 // Refetching without offset is needed as some of job IDs could have had delayed commits
112 // and have lower IDs than jobs already executed, blame concurrency :)
113 //
114 if ( $row === false ) {
115 if ( $offset != 0 ) {
116 $row = $dbr->selectRow( 'job', '*', '', __METHOD__,
117 array( 'ORDER BY' => 'job_id', 'LIMIT' => 1 ) );
118 }
119
120 if ( $row === false ) {
121 wfProfileOut( __METHOD__ );
122 return false;
123 }
124 }
125
126 // Try to delete it from the master
127 $dbw = wfGetDB( DB_MASTER );
128 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
129 $affected = $dbw->affectedRows();
130 $dbw->commit();
131
132 if ( !$affected ) {
133 // Failed, someone else beat us to it
134 // Try getting a random row
135 $row = $dbw->selectRow( 'job', array( 'MIN(job_id) as minjob',
136 'MAX(job_id) as maxjob' ), '1=1', __METHOD__ );
137 if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
138 // No jobs to get
139 wfProfileOut( __METHOD__ );
140 return false;
141 }
142 // Get the random row
143 $row = $dbw->selectRow( 'job', '*',
144 'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
145 if ( $row === false ) {
146 // Random job gone before we got the chance to select it
147 // Give up
148 wfProfileOut( __METHOD__ );
149 return false;
150 }
151 // Delete the random row
152 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
153 $affected = $dbw->affectedRows();
154 $dbw->commit();
155
156 if ( !$affected ) {
157 // Random job gone before we exclusively deleted it
158 // Give up
159 wfProfileOut( __METHOD__ );
160 return false;
161 }
162 }
163
164 // If execution got to here, there's a row in $row that has been deleted from the database
165 // by this thread. Hence the concurrent pop was successful.
166 $namespace = $row->job_namespace;
167 $dbkey = $row->job_title;
168 $title = Title::makeTitleSafe( $namespace, $dbkey );
169 $job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );
170
171 // Remove any duplicates it may have later in the queue
172 // Deadlock prone section
173 $dbw->begin();
174 $dbw->delete( 'job', $job->insertFields(), __METHOD__ );
175 $dbw->commit();
176
177 wfProfileOut( __METHOD__ );
178 return $job;
179 }
180
181 /**
182 * Create the appropriate object to handle a specific job
183 *
184 * @param $command String: Job command
185 * @param $title Title: Associated title
186 * @param $params Array: Job parameters
187 * @param $id Int: Job identifier
188 * @return Job
189 */
190 static function factory( $command, $title, $params = false, $id = 0 ) {
191 global $wgJobClasses;
192 if( isset( $wgJobClasses[$command] ) ) {
193 $class = $wgJobClasses[$command];
194 return new $class( $title, $params, $id );
195 }
196 throw new MWException( "Invalid job command `{$command}`" );
197 }
198
199 static function makeBlob( $params ) {
200 if ( $params !== false ) {
201 return serialize( $params );
202 } else {
203 return '';
204 }
205 }
206
207 static function extractBlob( $blob ) {
208 if ( (string)$blob !== '' ) {
209 return unserialize( $blob );
210 } else {
211 return false;
212 }
213 }
214
215 /**
216 * Batch-insert a group of jobs into the queue.
217 * This will be wrapped in a transaction with a forced commit.
218 *
219 * This may add duplicate at insert time, but they will be
220 * removed later on, when the first one is popped.
221 *
222 * @param $jobs array of Job objects
223 */
224 static function batchInsert( $jobs ) {
225 if( !count( $jobs ) ) {
226 return;
227 }
228 $dbw = wfGetDB( DB_MASTER );
229 $rows = array();
230 foreach( $jobs as $job ) {
231 $rows[] = $job->insertFields();
232 if ( count( $rows ) >= 50 ) {
233 # Do a small transaction to avoid slave lag
234 $dbw->begin();
235 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
236 $dbw->commit();
237 $rows = array();
238 }
239 }
240 if ( $rows ) {
241 $dbw->begin();
242 $dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
243 $dbw->commit();
244 }
245 }
246
247 /*-------------------------------------------------------------------------
248 * Non-static functions
249 *------------------------------------------------------------------------*/
250
251 /**
252 * @param $command
253 * @param $title
254 * @param $params array
255 * @param int $id
256 */
257 function __construct( $command, $title, $params = false, $id = 0 ) {
258 $this->command = $command;
259 $this->title = $title;
260 $this->params = $params;
261 $this->id = $id;
262
263 // A bit of premature generalisation
264 // Oh well, the whole class is premature generalisation really
265 $this->removeDuplicates = true;
266 }
267
268 /**
269 * Insert a single job into the queue.
270 * @return bool true on success
271 */
272 function insert() {
273 $fields = $this->insertFields();
274
275 $dbw = wfGetDB( DB_MASTER );
276
277 if ( $this->removeDuplicates ) {
278 $res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
279 if ( $dbw->numRows( $res ) ) {
280 return;
281 }
282 }
283 return $dbw->insert( 'job', $fields, __METHOD__ );
284 }
285
286 protected function insertFields() {
287 $dbw = wfGetDB( DB_MASTER );
288 return array(
289 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
290 'job_cmd' => $this->command,
291 'job_namespace' => $this->title->getNamespace(),
292 'job_title' => $this->title->getDBkey(),
293 'job_params' => Job::makeBlob( $this->params )
294 );
295 }
296
297 function toString() {
298 $paramString = '';
299 if ( $this->params ) {
300 foreach ( $this->params as $key => $value ) {
301 if ( $paramString != '' ) {
302 $paramString .= ' ';
303 }
304 $paramString .= "$key=$value";
305 }
306 }
307
308 if ( is_object( $this->title ) ) {
309 $s = "{$this->command} " . $this->title->getPrefixedDBkey();
310 if ( $paramString !== '' ) {
311 $s .= ' ' . $paramString;
312 }
313 return $s;
314 } else {
315 return "{$this->command} $paramString";
316 }
317 }
318
319 protected function setLastError( $error ) {
320 $this->error = $error;
321 }
322
323 function getLastError() {
324 return $this->error;
325 }
326 }