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