Merge "Http::getProxy() method to get proxy configuration"
[lhc/web/wiklou.git] / includes / deferred / SiteStatsUpdate.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 */
20
21 /**
22 * Class for handling updates to the site_stats table
23 */
24 class SiteStatsUpdate implements DeferrableUpdate {
25 /** @var int */
26 protected $edits = 0;
27
28 /** @var int */
29 protected $pages = 0;
30
31 /** @var int */
32 protected $articles = 0;
33
34 /** @var int */
35 protected $users = 0;
36
37 /** @var int */
38 protected $images = 0;
39
40 // @todo deprecate this constructor
41 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
42 $this->edits = $edits;
43 $this->articles = $good;
44 $this->pages = $pages;
45 $this->users = $users;
46 }
47
48 /**
49 * @param array $deltas
50 * @return SiteStatsUpdate
51 */
52 public static function factory( array $deltas ) {
53 $update = new self( 0, 0, 0 );
54
55 $fields = [ 'views', 'edits', 'pages', 'articles', 'users', 'images' ];
56 foreach ( $fields as $field ) {
57 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
58 $update->$field = $deltas[$field];
59 }
60 }
61
62 return $update;
63 }
64
65 public function doUpdate() {
66 global $wgSiteStatsAsyncFactor;
67
68 $this->doUpdateContextStats();
69
70 $rate = $wgSiteStatsAsyncFactor; // convenience
71 // If set to do so, only do actual DB updates 1 every $rate times.
72 // The other times, just update "pending delta" values in memcached.
73 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
74 $this->doUpdatePendingDeltas();
75 } else {
76 // Need a separate transaction because this a global lock
77 wfGetDB( DB_MASTER )->onTransactionIdle( [ $this, 'tryDBUpdateInternal' ] );
78 }
79 }
80
81 /**
82 * Do not call this outside of SiteStatsUpdate
83 */
84 public function tryDBUpdateInternal() {
85 global $wgSiteStatsAsyncFactor;
86
87 $dbw = wfGetDB( DB_MASTER );
88 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
89 $pd = [];
90 if ( $wgSiteStatsAsyncFactor ) {
91 // Lock the table so we don't have double DB/memcached updates
92 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
93 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
94 ) {
95 $this->doUpdatePendingDeltas();
96
97 return;
98 }
99 $pd = $this->getPendingDeltas();
100 // Piggy-back the async deltas onto those of this stats update....
101 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
102 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
103 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
104 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
105 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
106 }
107
108 // Build up an SQL query of deltas and apply them...
109 $updates = '';
110 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
111 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
112 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
113 $this->appendUpdate( $updates, 'ss_users', $this->users );
114 $this->appendUpdate( $updates, 'ss_images', $this->images );
115 if ( $updates != '' ) {
116 $dbw->update( 'site_stats', [ $updates ], [], __METHOD__ );
117 }
118
119 if ( $wgSiteStatsAsyncFactor ) {
120 // Decrement the async deltas now that we applied them
121 $this->removePendingDeltas( $pd );
122 // Commit the updates and unlock the table
123 $dbw->unlock( $lockKey, __METHOD__ );
124 }
125 }
126
127 /**
128 * @param IDatabase $dbw
129 * @return bool|mixed
130 */
131 public static function cacheUpdate( $dbw ) {
132 global $wgActiveUserDays;
133 $dbr = wfGetDB( DB_SLAVE, 'vslow' );
134 # Get non-bot users than did some recent action other than making accounts.
135 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
136 $activeUsers = $dbr->selectField(
137 'recentchanges',
138 'COUNT( DISTINCT rc_user_text )',
139 [
140 'rc_user != 0',
141 'rc_bot' => 0,
142 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
143 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX )
144 - $wgActiveUserDays * 24 * 3600 ) ),
145 ],
146 __METHOD__
147 );
148 $dbw->update(
149 'site_stats',
150 [ 'ss_active_users' => intval( $activeUsers ) ],
151 [ 'ss_row_id' => 1 ],
152 __METHOD__
153 );
154
155 return $activeUsers;
156 }
157
158 protected function doUpdateContextStats() {
159 $stats = RequestContext::getMain()->getStats();
160 foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
161 $delta = $this->$type;
162 if ( $delta !== 0 ) {
163 $stats->updateCount( "site.$type", $delta );
164 }
165 }
166 }
167
168 protected function doUpdatePendingDeltas() {
169 $this->adjustPending( 'ss_total_edits', $this->edits );
170 $this->adjustPending( 'ss_good_articles', $this->articles );
171 $this->adjustPending( 'ss_total_pages', $this->pages );
172 $this->adjustPending( 'ss_users', $this->users );
173 $this->adjustPending( 'ss_images', $this->images );
174 }
175
176 /**
177 * @param string $sql
178 * @param string $field
179 * @param int $delta
180 */
181 protected function appendUpdate( &$sql, $field, $delta ) {
182 if ( $delta ) {
183 if ( $sql ) {
184 $sql .= ',';
185 }
186 if ( $delta < 0 ) {
187 $sql .= "$field=$field-" . abs( $delta );
188 } else {
189 $sql .= "$field=$field+" . abs( $delta );
190 }
191 }
192 }
193
194 /**
195 * @param string $type
196 * @param string $sign ('+' or '-')
197 * @return string
198 */
199 private function getTypeCacheKey( $type, $sign ) {
200 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
201 }
202
203 /**
204 * Adjust the pending deltas for a stat type.
205 * Each stat type has two pending counters, one for increments and decrements
206 * @param string $type
207 * @param int $delta Delta (positive or negative)
208 */
209 protected function adjustPending( $type, $delta ) {
210 $cache = ObjectCache::getMainStashInstance();
211 if ( $delta < 0 ) { // decrement
212 $key = $this->getTypeCacheKey( $type, '-' );
213 } else { // increment
214 $key = $this->getTypeCacheKey( $type, '+' );
215 }
216
217 $magnitude = abs( $delta );
218 $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
219 }
220
221 /**
222 * Get pending delta counters for each stat type
223 * @return array Positive and negative deltas for each type
224 */
225 protected function getPendingDeltas() {
226 $cache = ObjectCache::getMainStashInstance();
227
228 $pending = [];
229 foreach ( [ 'ss_total_edits',
230 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
231 ) {
232 // Get pending increments and pending decrements
233 $flg = BagOStuff::READ_LATEST;
234 $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $type, '+' ), $flg );
235 $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $type, '-' ), $flg );
236 }
237
238 return $pending;
239 }
240
241 /**
242 * Reduce pending delta counters after updates have been applied
243 * @param array $pd Result of getPendingDeltas(), used for DB update
244 */
245 protected function removePendingDeltas( array $pd ) {
246 $cache = ObjectCache::getMainStashInstance();
247
248 foreach ( $pd as $type => $deltas ) {
249 foreach ( $deltas as $sign => $magnitude ) {
250 // Lower the pending counter now that we applied these changes
251 $cache->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
252 }
253 }
254 }
255 }