53 parent::__construct( $params );
55 $this->cluster = isset( $params[
'cluster'] ) ? $params[
'cluster'] :
false;
60 return [
'random',
'timestamp',
'fifo' ];
74 $found =
$dbr->selectField(
75 'job',
'1', [
'job_cmd' => $this->
type,
'job_token' =>
'' ], __METHOD__
91 $size = $this->
cache->get( $key );
92 if ( is_int( $size ) ) {
98 $size = (int)
$dbr->selectField(
'job',
'COUNT(*)',
99 [
'job_cmd' => $this->type,
'job_token' =>
'' ],
105 $this->
cache->set( $key, $size, self::CACHE_TTL_SHORT );
115 if ( $this->claimTTL <= 0 ) {
128 $count = (int)
$dbr->selectField(
'job',
'COUNT(*)',
129 [
'job_cmd' => $this->type,
"job_token != {$dbr->addQuotes( '' )}" ],
135 $this->
cache->set( $key,
$count, self::CACHE_TTL_SHORT );
146 if ( $this->claimTTL <= 0 ) {
159 $count = (int)
$dbr->selectField(
'job',
'COUNT(*)',
161 'job_cmd' => $this->type,
162 "job_token != {$dbr->addQuotes( '' )}",
163 "job_attempts >= " .
$dbr->addQuotes( $this->maxTries )
171 $this->
cache->set( $key,
$count, self::CACHE_TTL_SHORT );
186 $method = __METHOD__;
187 $dbw->onTransactionIdle(
188 function ()
use ( $dbw, $jobs,
$flags, $method ) {
206 if ( !count( $jobs ) ) {
212 foreach ( $jobs
as $job ) {
214 if ( $job->ignoreDuplicates() ) {
215 $rowSet[$row[
'job_sha1']] = $row;
221 if (
$flags & self::QOS_ATOMIC ) {
226 if ( count( $rowSet ) ) {
230 'job_sha1' => array_keys( $rowSet ),
235 foreach (
$res as $row ) {
236 wfDebug(
"Job with hash '{$row->job_sha1}' is a duplicate.\n" );
237 unset( $rowSet[$row->job_sha1] );
241 $rows = array_merge( $rowList, array_values( $rowSet ) );
243 foreach ( array_chunk( $rows, 50 )
as $rowBatch ) {
244 $dbw->
insert(
'job', $rowBatch, $method );
248 count( $rowSet ) + count( $rowList ) - count( $rows )
253 if (
$flags & self::QOS_ATOMIC ) {
267 $autoTrx = $dbw->getFlag(
DBO_TRX );
269 $scopedReset =
new ScopedCallback(
function ()
use ( $dbw, $autoTrx ) {
270 $dbw->setFlag( $autoTrx ?
DBO_TRX : 0 );
277 if ( in_array( $this->
order, [
'fifo',
'timestamp' ] ) ) {
280 $rand = mt_rand( 0, self::MAX_JOB_RANDOM );
281 $gte = (bool)mt_rand( 0, 1 );
292 self::extractBlob( $row->job_params ), $row->job_id );
293 $job->metadata[
'id'] = $row->job_id;
294 $job->metadata[
'timestamp'] = $row->job_timestamp;
298 if ( !
$job || mt_rand( 0, 9 ) == 0 ) {
324 $invertedDirection =
false;
333 $ineq = $gte ?
'>=' :
'<=';
334 $dir = $gte ?
'ASC' :
'DESC';
335 $row = $dbw->selectRow(
'job', self::selectFields(),
337 'job_cmd' => $this->
type,
339 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ],
341 [
'ORDER BY' =>
"job_random {$dir}" ]
343 if ( !$row && !$invertedDirection ) {
345 $invertedDirection =
true;
352 $row = $dbw->selectRow(
'job', self::selectFields(),
354 'job_cmd' => $this->
type,
358 [
'OFFSET' => mt_rand( 0, self::MAX_OFFSET ) ]
370 'job_token' => $uuid,
371 'job_token_timestamp' => $dbw->timestamp(),
372 'job_attempts = job_attempts+1' ],
373 [
'job_cmd' =>
$this->type,
'job_id' => $row->job_id,
'job_token' =>
'' ],
378 if ( !$dbw->affectedRows() ) {
400 if ( $dbw->getType() ===
'mysql' ) {
405 $dbw->query(
"UPDATE {$dbw->tableName( 'job' )} " .
407 "job_token = {$dbw->addQuotes( $uuid ) }, " .
408 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
409 "job_attempts = job_attempts+1 " .
411 "job_cmd = {$dbw->addQuotes( $this->type )} " .
412 "AND job_token = {$dbw->addQuotes( '' )} " .
413 ") ORDER BY job_id ASC LIMIT 1",
421 'job_token' => $uuid,
422 'job_token_timestamp' => $dbw->timestamp(),
423 'job_attempts = job_attempts+1' ],
425 $dbw->selectSQLText(
'job',
'job_id',
426 [
'job_cmd' => $this->
type,
'job_token' =>
'' ],
428 [
'ORDER BY' =>
'job_id ASC',
'LIMIT' => 1 ] ) .
435 if ( $dbw->affectedRows() ) {
436 $row = $dbw->selectRow(
'job', self::selectFields(),
437 [
'job_cmd' => $this->
type,
'job_token' => $uuid ], __METHOD__
440 wfDebug(
"Row deleted as duplicate by another process.\n" );
456 if ( !isset( $job->metadata[
'id'] ) ) {
457 throw new MWException(
"Job of type '{$job->getType()}' has no ID." );
462 $autoTrx = $dbw->getFlag(
DBO_TRX );
464 $scopedReset =
new ScopedCallback(
function ()
use ( $dbw, $autoTrx ) {
465 $dbw->setFlag( $autoTrx ?
DBO_TRX : 0 );
470 [
'job_cmd' => $this->
type,
'job_id' => $job->metadata[
'id'] ], __METHOD__ );
486 if ( !isset(
$params[
'rootJobSignature'] ) ) {
487 throw new MWException(
"Cannot register root job; missing 'rootJobSignature'." );
488 } elseif ( !isset(
$params[
'rootJobTimestamp'] ) ) {
489 throw new MWException(
"Cannot register root job; missing 'rootJobTimestamp'." );
499 $dbw->onTransactionIdle(
522 $dbw->delete(
'job', [
'job_cmd' => $this->
type ] );
535 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
536 $lbFactory->waitForReplication( [
'wiki' => $this->
wiki,
'cluster' => $this->cluster ] );
543 foreach ( [
'size',
'acquiredcount' ]
as $type ) {
572 $dbr->select(
'job', self::selectFields(), $conds ),
577 strlen( $row->job_params ) ?
unserialize( $row->job_params ) : []
579 $job->metadata[
'id'] = $row->job_id;
580 $job->metadata[
'timestamp'] = $row->job_timestamp;
591 return $this->cluster
592 ?
"DBCluster:{$this->cluster}:{$this->wiki}"
593 :
"LBFactory:{$this->wiki}";
602 $res =
$dbr->select(
'job',
'DISTINCT job_cmd',
603 [
'job_cmd' => $types ], __METHOD__ );
606 foreach (
$res as $row ) {
607 $types[] = $row->job_cmd;
615 $res =
$dbr->select(
'job', [
'job_cmd',
'COUNT(*) AS count' ],
616 [
'job_cmd' => $types ], __METHOD__, [
'GROUP BY' =>
'job_cmd' ] );
619 foreach (
$res as $row ) {
620 $sizes[$row->job_cmd] = (int)$row->count;
637 if ( !$dbw->lock(
"jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
642 if ( $this->claimTTL > 0 ) {
643 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
647 $res = $dbw->select(
'job',
'job_id',
649 'job_cmd' => $this->
type,
650 "job_token != {$dbw->addQuotes( '' )}",
651 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}",
652 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ],
658 }, iterator_to_array(
$res )
660 if ( count( $ids ) ) {
667 'job_token_timestamp' => $dbw->timestamp( $now ) ],
672 $affected = $dbw->affectedRows();
675 $this->aggr->notifyQueueNonEmpty( $this->
wiki, $this->
type );
680 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
683 "job_token != {$dbw->addQuotes( '' )}",
684 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}"
686 if ( $this->claimTTL > 0 ) {
687 $conds[] =
"job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
691 $res = $dbw->select(
'job',
'job_id', $conds, __METHOD__ );
695 }, iterator_to_array(
$res )
697 if ( count( $ids ) ) {
698 $dbw->delete(
'job', [
'job_id' => $ids ], __METHOD__ );
699 $affected = $dbw->affectedRows();
704 $dbw->unlock(
"jobqueue-recycle-{$this->type}", __METHOD__ );
722 'job_namespace' => $job->
getTitle()->getNamespace(),
723 'job_title' => $job->
getTitle()->getDBkey(),
724 'job_params' => self::makeBlob( $job->
getParams() ),
726 'job_id' => $dbw->nextSequenceValue(
'job_job_id_seq' ),
727 'job_timestamp' => $dbw->timestamp(),
728 'job_sha1' => Wikimedia\base_convert(
732 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
764 protected function getDB( $index ) {
765 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
766 $lb = ( $this->cluster !==
false )
767 ?
$lbFactory->getExternalLB( $this->cluster, $this->wiki )
770 return $lb->getConnectionRef( $index, [], $this->
wiki );
779 $cluster = is_string( $this->cluster ) ? $this->cluster :
'main';
801 if ( (
string)
$blob !==
'' ) {
813 throw new JobQueueError( get_class( $e ) .
": " . $e->getMessage() );
832 'job_token_timestamp',
set($key, $value, $ttl=0, array $opts=[])
Set the value of a key in cache.
doBatchPushInternal(IDatabase $dbw, array $jobs, $flags, $method)
This function should not be called outside of JobQueueDB.
static extractBlob($blob)
static incrStats($key, $type, $delta=1)
Call wfIncrStats() for the queue overall and for the queue type.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any order
static getMainWANInstance()
Get the main WAN cache object.
insert($table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
wfForeignMemcKey($db, $prefix)
Make a cache key for a foreign DB.
getCoalesceLocationInternal()
processing should stop and the error should be shown to the user * false
__construct(array $params)
Additional parameters include:
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
doGetSiblingQueuesWithJobs(array $types)
Class to both describe a background job and handle jobs.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
it s the revision text itself In either if gzip is the revision text is gzipped $flags
get($key, &$curTTL=null, array $checkKeys=[], &$asOf=null)
Fetch the value of a key from cache.
Class to handle job queues stored in the DB.
wfRandomString($length=32)
Get a random string containing a number of pseudo-random hex characters.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Prior to maintenance scripts were a hodgepodge of code that had no cohesion or formal method of action Beginning maintenance scripts have been cleaned up to use a unified class Directory structure How to run a script How to write your own DIRECTORY STRUCTURE The maintenance directory of a MediaWiki installation contains several all of which have unique purposes HOW TO RUN A SCRIPT Ridiculously just call php someScript php that s in the top level maintenance directory if not default wiki
recycleAndDeleteStaleJobs()
Recycle or destroy any jobs that have been claimed for too long.
you have access to all of the normal MediaWiki so you can get a DB use the cache
throwDBException(DBError $e)
getRootJobCacheKey($signature)
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
namespace and then decline to actually register it file or subcat img or subcat $title
endAtomic($fname=__METHOD__)
Ends an atomic section of SQL statements.
getJobIterator(array $conds)
doBatchPush(array $jobs, $flags)
Convenience class for generating iterators from iterators.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
claimRandom($uuid, $rand, $gte)
Reserve a row with a single UPDATE without holding row locks over RTTs...
startAtomic($fname=__METHOD__)
Begin an atomic section of statements.
doDeduplicateRootJob(IJobSpecification $job)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
static factory($command, Title $title, $params=[])
Create the appropriate object to handle a specific job.
Class to handle enqueueing and running of background jobs.
doGetSiblingQueueSizes(array $types)
static selectFields()
Return the list of job fields that should be selected.
Job queue task description interface.
claimOldest($uuid)
Reserve a row with a single UPDATE without holding row locks over RTTs...
wfSplitWikiID($wiki)
Split a wiki ID into DB name and table prefix.
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Basic database interface for live and lazy-loaded relation database handles.
insertFields(IJobSpecification $job)
bool string $cluster
Name of an external DB cluster.