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