MediaWiki  1.32.5
RefreshLinksJob.php
Go to the documentation of this file.
1 <?php
25 
39 class RefreshLinksJob extends Job {
41  const PARSE_THRESHOLD_SEC = 1.0;
43  const CLOCK_FUDGE = 10;
45  const LAG_WAIT_TIMEOUT = 15;
46 
48  parent::__construct( 'refreshLinks', $title, $params );
49  // Avoid the overhead of de-duplication when it would be pointless
50  $this->removeDuplicates = (
51  // Ranges rarely will line up
52  !isset( $params['range'] ) &&
53  // Multiple pages per job make matches unlikely
54  !( isset( $params['pages'] ) && count( $params['pages'] ) != 1 )
55  );
56  $this->params += [ 'causeAction' => 'unknown', 'causeAgent' => 'unknown' ];
57  }
58 
64  public static function newPrioritized( Title $title, array $params ) {
65  $job = new self( $title, $params );
66  $job->command = 'refreshLinksPrioritized';
67 
68  return $job;
69  }
70 
76  public static function newDynamic( Title $title, array $params ) {
77  $job = new self( $title, $params );
78  $job->command = 'refreshLinksDynamic';
79 
80  return $job;
81  }
82 
83  function run() {
84  global $wgUpdateRowsPerJob;
85 
86  // Job to update all (or a range of) backlink pages for a page
87  if ( !empty( $this->params['recursive'] ) ) {
88  // When the base job branches, wait for the replica DBs to catch up to the master.
89  // From then on, we know that any template changes at the time the base job was
90  // enqueued will be reflected in backlink page parses when the leaf jobs run.
91  if ( !isset( $this->params['range'] ) ) {
92  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
93  if ( !$lbFactory->waitForReplication( [
94  'domain' => $lbFactory->getLocalDomainID(),
95  'timeout' => self::LAG_WAIT_TIMEOUT
96  ] ) ) { // only try so hard
97  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
98  $stats->increment( 'refreshlinks.lag_wait_failed' );
99  }
100  }
101  // Carry over information for de-duplication
102  $extraParams = $this->getRootJobParams();
103  $extraParams['triggeredRecursive'] = true;
104  // Carry over cause information for logging
105  $extraParams['causeAction'] = $this->params['causeAction'];
106  $extraParams['causeAgent'] = $this->params['causeAgent'];
107  // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
108  // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
110  $this,
112  1, // job-per-title
113  [ 'params' => $extraParams ]
114  );
115  JobQueueGroup::singleton()->push( $jobs );
116  // Job to update link tables for a set of titles
117  } elseif ( isset( $this->params['pages'] ) ) {
118  foreach ( $this->params['pages'] as $nsAndKey ) {
119  list( $ns, $dbKey ) = $nsAndKey;
120  $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
121  }
122  // Job to update link tables for a given title
123  } else {
124  $this->runForTitle( $this->title );
125  }
126 
127  return true;
128  }
129 
134  protected function runForTitle( Title $title ) {
135  $services = MediaWikiServices::getInstance();
136  $stats = $services->getStatsdDataFactory();
137  $lbFactory = $services->getDBLoadBalancerFactory();
138  $revisionStore = $services->getRevisionStore();
139  $renderer = $services->getRevisionRenderer();
140  $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
141 
142  $page = WikiPage::factory( $title );
143  $page->loadPageData( WikiPage::READ_LATEST );
144 
145  // Serialize links updates by page ID so they see each others' changes
146  $dbw = $lbFactory->getMainLB()->getConnection( DB_MASTER );
148  $scopedLock = LinksUpdate::acquirePageLock( $dbw, $page->getId(), 'job' );
149  if ( $scopedLock === null ) {
150  // Another job is already updating the page, likely for an older revision (T170596).
151  $this->setLastError( 'LinksUpdate already running for this page, try again later.' );
152  return false;
153  }
154  // Get the latest ID *after* acquirePageLock() flushed the transaction.
155  // This is used to detect edits/moves after loadPageData() but before the scope lock.
156  // The works around the chicken/egg problem of determining the scope lock key.
158 
159  if ( !empty( $this->params['triggeringRevisionId'] ) ) {
160  // Fetch the specified revision; lockAndGetLatest() below detects if the page
161  // was edited since and aborts in order to avoid corrupting the link tables
162  $revision = $revisionStore->getRevisionById(
163  (int)$this->params['triggeringRevisionId'],
164  Revision::READ_LATEST
165  );
166  } else {
167  // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
168  $revision = $revisionStore->getRevisionByTitle( $title, 0, Revision::READ_LATEST );
169  }
170 
171  if ( !$revision ) {
172  $stats->increment( 'refreshlinks.rev_not_found' );
173  $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
174  return false; // just deleted?
175  } elseif ( $revision->getId() != $latest || $revision->getPageId() !== $page->getId() ) {
176  // Do not clobber over newer updates with older ones. If all jobs where FIFO and
177  // serialized, it would be OK to update links based on older revisions since it
178  // would eventually get to the latest. Since that is not the case (by design),
179  // only update the link tables to a state matching the current revision's output.
180  $stats->increment( 'refreshlinks.rev_not_current' );
181  $this->setLastError( "Revision {$revision->getId()} is not current" );
182  return false;
183  }
184 
185  $parserOutput = false;
186  $parserOptions = $page->makeParserOptions( 'canonical' );
187  // If page_touched changed after this root job, then it is likely that
188  // any views of the pages already resulted in re-parses which are now in
189  // cache. The cache can be reused to avoid expensive parsing in some cases.
190  if ( isset( $this->params['rootJobTimestamp'] ) ) {
191  $opportunistic = !empty( $this->params['isOpportunistic'] );
192 
193  $skewedTimestamp = $this->params['rootJobTimestamp'];
194  if ( $opportunistic ) {
195  // Neither clock skew nor DB snapshot/replica DB lag matter much for such
196  // updates; focus on reusing the (often recently updated) cache
197  } else {
198  // For transclusion updates, the template changes must be reflected
199  $skewedTimestamp = wfTimestamp( TS_MW,
200  wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
201  );
202  }
203 
204  if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
205  // Something already updated the backlinks since this job was made
206  $stats->increment( 'refreshlinks.update_skipped' );
207  return true;
208  }
209 
210  if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
211  // Cache is suspected to be up-to-date. As long as the cache rev ID matches
212  // and it reflects the job's triggering change, then it is usable.
213  $parserOutput = $services->getParserCache()->getDirty( $page, $parserOptions );
214  if ( !$parserOutput
215  || $parserOutput->getCacheRevisionId() != $revision->getId()
216  || $parserOutput->getCacheTime() < $skewedTimestamp
217  ) {
218  $parserOutput = false; // too stale
219  }
220  }
221  }
222 
223  // Fetch the current revision and parse it if necessary...
224  if ( $parserOutput ) {
225  $stats->increment( 'refreshlinks.parser_cached' );
226  } else {
227  $start = microtime( true );
228 
229  $checkCache = $page->shouldCheckParserCache( $parserOptions, $revision->getId() );
230 
231  // Revision ID must be passed to the parser output to get revision variables correct
232  $renderedRevision = $renderer->getRenderedRevision(
233  $revision,
234  $parserOptions,
235  null,
236  [
237  // use master, for consistency with the getRevisionByTitle call above.
238  'use-master' => true,
239  // bypass audience checks, since we know that this is the current revision.
240  'audience' => RevisionRecord::RAW
241  ]
242  );
243  $parserOutput = $renderedRevision->getRevisionParserOutput(
244  // HTML is only needed if the output is to be placed in the parser cache
245  [ 'generate-html' => $checkCache ]
246  );
247 
248  // If it took a long time to render, then save this back to the cache to avoid
249  // wasted CPU by other apaches or job runners. We don't want to always save to
250  // cache as this can cause high cache I/O and LRU churn when a template changes.
251  $elapsed = microtime( true ) - $start;
252 
253  $parseThreshold = $this->params['parseThreshold'] ?? self::PARSE_THRESHOLD_SEC;
254 
255  if ( $checkCache && $elapsed >= $parseThreshold && $parserOutput->isCacheable() ) {
256  $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
257  $services->getParserCache()->save(
258  $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
259  );
260  }
261  $stats->increment( 'refreshlinks.parser_uncached' );
262  }
263 
264  $options = [
265  'recursive' => !empty( $this->params['useRecursiveLinksUpdate'] ),
266  // Carry over cause so the update can do extra logging
267  'causeAction' => $this->params['causeAction'],
268  'causeAgent' => $this->params['causeAgent'],
269  'defer' => false,
270  'transactionTicket' => $ticket,
271  ];
272  if ( !empty( $this->params['triggeringUser'] ) ) {
273  $userInfo = $this->params['triggeringUser'];
274  if ( $userInfo['userId'] ) {
275  $options['triggeringUser'] = User::newFromId( $userInfo['userId'] );
276  } else {
277  // Anonymous, use the username
278  $options['triggeringUser'] = User::newFromName( $userInfo['userName'], false );
279  }
280  }
281  $page->doSecondaryDataUpdates( $options );
282 
284 
285  // Commit any writes here in case this method is called in a loop.
286  // In that case, the scoped lock will fail to be acquired.
287  $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
288 
289  return true;
290  }
291 
292  public function getDeduplicationInfo() {
293  $info = parent::getDeduplicationInfo();
294  unset( $info['causeAction'] );
295  unset( $info['causeAgent'] );
296  if ( is_array( $info['params'] ) ) {
297  // For per-pages jobs, the job title is that of the template that changed
298  // (or similar), so remove that since it ruins duplicate detection
299  if ( isset( $info['params']['pages'] ) ) {
300  unset( $info['namespace'] );
301  unset( $info['title'] );
302  }
303  }
304 
305  return $info;
306  }
307 
308  public function workItemCount() {
309  if ( !empty( $this->params['recursive'] ) ) {
310  return 0; // nothing actually refreshed
311  } elseif ( isset( $this->params['pages'] ) ) {
312  return count( $this->params['pages'] );
313  }
314 
315  return 1; // one title
316  }
317 }
Job\getRootJobParams
getRootJobParams()
Definition: Job.php:279
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:615
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:45
LinksUpdate\acquirePageLock
static acquirePageLock(IDatabase $dbw, $pageId, $why='atomicity')
Acquire a lock for performing link table updates for a page on a DB.
Definition: LinksUpdate.php:200
captcha-old.count
count
Definition: captcha-old.py:249
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1954
Job\$title
Title $title
Definition: Job.php:41
RefreshLinksJob\__construct
__construct(Title $title, array $params)
Definition: RefreshLinksJob.php:47
RefreshLinksJob\getDeduplicationInfo
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
Definition: RefreshLinksJob.php:292
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:592
RefreshLinksJob\newDynamic
static newDynamic(Title $title, array $params)
Definition: RefreshLinksJob.php:76
RefreshLinksJob\newPrioritized
static newPrioritized(Title $title, array $params)
Definition: RefreshLinksJob.php:64
Job\$params
array $params
Array of job parameters.
Definition: Job.php:35
Job\setLastError
setLastError( $error)
Definition: Job.php:384
php
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
Definition: injection.txt:35
BacklinkJobUtils\partitionBacklinkJob
static partitionBacklinkJob(Job $job, $bSize, $cSize, $opts=[])
Break down $job into approximately ($bSize/$cSize) leaf jobs and a single partition job that covers t...
Definition: BacklinkJobUtils.php:87
Job
Class to both describe a background job and handle jobs.
Definition: Job.php:30
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:127
RefreshLinksJob\run
run()
Run the job.
Definition: RefreshLinksJob.php:83
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$wgUpdateRowsPerJob
$wgUpdateRowsPerJob
Number of rows to update per job.
Definition: DefaultSettings.php:8480
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
list
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
Definition: deferred.txt:11
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:573
RefreshLinksJob
Job to update link tables for pages.
Definition: RefreshLinksJob.php:39
RefreshLinksJob\workItemCount
workItemCount()
Definition: RefreshLinksJob.php:308
Title\getLatestRevID
getLatestRevID( $flags=0)
What is the page_latest field for this page?
Definition: Title.php:3655
title
title
Definition: parserTests.txt:239
Title\GAID_FOR_UPDATE
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Definition: Title.php:54
Title
Represents a title within MediaWiki.
Definition: Title.php:39
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:69
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:2044
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:48
as
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
Definition: distributors.txt:9
InfoAction\invalidateCache
static invalidateCache(Title $title, $revid=null)
Clear the info cache for a given Title.
Definition: InfoAction.php:70
RefreshLinksJob\runForTitle
runForTitle(Title $title)
Definition: RefreshLinksJob.php:134
$services
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2278
MediaWikiServices
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
Definition: injection.txt:23