Merge "maintenance: Deprecate Maintenance::hasArg/getArg with no param"
[lhc/web/wiklou.git] / includes / jobqueue / jobs / RefreshLinksJob.php
1 <?php
2 /**
3 * Job to update link tables for pages
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 * @ingroup JobQueue
22 */
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Revision\RevisionRecord;
25
26 /**
27 * Job to update link tables for pages
28 *
29 * This job comes in a few variants:
30 * - a) Recursive jobs to update links for backlink pages for a given title.
31 * These jobs have (recursive:true,table:<table>) set.
32 * - b) Jobs to update links for a set of pages (the job title is ignored).
33 * These jobs have (pages:(<page ID>:(<namespace>,<title>),...) set.
34 * - c) Jobs to update links for a single page (the job title)
35 * These jobs need no extra fields set.
36 *
37 * @ingroup JobQueue
38 */
39 class RefreshLinksJob extends Job {
40 /** @var float Cache parser output when it takes this long to render */
41 const PARSE_THRESHOLD_SEC = 1.0;
42 /** @var int Lag safety margin when comparing root job times to last-refresh times */
43 const CLOCK_FUDGE = 10;
44 /** @var int How many seconds to wait for replica DBs to catch up */
45 const LAG_WAIT_TIMEOUT = 15;
46
47 function __construct( Title $title, array $params ) {
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 // This will control transaction rounds in order to run DataUpdates
58 $this->executionFlags |= self::JOB_NO_EXPLICIT_TRX_ROUND;
59 }
60
61 /**
62 * @param Title $title
63 * @param array $params
64 * @return RefreshLinksJob
65 */
66 public static function newPrioritized( Title $title, array $params ) {
67 $job = new self( $title, $params );
68 $job->command = 'refreshLinksPrioritized';
69
70 return $job;
71 }
72
73 /**
74 * @param Title $title
75 * @param array $params
76 * @return RefreshLinksJob
77 */
78 public static function newDynamic( Title $title, array $params ) {
79 $job = new self( $title, $params );
80 $job->command = 'refreshLinksDynamic';
81
82 return $job;
83 }
84
85 function run() {
86 global $wgUpdateRowsPerJob;
87
88 $ok = true;
89 // Job to update all (or a range of) backlink pages for a page
90 if ( !empty( $this->params['recursive'] ) ) {
91 // When the base job branches, wait for the replica DBs to catch up to the master.
92 // From then on, we know that any template changes at the time the base job was
93 // enqueued will be reflected in backlink page parses when the leaf jobs run.
94 if ( !isset( $this->params['range'] ) ) {
95 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
96 if ( !$lbFactory->waitForReplication( [
97 'domain' => $lbFactory->getLocalDomainID(),
98 'timeout' => self::LAG_WAIT_TIMEOUT
99 ] ) ) { // only try so hard
100 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
101 $stats->increment( 'refreshlinks.lag_wait_failed' );
102 }
103 }
104 // Carry over information for de-duplication
105 $extraParams = $this->getRootJobParams();
106 $extraParams['triggeredRecursive'] = true;
107 // Carry over cause information for logging
108 $extraParams['causeAction'] = $this->params['causeAction'];
109 $extraParams['causeAgent'] = $this->params['causeAgent'];
110 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
111 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
112 $jobs = BacklinkJobUtils::partitionBacklinkJob(
113 $this,
114 $wgUpdateRowsPerJob,
115 1, // job-per-title
116 [ 'params' => $extraParams ]
117 );
118 JobQueueGroup::singleton()->push( $jobs );
119 // Job to update link tables for a set of titles
120 } elseif ( isset( $this->params['pages'] ) ) {
121 foreach ( $this->params['pages'] as list( $ns, $dbKey ) ) {
122 $title = Title::makeTitleSafe( $ns, $dbKey );
123 if ( $title ) {
124 $this->runForTitle( $title );
125 } else {
126 $ok = false;
127 $this->setLastError( "Invalid title ($ns,$dbKey)." );
128 }
129 }
130 // Job to update link tables for a given title
131 } else {
132 $this->runForTitle( $this->title );
133 }
134
135 return $ok;
136 }
137
138 /**
139 * @param Title $title
140 * @return bool
141 */
142 protected function runForTitle( Title $title ) {
143 $services = MediaWikiServices::getInstance();
144 $stats = $services->getStatsdDataFactory();
145 $lbFactory = $services->getDBLoadBalancerFactory();
146 $revisionStore = $services->getRevisionStore();
147 $renderer = $services->getRevisionRenderer();
148 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
149
150 $lbFactory->beginMasterChanges( __METHOD__ );
151
152 $page = WikiPage::factory( $title );
153 $page->loadPageData( WikiPage::READ_LATEST );
154
155 // Serialize links updates by page ID so they see each others' changes
156 $dbw = $lbFactory->getMainLB()->getConnection( DB_MASTER );
157 /** @noinspection PhpUnusedLocalVariableInspection */
158 $scopedLock = LinksUpdate::acquirePageLock( $dbw, $page->getId(), 'job' );
159 if ( $scopedLock === null ) {
160 // Another job is already updating the page, likely for an older revision (T170596).
161 $this->setLastError( 'LinksUpdate already running for this page, try again later.' );
162 return false;
163 }
164 // Get the latest ID *after* acquirePageLock() flushed the transaction.
165 // This is used to detect edits/moves after loadPageData() but before the scope lock.
166 // The works around the chicken/egg problem of determining the scope lock key.
167 $latest = $title->getLatestRevID( Title::GAID_FOR_UPDATE );
168
169 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
170 // Fetch the specified revision; lockAndGetLatest() below detects if the page
171 // was edited since and aborts in order to avoid corrupting the link tables
172 $revision = $revisionStore->getRevisionById(
173 (int)$this->params['triggeringRevisionId'],
174 Revision::READ_LATEST
175 );
176 } else {
177 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
178 $revision = $revisionStore->getRevisionByTitle( $title, 0, Revision::READ_LATEST );
179 }
180
181 if ( !$revision ) {
182 $stats->increment( 'refreshlinks.rev_not_found' );
183 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
184 return false; // just deleted?
185 } elseif ( $revision->getId() != $latest || $revision->getPageId() !== $page->getId() ) {
186 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
187 // serialized, it would be OK to update links based on older revisions since it
188 // would eventually get to the latest. Since that is not the case (by design),
189 // only update the link tables to a state matching the current revision's output.
190 $stats->increment( 'refreshlinks.rev_not_current' );
191 $this->setLastError( "Revision {$revision->getId()} is not current" );
192 return false;
193 }
194
195 $parserOutput = false;
196 $parserOptions = $page->makeParserOptions( 'canonical' );
197 // If page_touched changed after this root job, then it is likely that
198 // any views of the pages already resulted in re-parses which are now in
199 // cache. The cache can be reused to avoid expensive parsing in some cases.
200 if ( isset( $this->params['rootJobTimestamp'] ) ) {
201 $opportunistic = !empty( $this->params['isOpportunistic'] );
202
203 $skewedTimestamp = $this->params['rootJobTimestamp'];
204 if ( $opportunistic ) {
205 // Neither clock skew nor DB snapshot/replica DB lag matter much for such
206 // updates; focus on reusing the (often recently updated) cache
207 } else {
208 // For transclusion updates, the template changes must be reflected
209 $skewedTimestamp = wfTimestamp( TS_MW,
210 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
211 );
212 }
213
214 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
215 // Something already updated the backlinks since this job was made
216 $stats->increment( 'refreshlinks.update_skipped' );
217 return true;
218 }
219
220 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
221 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
222 // and it reflects the job's triggering change, then it is usable.
223 $parserOutput = $services->getParserCache()->getDirty( $page, $parserOptions );
224 if ( !$parserOutput
225 || $parserOutput->getCacheRevisionId() != $revision->getId()
226 || $parserOutput->getCacheTime() < $skewedTimestamp
227 ) {
228 $parserOutput = false; // too stale
229 }
230 }
231 }
232
233 // Fetch the current revision and parse it if necessary...
234 if ( $parserOutput ) {
235 $stats->increment( 'refreshlinks.parser_cached' );
236 } else {
237 $start = microtime( true );
238
239 $checkCache = $page->shouldCheckParserCache( $parserOptions, $revision->getId() );
240
241 // Revision ID must be passed to the parser output to get revision variables correct
242 $renderedRevision = $renderer->getRenderedRevision(
243 $revision,
244 $parserOptions,
245 null,
246 [
247 // use master, for consistency with the getRevisionByTitle call above.
248 'use-master' => true,
249 // bypass audience checks, since we know that this is the current revision.
250 'audience' => RevisionRecord::RAW
251 ]
252 );
253 $parserOutput = $renderedRevision->getRevisionParserOutput(
254 // HTML is only needed if the output is to be placed in the parser cache
255 [ 'generate-html' => $checkCache ]
256 );
257
258 // If it took a long time to render, then save this back to the cache to avoid
259 // wasted CPU by other apaches or job runners. We don't want to always save to
260 // cache as this can cause high cache I/O and LRU churn when a template changes.
261 $elapsed = microtime( true ) - $start;
262
263 $parseThreshold = $this->params['parseThreshold'] ?? self::PARSE_THRESHOLD_SEC;
264
265 if ( $checkCache && $elapsed >= $parseThreshold && $parserOutput->isCacheable() ) {
266 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
267 $services->getParserCache()->save(
268 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
269 );
270 }
271 $stats->increment( 'refreshlinks.parser_uncached' );
272 }
273
274 $options = [
275 'recursive' => !empty( $this->params['useRecursiveLinksUpdate'] ),
276 // Carry over cause so the update can do extra logging
277 'causeAction' => $this->params['causeAction'],
278 'causeAgent' => $this->params['causeAgent'],
279 'defer' => false,
280 'transactionTicket' => $ticket,
281 ];
282 if ( !empty( $this->params['triggeringUser'] ) ) {
283 $userInfo = $this->params['triggeringUser'];
284 if ( $userInfo['userId'] ) {
285 $options['triggeringUser'] = User::newFromId( $userInfo['userId'] );
286 } else {
287 // Anonymous, use the username
288 $options['triggeringUser'] = User::newFromName( $userInfo['userName'], false );
289 }
290 }
291
292 $lbFactory->commitMasterChanges( __METHOD__ );
293
294 $page->doSecondaryDataUpdates( $options );
295
296 InfoAction::invalidateCache( $title );
297
298 // Commit any writes here in case this method is called in a loop.
299 // In that case, the scoped lock will fail to be acquired.
300 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
301
302 return true;
303 }
304
305 public function getDeduplicationInfo() {
306 $info = parent::getDeduplicationInfo();
307 unset( $info['causeAction'] );
308 unset( $info['causeAgent'] );
309 if ( is_array( $info['params'] ) ) {
310 // For per-pages jobs, the job title is that of the template that changed
311 // (or similar), so remove that since it ruins duplicate detection
312 if ( isset( $info['params']['pages'] ) ) {
313 unset( $info['namespace'] );
314 unset( $info['title'] );
315 }
316 }
317
318 return $info;
319 }
320
321 public function workItemCount() {
322 if ( !empty( $this->params['recursive'] ) ) {
323 return 0; // nothing actually refreshed
324 } elseif ( isset( $this->params['pages'] ) ) {
325 return count( $this->params['pages'] );
326 }
327
328 return 1; // one title
329 }
330 }