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