Add numerous missing @throws to method documentation
[lhc/web/wiklou.git] / includes / job / JobQueueDB.php
1 <?php
2 /**
3 * Database-backed job queue 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 * @author Aaron Schulz
22 */
23
24 /**
25 * Class to handle job queues stored in the DB
26 *
27 * @ingroup JobQueue
28 * @since 1.21
29 */
30 class JobQueueDB extends JobQueue {
31 const CACHE_TTL = 300; // integer; seconds to cache queue information
32 const MAX_AGE_PRUNE = 604800; // integer; seconds a job can live once claimed
33 const MAX_ATTEMPTS = 3; // integer; number of times to try a job
34 const MAX_JOB_RANDOM = 2147483647; // integer; 2^31 - 1, used for job_random
35
36 /**
37 * @see JobQueue::doIsEmpty()
38 * @return bool
39 */
40 protected function doIsEmpty() {
41 global $wgMemc;
42
43 $key = $this->getEmptinessCacheKey();
44
45 $isEmpty = $wgMemc->get( $key );
46 if ( $isEmpty === 'true' ) {
47 return true;
48 } elseif ( $isEmpty === 'false' ) {
49 return false;
50 }
51
52 $found = $this->getSlaveDB()->selectField(
53 'job', '1', array( 'job_cmd' => $this->type ), __METHOD__
54 );
55
56 $wgMemc->add( $key, $found ? 'false' : 'true', self::CACHE_TTL );
57 }
58
59 /**
60 * @see JobQueue::doBatchPush()
61 * @param array $jobs
62 * @param $flags
63 * @throws DBError|Exception
64 * @return bool
65 */
66 protected function doBatchPush( array $jobs, $flags ) {
67 if ( count( $jobs ) ) {
68 $dbw = $this->getMasterDB();
69
70 $rowSet = array(); // (sha1 => job) map for jobs that are de-duplicated
71 $rowList = array(); // list of jobs for jobs that are are not de-duplicated
72
73 foreach ( $jobs as $job ) {
74 $row = $this->insertFields( $job );
75 if ( $job->ignoreDuplicates() ) {
76 $rowSet[$row['job_sha1']] = $row;
77 } else {
78 $rowList[] = $row;
79 }
80 }
81
82 $atomic = ( $flags & self::QoS_Atomic );
83 $key = $this->getEmptinessCacheKey();
84 $ttl = self::CACHE_TTL;
85
86 $dbw->onTransactionIdle(
87 function() use ( $dbw, $rowSet, $rowList, $atomic, $key, $ttl
88 ) {
89 global $wgMemc;
90
91 if ( $atomic ) {
92 $dbw->begin( __METHOD__ ); // wrap all the job additions in one transaction
93 }
94 try {
95 // Strip out any duplicate jobs that are already in the queue...
96 if ( count( $rowSet ) ) {
97 $res = $dbw->select( 'job', 'job_sha1',
98 array(
99 // No job_type condition since it's part of the job_sha1 hash
100 'job_sha1' => array_keys( $rowSet ),
101 'job_token' => '' // unclaimed
102 ),
103 __METHOD__
104 );
105 foreach ( $res as $row ) {
106 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate." );
107 unset( $rowSet[$row->job_sha1] ); // already enqueued
108 }
109 }
110 // Build the full list of job rows to insert
111 $rows = array_merge( $rowList, array_values( $rowSet ) );
112 // Insert the job rows in chunks to avoid slave lag...
113 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
114 $dbw->insert( 'job', $rowBatch, __METHOD__ );
115 }
116 } catch ( DBError $e ) {
117 if ( $atomic ) {
118 $dbw->rollback( __METHOD__ );
119 }
120 throw $e;
121 }
122 if ( $atomic ) {
123 $dbw->commit( __METHOD__ );
124 }
125
126 $wgMemc->set( $key, 'false', $ttl ); // queue is not empty
127 } );
128 }
129
130 return true;
131 }
132
133 /**
134 * @see JobQueue::doPop()
135 * @return Job|bool
136 */
137 protected function doPop() {
138 global $wgMemc;
139
140 if ( $wgMemc->get( $this->getEmptinessCacheKey() ) === 'true' ) {
141 return false; // queue is empty
142 }
143
144 $dbw = $this->getMasterDB();
145 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
146
147 $uuid = wfRandomString( 32 ); // pop attempt
148 $job = false; // job popped off
149 // Occasionally recycle jobs back into the queue that have been claimed too long
150 if ( mt_rand( 0, 99 ) == 0 ) {
151 $this->recycleStaleJobs();
152 }
153 do { // retry when our row is invalid or deleted as a duplicate
154 // Try to reserve a row in the DB...
155 if ( in_array( $this->order, array( 'fifo', 'timestamp' ) ) ) {
156 $row = $this->claimOldest( $uuid );
157 } else { // random first
158 $rand = mt_rand( 0, self::MAX_JOB_RANDOM ); // encourage concurrent UPDATEs
159 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
160 $row = $this->claimRandom( $uuid, $rand, $gte );
161 if ( !$row ) { // need to try the other direction
162 $row = $this->claimRandom( $uuid, $rand, !$gte );
163 }
164 }
165 // Check if we found a row to reserve...
166 if ( !$row ) {
167 $wgMemc->set( $this->getEmptinessCacheKey(), 'true', self::CACHE_TTL );
168 break; // nothing to do
169 }
170 // Get the job object from the row...
171 $title = Title::makeTitleSafe( $row->job_namespace, $row->job_title );
172 if ( !$title ) {
173 $dbw->delete( 'job', array( 'job_id' => $row->job_id ), __METHOD__ );
174 wfIncrStats( 'job-pop' );
175 wfDebugLog( 'JobQueueDB', "Row has invalid title '{$row->job_title}'." );
176 continue; // try again
177 }
178 $job = Job::factory( $row->job_cmd, $title,
179 self::extractBlob( $row->job_params ), $row->job_id );
180 $job->id = $row->job_id; // XXX: work around broken subclasses
181 // Flag this job as an old duplicate based on its "root" job...
182 if ( $this->isRootJobOldDuplicate( $job ) ) {
183 $job = DuplicateJob::newFromJob( $job ); // convert to a no-op
184 }
185 break; // done
186 } while( true );
187
188 return $job;
189 }
190
191 /**
192 * Reserve a row with a single UPDATE without holding row locks over RTTs...
193 *
194 * @param $uuid string 32 char hex string
195 * @param $rand integer Random unsigned integer (31 bits)
196 * @param $gte bool Search for job_random >= $random (otherwise job_random <= $random)
197 * @return Row|false
198 */
199 protected function claimRandom( $uuid, $rand, $gte ) {
200 $dbw = $this->getMasterDB();
201 $dir = $gte ? 'ASC' : 'DESC';
202 $ineq = $gte ? '>=' : '<=';
203
204 $row = false; // the row acquired
205 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
206 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
207 // not replication safe. Due to http://bugs.mysql.com/bug.php?id=6980, subqueries cannot
208 // be used here with MySQL.
209 do {
210 $row = $dbw->selectRow( 'job', '*', // find a random job
211 array(
212 'job_cmd' => $this->type,
213 'job_token' => '',
214 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ),
215 __METHOD__,
216 array( 'ORDER BY' => "job_random {$dir}" )
217 );
218 if ( $row ) { // claim the job
219 $dbw->update( 'job', // update by PK
220 array(
221 'job_token' => $uuid,
222 'job_token_timestamp' => $dbw->timestamp(),
223 'job_attempts = job_attempts+1' ),
224 array( 'job_cmd' => $this->type, 'job_id' => $row->job_id, 'job_token' => '' ),
225 __METHOD__
226 );
227 // This might get raced out by another runner when claiming the previously
228 // selected row. The use of job_random should minimize this problem, however.
229 if ( !$dbw->affectedRows() ) {
230 $row = false; // raced out
231 }
232 } else {
233 break; // nothing to do
234 }
235 } while ( !$row );
236
237 return $row;
238 }
239
240 /**
241 * Reserve a row with a single UPDATE without holding row locks over RTTs...
242 *
243 * @param $uuid string 32 char hex string
244 * @return Row|false
245 */
246 protected function claimOldest( $uuid ) {
247 $dbw = $this->getMasterDB();
248
249 $row = false; // the row acquired
250 do {
251 if ( $dbw->getType() === 'mysql' ) {
252 // Per http://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
253 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
254 // Oracle and Postgre have no such limitation. However, MySQL offers an
255 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
256 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
257 "SET " .
258 "job_token = {$dbw->addQuotes( $uuid ) }, " .
259 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
260 "job_attempts = job_attempts+1 " .
261 "WHERE ( " .
262 "job_cmd = {$dbw->addQuotes( $this->type )} " .
263 "AND job_token = {$dbw->addQuotes( '' )} " .
264 ") ORDER BY job_id ASC LIMIT 1",
265 __METHOD__
266 );
267 } else {
268 // Use a subquery to find the job, within an UPDATE to claim it.
269 // This uses as much of the DB wrapper functions as possible.
270 $dbw->update( 'job',
271 array(
272 'job_token' => $uuid,
273 'job_token_timestamp' => $dbw->timestamp(),
274 'job_attempts = job_attempts+1' ),
275 array( 'job_id = (' .
276 $dbw->selectSQLText( 'job', 'job_id',
277 array( 'job_cmd' => $this->type, 'job_token' => '' ),
278 __METHOD__,
279 array( 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ) ) .
280 ')'
281 ),
282 __METHOD__
283 );
284 }
285 // Fetch any row that we just reserved...
286 if ( $dbw->affectedRows() ) {
287 $row = $dbw->selectRow( 'job', '*',
288 array( 'job_cmd' => $this->type, 'job_token' => $uuid ), __METHOD__
289 );
290 if ( !$row ) { // raced out by duplicate job removal
291 wfDebugLog( 'JobQueueDB', "Row deleted as duplicate by another process." );
292 }
293 } else {
294 break; // nothing to do
295 }
296 } while ( !$row );
297
298 return $row;
299 }
300
301 /**
302 * Recycle or destroy any jobs that have been claimed for too long
303 *
304 * @return integer Number of jobs recycled/deleted
305 */
306 protected function recycleStaleJobs() {
307 $now = time();
308 $dbw = $this->getMasterDB();
309 $count = 0; // affected rows
310
311 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
312 return $count; // already in progress
313 }
314
315 // Remove claims on jobs acquired for too long if enabled...
316 if ( $this->claimTTL > 0 ) {
317 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
318 // Get the IDs of jobs that have be claimed but not finished after too long.
319 // These jobs can be recycled into the queue by expiring the claim. Selecting
320 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
321 $res = $dbw->select( 'job', 'job_id',
322 array(
323 'job_cmd' => $this->type,
324 "job_token != {$dbw->addQuotes( '' )}", // was acquired
325 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
326 "job_attempts < {$dbw->addQuotes( self::MAX_ATTEMPTS )}" ), // retries left
327 __METHOD__
328 );
329 $ids = array_map( function( $o ) { return $o->job_id; }, iterator_to_array( $res ) );
330 if ( count( $ids ) ) {
331 // Reset job_token for these jobs so that other runners will pick them up.
332 // Set the timestamp to the current time, as it is useful to now that the job
333 // was already tried before (the timestamp becomes the "released" time).
334 $dbw->update( 'job',
335 array(
336 'job_token' => '',
337 'job_token_timestamp' => $dbw->timestamp( $now ) ), // time of release
338 array(
339 'job_id' => $ids ),
340 __METHOD__
341 );
342 $count += $dbw->affectedRows();
343 }
344 }
345
346 // Just destroy any stale jobs...
347 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
348 $conds = array(
349 'job_cmd' => $this->type,
350 "job_token != {$dbw->addQuotes( '' )}", // was acquired
351 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
352 );
353 if ( $this->claimTTL > 0 ) { // only prune jobs attempted too many times...
354 $conds[] = "job_attempts >= {$dbw->addQuotes( self::MAX_ATTEMPTS )}";
355 }
356 // Get the IDs of jobs that are considered stale and should be removed. Selecting
357 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
358 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__ );
359 $ids = array_map( function( $o ) { return $o->job_id; }, iterator_to_array( $res ) );
360 if ( count( $ids ) ) {
361 $dbw->delete( 'job', array( 'job_id' => $ids ), __METHOD__ );
362 $count += $dbw->affectedRows();
363 }
364
365 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__ );
366
367 return $count;
368 }
369
370 /**
371 * @see JobQueue::doAck()
372 * @param Job $job
373 * @throws MWException
374 * @return Job|bool
375 */
376 protected function doAck( Job $job ) {
377 if ( !$job->getId() ) {
378 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
379 }
380
381 $dbw = $this->getMasterDB();
382 $dbw->commit( __METHOD__, 'flush' ); // flush existing transaction
383
384 // Delete a row with a single DELETE without holding row locks over RTTs...
385 $dbw->delete( 'job',
386 array( 'job_cmd' => $this->type, 'job_id' => $job->getId() ), __METHOD__ );
387
388 return true;
389 }
390
391 /**
392 * @see JobQueue::doDeduplicateRootJob()
393 * @param Job $job
394 * @throws MWException
395 * @return bool
396 */
397 protected function doDeduplicateRootJob( Job $job ) {
398 $params = $job->getParams();
399 if ( !isset( $params['rootJobSignature'] ) ) {
400 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
401 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
402 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
403 }
404 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
405 // Callers should call batchInsert() and then this function so that if the insert
406 // fails, the de-duplication registration will be aborted. Since the insert is
407 // deferred till "transaction idle", do that same here, so that the ordering is
408 // maintained. Having only the de-duplication registration succeed would cause
409 // jobs to become no-ops without any actual jobs that made them redundant.
410 $this->getMasterDB()->onTransactionIdle( function() use ( $params, $key ) {
411 global $wgMemc;
412
413 $timestamp = $wgMemc->get( $key ); // current last timestamp of this job
414 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
415 return true; // a newer version of this root job was enqueued
416 }
417
418 // Update the timestamp of the last root job started at the location...
419 return $wgMemc->set( $key, $params['rootJobTimestamp'], 14*86400 ); // 2 weeks
420 } );
421
422 return true;
423 }
424
425 /**
426 * Check if the "root" job of a given job has been superseded by a newer one
427 *
428 * @param $job Job
429 * @return bool
430 */
431 protected function isRootJobOldDuplicate( Job $job ) {
432 global $wgMemc;
433
434 $params = $job->getParams();
435 if ( !isset( $params['rootJobSignature'] ) ) {
436 return false; // job has no de-deplication info
437 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
438 trigger_error( "Cannot check root job; missing 'rootJobTimestamp'." );
439 return false;
440 }
441
442 // Get the last time this root job was enqueued
443 $timestamp = $wgMemc->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
444
445 // Check if a new root job was started at the location after this one's...
446 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
447 }
448
449 /**
450 * @see JobQueue::doWaitForBackups()
451 * @return void
452 */
453 protected function doWaitForBackups() {
454 wfWaitForSlaves();
455 }
456
457 /**
458 * @return DatabaseBase
459 */
460 protected function getSlaveDB() {
461 return wfGetDB( DB_SLAVE, array(), $this->wiki );
462 }
463
464 /**
465 * @return DatabaseBase
466 */
467 protected function getMasterDB() {
468 return wfGetDB( DB_MASTER, array(), $this->wiki );
469 }
470
471 /**
472 * @param $job Job
473 * @return array
474 */
475 protected function insertFields( Job $job ) {
476 $dbw = $this->getMasterDB();
477 return array(
478 // Fields that describe the nature of the job
479 'job_cmd' => $job->getType(),
480 'job_namespace' => $job->getTitle()->getNamespace(),
481 'job_title' => $job->getTitle()->getDBkey(),
482 'job_params' => self::makeBlob( $job->getParams() ),
483 // Additional job metadata
484 'job_id' => $dbw->nextSequenceValue( 'job_job_id_seq' ),
485 'job_timestamp' => $dbw->timestamp(),
486 'job_sha1' => wfBaseConvert(
487 sha1( serialize( $job->getDeduplicationInfo() ) ),
488 16, 36, 31
489 ),
490 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
491 );
492 }
493
494 /**
495 * @return string
496 */
497 private function getEmptinessCacheKey() {
498 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
499 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'isempty' );
500 }
501
502 /**
503 * @param string $signature Hash identifier of the root job
504 * @return string
505 */
506 private function getRootJobCacheKey( $signature ) {
507 list( $db, $prefix ) = wfSplitWikiID( $this->wiki );
508 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $this->type, 'rootjob', $signature );
509 }
510
511 /**
512 * @param $params
513 * @return string
514 */
515 protected static function makeBlob( $params ) {
516 if ( $params !== false ) {
517 return serialize( $params );
518 } else {
519 return '';
520 }
521 }
522
523 /**
524 * @param $blob
525 * @return bool|mixed
526 */
527 protected static function extractBlob( $blob ) {
528 if ( (string)$blob !== '' ) {
529 return unserialize( $blob );
530 } else {
531 return false;
532 }
533 }
534 }