summaryrefslogtreecommitdiff
path: root/includes/job/JobQueue.php
blob: 0d917ba3e65af1e06ba3553616d1f25efbcdb5e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
<?php
/**
 * Job queue base code
 *
 * @file
 * @defgroup JobQueue JobQueue
 */

if ( !defined( 'MEDIAWIKI' ) ) {
	die( "This file is part of MediaWiki, it is not a valid entry point\n" );
}

/**
 * Class to both describe a background job and handle jobs.
 *
 * @ingroup JobQueue
 */
abstract class Job {

	/**
	 * @var Title
	 */
	var $title;

	var $command,
		$params,
		$id,
		$removeDuplicates,
		$error;

	/*-------------------------------------------------------------------------
	 * Abstract functions
	 *------------------------------------------------------------------------*/

	/**
	 * Run the job
	 * @return boolean success
	 */
	abstract function run();

	/*-------------------------------------------------------------------------
	 * Static functions
	 *------------------------------------------------------------------------*/

	/**
	 * Pop a job of a certain type.  This tries less hard than pop() to
	 * actually find a job; it may be adversely affected by concurrent job
	 * runners.
	 *
	 * @param $type string
	 *
	 * @return Job
	 */
	static function pop_type( $type ) {
		wfProfilein( __METHOD__ );

		$dbw = wfGetDB( DB_MASTER );

		$dbw->begin();

		$row = $dbw->selectRow(
			'job',
			'*',
			array( 'job_cmd' => $type ),
			__METHOD__,
			array( 'LIMIT' => 1, 'FOR UPDATE' )
		);

		if ( $row === false ) {
			$dbw->commit();
			wfProfileOut( __METHOD__ );
			return false;
		}

		/* Ensure we "own" this row */
		$dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
		$affected = $dbw->affectedRows();
		$dbw->commit();

		if ( $affected == 0 ) {
			wfProfileOut( __METHOD__ );
			return false;
		}

		wfIncrStats( 'job-pop' );
		$namespace = $row->job_namespace;
		$dbkey = $row->job_title;
		$title = Title::makeTitleSafe( $namespace, $dbkey );
		$job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ),
			$row->job_id );

		$job->removeDuplicates();

		wfProfileOut( __METHOD__ );
		return $job;
	}

	/**
	 * Pop a job off the front of the queue
	 *
	 * @param $offset Integer: Number of jobs to skip
	 * @return Job or false if there's no jobs
	 */
	static function pop( $offset = 0 ) {
		global $wgJobTypesExcludedFromDefaultQueue;
		wfProfileIn( __METHOD__ );

		$dbr = wfGetDB( DB_SLAVE );

		/* Get a job from the slave, start with an offset,
			scan full set afterwards, avoid hitting purged rows

			NB: If random fetch previously was used, offset
				will always be ahead of few entries
		*/
		$conditions = array();
		if ( count( $wgJobTypesExcludedFromDefaultQueue ) != 0 ) {
			foreach ( $wgJobTypesExcludedFromDefaultQueue as $cmdType ) {
				$conditions[] = "job_cmd != " . $dbr->addQuotes( $cmdType );
			}
		}
		$offset = intval( $offset );
		$options = array( 'ORDER BY' => 'job_id', 'USE INDEX' => 'PRIMARY' );

		$row = $dbr->selectRow( 'job', '*',
			array_merge( $conditions, array( "job_id >= $offset" ) ),
			__METHOD__,
			$options
		);

		// Refetching without offset is needed as some of job IDs could have had delayed commits
		// and have lower IDs than jobs already executed, blame concurrency :)
		//
		if ( $row === false ) {
			if ( $offset != 0 ) {
				$row = $dbr->selectRow( 'job', '*', $conditions, __METHOD__, $options );
			}

			if ( $row === false ) {
				wfProfileOut( __METHOD__ );
				return false;
			}
		}

		// Try to delete it from the master
		$dbw = wfGetDB( DB_MASTER );
		$dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
		$affected = $dbw->affectedRows();
		$dbw->commit();

		if ( !$affected ) {
			// Failed, someone else beat us to it
			// Try getting a random row
			$row = $dbw->selectRow( 'job', array( 'MIN(job_id) as minjob',
				'MAX(job_id) as maxjob' ), '1=1', __METHOD__ );
			if ( $row === false || is_null( $row->minjob ) || is_null( $row->maxjob ) ) {
				// No jobs to get
				wfProfileOut( __METHOD__ );
				return false;
			}
			// Get the random row
			$row = $dbw->selectRow( 'job', '*',
				'job_id >= ' . mt_rand( $row->minjob, $row->maxjob ), __METHOD__ );
			if ( $row === false ) {
				// Random job gone before we got the chance to select it
				// Give up
				wfProfileOut( __METHOD__ );
				return false;
			}
			// Delete the random row
			$dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
			$affected = $dbw->affectedRows();
			$dbw->commit();

			if ( !$affected ) {
				// Random job gone before we exclusively deleted it
				// Give up
				wfProfileOut( __METHOD__ );
				return false;
			}
		}

		// If execution got to here, there's a row in $row that has been deleted from the database
		// by this thread. Hence the concurrent pop was successful.
		wfIncrStats( 'job-pop' );
		$namespace = $row->job_namespace;
		$dbkey = $row->job_title;
		$title = Title::makeTitleSafe( $namespace, $dbkey );
		$job = Job::factory( $row->job_cmd, $title, Job::extractBlob( $row->job_params ), $row->job_id );

		// Remove any duplicates it may have later in the queue
		$job->removeDuplicates();

		wfProfileOut( __METHOD__ );
		return $job;
	}

	/**
	 * Create the appropriate object to handle a specific job
	 *
	 * @param $command String: Job command
	 * @param $title Title: Associated title
	 * @param $params Array: Job parameters
	 * @param $id Int: Job identifier
	 * @return Job
	 */
	static function factory( $command, $title, $params = false, $id = 0 ) {
		global $wgJobClasses;
		if( isset( $wgJobClasses[$command] ) ) {
			$class = $wgJobClasses[$command];
			return new $class( $title, $params, $id );
		}
		throw new MWException( "Invalid job command `{$command}`" );
	}

	static function makeBlob( $params ) {
		if ( $params !== false ) {
			return serialize( $params );
		} else {
			return '';
		}
	}

	static function extractBlob( $blob ) {
		if ( (string)$blob !== '' ) {
			return unserialize( $blob );
		} else {
			return false;
		}
	}

	/**
	 * Batch-insert a group of jobs into the queue.
	 * This will be wrapped in a transaction with a forced commit.
	 *
	 * This may add duplicate at insert time, but they will be
	 * removed later on, when the first one is popped.
	 *
	 * @param $jobs array of Job objects
	 */
	static function batchInsert( $jobs ) {
		if ( !count( $jobs ) ) {
			return;
		}
		$dbw = wfGetDB( DB_MASTER );
		$rows = array();
		foreach ( $jobs as $job ) {
			$rows[] = $job->insertFields();
			if ( count( $rows ) >= 50 ) {
				# Do a small transaction to avoid slave lag
				$dbw->begin();
				$dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
				$dbw->commit();
				$rows = array();
			}
		}
		if ( $rows ) { // last chunk
			$dbw->begin();
			$dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
			$dbw->commit();
		}
		wfIncrStats( 'job-insert', count( $jobs ) );
	}

	/**
	 * Insert a group of jobs into the queue.
	 *
	 * Same as batchInsert() but does not commit and can thus
	 * be rolled-back as part of a larger transaction. However,
	 * large batches of jobs can cause slave lag.
	 *
	 * @param $jobs array of Job objects
	 */
	static function safeBatchInsert( $jobs ) {
		if ( !count( $jobs ) ) {
			return;
		}
		$dbw = wfGetDB( DB_MASTER );
		$rows = array();
		foreach ( $jobs as $job ) {
			$rows[] = $job->insertFields();
			if ( count( $rows ) >= 500 ) {
				$dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
				$rows = array();
			}
		}
		if ( $rows ) { // last chunk
			$dbw->insert( 'job', $rows, __METHOD__, 'IGNORE' );
		}
		wfIncrStats( 'job-insert', count( $jobs ) );
	}

	/*-------------------------------------------------------------------------
	 * Non-static functions
	 *------------------------------------------------------------------------*/

	/**
	 * @param $command
	 * @param $title
	 * @param $params array
	 * @param int $id
	 */
	function __construct( $command, $title, $params = false, $id = 0 ) {
		$this->command = $command;
		$this->title = $title;
		$this->params = $params;
		$this->id = $id;

		// A bit of premature generalisation
		// Oh well, the whole class is premature generalisation really
		$this->removeDuplicates = true;
	}

	/**
	 * Insert a single job into the queue.
	 * @return bool true on success
	 */
	function insert() {
		$fields = $this->insertFields();

		$dbw = wfGetDB( DB_MASTER );

		if ( $this->removeDuplicates ) {
			$res = $dbw->select( 'job', array( '1' ), $fields, __METHOD__ );
			if ( $dbw->numRows( $res ) ) {
				return;
			}
		}
		wfIncrStats( 'job-insert' );
		return $dbw->insert( 'job', $fields, __METHOD__ );
	}

	protected function insertFields() {
		$dbw = wfGetDB( DB_MASTER );
		return array(
			'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
			'job_cmd' => $this->command,
			'job_namespace' => $this->title->getNamespace(),
			'job_title' => $this->title->getDBkey(),
			'job_params' => Job::makeBlob( $this->params )
		);
	}

	/**
	 * Remove jobs in the job queue which are duplicates of this job.
	 * This is deadlock-prone and so starts its own transaction.
	 */
	function removeDuplicates() {
		if ( !$this->removeDuplicates ) {
			return;
		}

		$fields = $this->insertFields();
		unset( $fields['job_id'] );
		$dbw = wfGetDB( DB_MASTER );
		$dbw->begin();
		$dbw->delete( 'job', $fields, __METHOD__ );
		$affected = $dbw->affectedRows();
		$dbw->commit();
		if ( $affected ) {
			wfIncrStats( 'job-dup-delete', $affected );
		}
	}

	function toString() {
		$paramString = '';
		if ( $this->params ) {
			foreach ( $this->params as $key => $value ) {
				if ( $paramString != '' ) {
					$paramString .= ' ';
				}
				$paramString .= "$key=$value";
			}
		}

		if ( is_object( $this->title ) ) {
			$s = "{$this->command} " . $this->title->getPrefixedDBkey();
			if ( $paramString !== '' ) {
				$s .= ' ' . $paramString;
			}
			return $s;
		} else {
			return "{$this->command} $paramString";
		}
	}

	protected function setLastError( $error ) {
		$this->error = $error;
	}

	function getLastError() {
		return $this->error;
	}
}