Merge "Rewrite pref cleanup script"
[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 Wikimedia\Rdbms\DBReplicationWaitError;
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 }
58
59 /**
60 * @param Title $title
61 * @param array $params
62 * @return RefreshLinksJob
63 */
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
71 /**
72 * @param Title $title
73 * @param array $params
74 * @return RefreshLinksJob
75 */
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 try {
93 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
94 $lbFactory->waitForReplication( [
95 'wiki' => wfWikiID(),
96 'timeout' => self::LAG_WAIT_TIMEOUT
97 ] );
98 } catch ( DBReplicationWaitError $e ) { // only try so hard
99 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
100 $stats->increment( 'refreshlinks.lag_wait_failed' );
101 }
102 }
103 // Carry over information for de-duplication
104 $extraParams = $this->getRootJobParams();
105 $extraParams['triggeredRecursive'] = true;
106 // Carry over cause information for logging
107 $extraParams['causeAction'] = $this->params['causeAction'];
108 $extraParams['causeAgent'] = $this->params['causeAgent'];
109 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
110 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
111 $jobs = BacklinkJobUtils::partitionBacklinkJob(
112 $this,
113 $wgUpdateRowsPerJob,
114 1, // job-per-title
115 [ 'params' => $extraParams ]
116 );
117 JobQueueGroup::singleton()->push( $jobs );
118 // Job to update link tables for a set of titles
119 } elseif ( isset( $this->params['pages'] ) ) {
120 foreach ( $this->params['pages'] as $nsAndKey ) {
121 list( $ns, $dbKey ) = $nsAndKey;
122 $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
123 }
124 // Job to update link tables for a given title
125 } else {
126 $this->runForTitle( $this->title );
127 }
128
129 return true;
130 }
131
132 /**
133 * @param Title $title
134 * @return bool
135 */
136 protected function runForTitle( Title $title ) {
137 $services = MediaWikiServices::getInstance();
138 $stats = $services->getStatsdDataFactory();
139 $lbFactory = $services->getDBLoadBalancerFactory();
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 );
147 /** @noinspection PhpUnusedLocalVariableInspection */
148 $scopedLock = LinksUpdate::acquirePageLock( $dbw, $page->getId(), 'job' );
149 // Get the latest ID *after* acquirePageLock() flushed the transaction.
150 // This is used to detect edits/moves after loadPageData() but before the scope lock.
151 // The works around the chicken/egg problem of determining the scope lock key.
152 $latest = $title->getLatestRevID( Title::GAID_FOR_UPDATE );
153
154 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
155 // Fetch the specified revision; lockAndGetLatest() below detects if the page
156 // was edited since and aborts in order to avoid corrupting the link tables
157 $revision = Revision::newFromId(
158 $this->params['triggeringRevisionId'],
159 Revision::READ_LATEST
160 );
161 } else {
162 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
163 $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
164 }
165
166 if ( !$revision ) {
167 $stats->increment( 'refreshlinks.rev_not_found' );
168 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
169 return false; // just deleted?
170 } elseif ( $revision->getId() != $latest || $revision->getPage() !== $page->getId() ) {
171 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
172 // serialized, it would be OK to update links based on older revisions since it
173 // would eventually get to the latest. Since that is not the case (by design),
174 // only update the link tables to a state matching the current revision's output.
175 $stats->increment( 'refreshlinks.rev_not_current' );
176 $this->setLastError( "Revision {$revision->getId()} is not current" );
177 return false;
178 }
179
180 $content = $revision->getContent( Revision::RAW );
181 if ( !$content ) {
182 // If there is no content, pretend the content is empty
183 $content = $revision->getContentHandler()->makeEmptyContent();
184 }
185
186 $parserOutput = false;
187 $parserOptions = $page->makeParserOptions( 'canonical' );
188 // If page_touched changed after this root job, then it is likely that
189 // any views of the pages already resulted in re-parses which are now in
190 // cache. The cache can be reused to avoid expensive parsing in some cases.
191 if ( isset( $this->params['rootJobTimestamp'] ) ) {
192 $opportunistic = !empty( $this->params['isOpportunistic'] );
193
194 $skewedTimestamp = $this->params['rootJobTimestamp'];
195 if ( $opportunistic ) {
196 // Neither clock skew nor DB snapshot/replica DB lag matter much for such
197 // updates; focus on reusing the (often recently updated) cache
198 } else {
199 // For transclusion updates, the template changes must be reflected
200 $skewedTimestamp = wfTimestamp( TS_MW,
201 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
202 );
203 }
204
205 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
206 // Something already updated the backlinks since this job was made
207 $stats->increment( 'refreshlinks.update_skipped' );
208 return true;
209 }
210
211 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
212 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
213 // and it reflects the job's triggering change, then it is usable.
214 $parserOutput = $services->getParserCache()->getDirty( $page, $parserOptions );
215 if ( !$parserOutput
216 || $parserOutput->getCacheRevisionId() != $revision->getId()
217 || $parserOutput->getCacheTime() < $skewedTimestamp
218 ) {
219 $parserOutput = false; // too stale
220 }
221 }
222 }
223
224 // Fetch the current revision and parse it if necessary...
225 if ( $parserOutput ) {
226 $stats->increment( 'refreshlinks.parser_cached' );
227 } else {
228 $start = microtime( true );
229 // Revision ID must be passed to the parser output to get revision variables correct
230 $parserOutput = $content->getParserOutput(
231 $title, $revision->getId(), $parserOptions, false );
232 $elapsed = microtime( true ) - $start;
233 // If it took a long time to render, then save this back to the cache to avoid
234 // wasted CPU by other apaches or job runners. We don't want to always save to
235 // cache as this can cause high cache I/O and LRU churn when a template changes.
236 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
237 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
238 && $parserOutput->isCacheable()
239 ) {
240 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
241 $services->getParserCache()->save(
242 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
243 );
244 }
245 $stats->increment( 'refreshlinks.parser_uncached' );
246 }
247
248 $updates = $content->getSecondaryDataUpdates(
249 $title,
250 null,
251 !empty( $this->params['useRecursiveLinksUpdate'] ),
252 $parserOutput
253 );
254
255 // For legacy hook handlers doing updates via LinksUpdateConstructed, make sure
256 // any pending writes they made get flushed before the doUpdate() calls below.
257 // This avoids snapshot-clearing errors in LinksUpdate::acquirePageLock().
258 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
259
260 foreach ( $updates as $update ) {
261 // Carry over cause in case so the update can do extra logging
262 $update->setCause( $this->params['causeAction'], $this->params['causeAgent'] );
263 // FIXME: This code probably shouldn't be here?
264 // Needed by things like Echo notifications which need
265 // to know which user caused the links update
266 if ( $update instanceof LinksUpdate ) {
267 $update->setRevision( $revision );
268 if ( !empty( $this->params['triggeringUser'] ) ) {
269 $userInfo = $this->params['triggeringUser'];
270 if ( $userInfo['userId'] ) {
271 $user = User::newFromId( $userInfo['userId'] );
272 } else {
273 // Anonymous, use the username
274 $user = User::newFromName( $userInfo['userName'], false );
275 }
276 $update->setTriggeringUser( $user );
277 }
278 }
279 }
280
281 foreach ( $updates as $update ) {
282 $update->setTransactionTicket( $ticket );
283 $update->doUpdate();
284 }
285
286 InfoAction::invalidateCache( $title );
287
288 // Commit any writes here in case this method is called in a loop.
289 // In that case, the scoped lock will fail to be acquired.
290 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
291
292 return true;
293 }
294
295 public function getDeduplicationInfo() {
296 $info = parent::getDeduplicationInfo();
297 unset( $info['causeAction'] );
298 unset( $info['causeAgent'] );
299 if ( is_array( $info['params'] ) ) {
300 // For per-pages jobs, the job title is that of the template that changed
301 // (or similar), so remove that since it ruins duplicate detection
302 if ( isset( $info['params']['pages'] ) ) {
303 unset( $info['namespace'] );
304 unset( $info['title'] );
305 }
306 }
307
308 return $info;
309 }
310
311 public function workItemCount() {
312 if ( !empty( $this->params['recursive'] ) ) {
313 return 0; // nothing actually refreshed
314 } elseif ( isset( $this->params['pages'] ) ) {
315 return count( $this->params['pages'] );
316 }
317
318 return 1; // one title
319 }
320 }