Merge "Remove --max-slave-lag options and remnants from maintenance scripts"
[lhc/web/wiklou.git] / includes / jobqueue / jobs / RecentChangesUpdateJob.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Aaron Schulz
20 * @ingroup JobQueue
21 */
22
23 /**
24 * Job for pruning recent changes
25 *
26 * @ingroup JobQueue
27 * @since 1.25
28 */
29 class RecentChangesUpdateJob extends Job {
30 function __construct( $title, $params ) {
31 parent::__construct( 'recentChangesUpdate', $title, $params );
32
33 if ( !isset( $params['type'] ) ) {
34 throw new Exception( "Missing 'type' parameter." );
35 }
36
37 $this->removeDuplicates = true;
38 }
39
40 /**
41 * @return RecentChangesUpdateJob
42 */
43 final public static function newPurgeJob() {
44 return new self(
45 SpecialPage::getTitleFor( 'Recentchanges' ), array( 'type' => 'purge' )
46 );
47 }
48
49 /**
50 * @return RecentChangesUpdateJob
51 * @since 1.26
52 */
53 final public static function newCacheUpdateJob() {
54 return new self(
55 SpecialPage::getTitleFor( 'Recentchanges' ), array( 'type' => 'cacheUpdate' )
56 );
57 }
58
59 public function run() {
60 if ( $this->params['type'] === 'purge' ) {
61 $this->purgeExpiredRows();
62 } elseif ( $this->params['type'] === 'cacheUpdate' ) {
63 $this->updateActiveUsers();
64 } else {
65 throw new InvalidArgumentException(
66 "Invalid 'type' parameter '{$this->params['type']}'." );
67 }
68
69 return true;
70 }
71
72 protected function purgeExpiredRows() {
73 global $wgRCMaxAge;
74
75 $lockKey = wfWikiID() . ':recentchanges-prune';
76
77 $dbw = wfGetDB( DB_MASTER );
78 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
79 return; // already in progress
80 }
81 $batchSize = 100; // Avoid slave lag
82
83 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
84 do {
85 $rcIds = $dbw->selectFieldValues( 'recentchanges',
86 'rc_id',
87 array( 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ),
88 __METHOD__,
89 array( 'LIMIT' => $batchSize )
90 );
91 if ( $rcIds ) {
92 $dbw->delete( 'recentchanges', array( 'rc_id' => $rcIds ), __METHOD__ );
93 }
94 // Commit in chunks to avoid slave lag
95 $dbw->commit( __METHOD__, 'flush' );
96
97 if ( count( $rcIds ) === $batchSize ) {
98 // There might be more, so try waiting for slaves
99 if ( !wfWaitForSlaves( null, false, false, /* $timeout = */ 3 ) ) {
100 // Another job will continue anyway
101 break;
102 }
103 }
104 } while ( $rcIds );
105
106 $dbw->unlock( $lockKey, __METHOD__ );
107 }
108
109 protected function updateActiveUsers() {
110 global $wgActiveUserDays;
111
112 // Users that made edits at least this many days ago are "active"
113 $days = $wgActiveUserDays;
114 // Pull in the full window of active users in this update
115 $window = $wgActiveUserDays * 86400;
116
117 $dbw = wfGetDB( DB_MASTER );
118 // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
119 // onTransactionIdle() will run immediately since there is no trx.
120 $dbw->onTransactionIdle( function() use ( $dbw, $days, $window ) {
121 // Avoid disconnect/ping() cycle that makes locks fall off
122 $dbw->setSessionOptions( array( 'connTimeout' => 900 ) );
123
124 $lockKey = wfWikiID() . '-activeusers';
125 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
126 return false; // exclusive update (avoids duplicate entries)
127 }
128
129 $nowUnix = time();
130 // Get the last-updated timestamp for the cache
131 $cTime = $dbw->selectField( 'querycache_info',
132 'qci_timestamp',
133 array( 'qci_type' => 'activeusers' )
134 );
135 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
136
137 // Pick the date range to fetch from. This is normally from the last
138 // update to till the present time, but has a limited window for sanity.
139 // If the window is limited, multiple runs are need to fully populate it.
140 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
141 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
142
143 // Get all the users active since the last update
144 $res = $dbw->select(
145 array( 'recentchanges' ),
146 array( 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ),
147 array(
148 'rc_user > 0', // actual accounts
149 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
150 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
151 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
152 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
153 ),
154 __METHOD__,
155 array(
156 'GROUP BY' => array( 'rc_user_text' ),
157 'ORDER BY' => 'NULL' // avoid filesort
158 )
159 );
160 $names = array();
161 foreach ( $res as $row ) {
162 $names[$row->rc_user_text] = $row->lastedittime;
163 }
164
165 // Rotate out users that have not edited in too long (according to old data set)
166 $dbw->delete( 'querycachetwo',
167 array(
168 'qcc_type' => 'activeusers',
169 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
170 ),
171 __METHOD__
172 );
173
174 // Find which of the recently active users are already accounted for
175 if ( count( $names ) ) {
176 $res = $dbw->select( 'querycachetwo',
177 array( 'user_name' => 'qcc_title' ),
178 array(
179 'qcc_type' => 'activeusers',
180 'qcc_namespace' => NS_USER,
181 'qcc_title' => array_keys( $names ) ),
182 __METHOD__
183 );
184 foreach ( $res as $row ) {
185 unset( $names[$row->user_name] );
186 }
187 }
188
189 // Insert the users that need to be added to the list
190 if ( count( $names ) ) {
191 $newRows = array();
192 foreach ( $names as $name => $lastEditTime ) {
193 $newRows[] = array(
194 'qcc_type' => 'activeusers',
195 'qcc_namespace' => NS_USER,
196 'qcc_title' => $name,
197 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
198 'qcc_namespacetwo' => 0, // unused
199 'qcc_titletwo' => '' // unused
200 );
201 }
202 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
203 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
204 wfWaitForSlaves();
205 }
206 }
207
208 // If a transaction was already started, it might have an old
209 // snapshot, so kludge the timestamp range back as needed.
210 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
211
212 // Touch the data freshness timestamp
213 $dbw->replace( 'querycache_info',
214 array( 'qci_type' ),
215 array( 'qci_type' => 'activeusers',
216 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ), // not always $now
217 __METHOD__
218 );
219
220 $dbw->unlock( $lockKey, __METHOD__ );
221 } );
222 }
223 }