Moved view count from WikiPage to Title; avoids an extra DB query when showing the...
[lhc/web/wiklou.git] / includes / objectcache / SqlBagOStuff.php
1 <?php
2
3 /**
4 * Class to store objects in the database
5 *
6 * @ingroup Cache
7 */
8 class SqlBagOStuff extends BagOStuff {
9
10 /**
11 * @var LoadBalancer
12 */
13 var $lb;
14
15 /**
16 * @var DatabaseBase
17 */
18 var $db;
19 var $serverInfo;
20 var $lastExpireAll = 0;
21 var $purgePeriod = 100;
22 var $shards = 1;
23 var $tableName = 'objectcache';
24
25 /**
26 * Constructor. Parameters are:
27 * - server: A server info structure in the format required by each
28 * element in $wgDBServers.
29 *
30 * - purgePeriod: The average number of object cache requests in between
31 * garbage collection operations, where expired entries
32 * are removed from the database. Or in other words, the
33 * reciprocal of the probability of purging on any given
34 * request. If this is set to zero, purging will never be
35 * done.
36 *
37 * - tableName: The table name to use, default is "objectcache".
38 *
39 * - shards: The number of tables to use for data storage. If this is
40 * more than 1, table names will be formed in the style
41 * objectcacheNNN where NNN is the shard index, between 0 and
42 * shards-1. The number of digits will be the minimum number
43 * required to hold the largest shard index. Data will be
44 * distributed across all tables by key hash. This is for
45 * MySQL bugs 61735 and 61736.
46 *
47 * @param $params array
48 */
49 public function __construct( $params ) {
50 if ( isset( $params['server'] ) ) {
51 $this->serverInfo = $params['server'];
52 $this->serverInfo['load'] = 1;
53 }
54 if ( isset( $params['purgePeriod'] ) ) {
55 $this->purgePeriod = intval( $params['purgePeriod'] );
56 }
57 if ( isset( $params['tableName'] ) ) {
58 $this->tableName = $params['tableName'];
59 }
60 if ( isset( $params['shards'] ) ) {
61 $this->shards = intval( $params['shards'] );
62 }
63 }
64
65 /**
66 * @return DatabaseBase
67 */
68 protected function getDB() {
69 if ( !isset( $this->db ) ) {
70 # If server connection info was given, use that
71 if ( $this->serverInfo ) {
72 $this->lb = new LoadBalancer( array(
73 'servers' => array( $this->serverInfo ) ) );
74 $this->db = $this->lb->getConnection( DB_MASTER );
75 $this->db->clearFlag( DBO_TRX );
76 } else {
77 # We must keep a separate connection to MySQL in order to avoid deadlocks
78 # However, SQLite has an opposite behaviour.
79 # @todo Investigate behaviour for other databases
80 if ( wfGetDB( DB_MASTER )->getType() == 'sqlite' ) {
81 $this->db = wfGetDB( DB_MASTER );
82 } else {
83 $this->lb = wfGetLBFactory()->newMainLB();
84 $this->db = $this->lb->getConnection( DB_MASTER );
85 $this->db->clearFlag( DBO_TRX );
86 }
87 }
88 }
89
90 return $this->db;
91 }
92
93 /**
94 * Get the table name for a given key
95 */
96 protected function getTableByKey( $key ) {
97 if ( $this->shards > 1 ) {
98 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
99 return $this->getTableByShard( $hash % $this->shards );
100 } else {
101 return $this->tableName;
102 }
103 }
104
105 /**
106 * Get the table name for a given shard index
107 */
108 protected function getTableByShard( $index ) {
109 if ( $this->shards > 1 ) {
110 $decimals = strlen( $this->shards - 1 );
111 return $this->tableName .
112 sprintf( "%0{$decimals}d", $index );
113 } else {
114 return $this->tableName;
115 }
116 }
117
118 public function get( $key ) {
119 # expire old entries if any
120 $this->garbageCollect();
121 $db = $this->getDB();
122 $tableName = $this->getTableByKey( $key );
123 $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
124 array( 'keyname' => $key ), __METHOD__ );
125
126 if ( !$row ) {
127 $this->debug( 'get: no matching rows' );
128 return false;
129 }
130
131 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
132
133 if ( $this->isExpired( $row->exptime ) ) {
134 $this->debug( "get: key has expired, deleting" );
135 try {
136 $db->begin();
137 # Put the expiry time in the WHERE condition to avoid deleting a
138 # newly-inserted value
139 $db->delete( $tableName,
140 array(
141 'keyname' => $key,
142 'exptime' => $row->exptime
143 ), __METHOD__ );
144 $db->commit();
145 } catch ( DBQueryError $e ) {
146 $this->handleWriteError( $e );
147 }
148
149 return false;
150 }
151
152 return $this->unserialize( $db->decodeBlob( $row->value ) );
153 }
154
155 public function set( $key, $value, $exptime = 0 ) {
156 $db = $this->getDB();
157 $exptime = intval( $exptime );
158
159 if ( $exptime < 0 ) {
160 $exptime = 0;
161 }
162
163 if ( $exptime == 0 ) {
164 $encExpiry = $this->getMaxDateTime();
165 } else {
166 if ( $exptime < 3.16e8 ) { # ~10 years
167 $exptime += time();
168 }
169
170 $encExpiry = $db->timestamp( $exptime );
171 }
172 try {
173 $db->begin();
174 // (bug 24425) use a replace if the db supports it instead of
175 // delete/insert to avoid clashes with conflicting keynames
176 $db->replace(
177 $this->getTableByKey( $key ),
178 array( 'keyname' ),
179 array(
180 'keyname' => $key,
181 'value' => $db->encodeBlob( $this->serialize( $value ) ),
182 'exptime' => $encExpiry
183 ), __METHOD__ );
184 $db->commit();
185 } catch ( DBQueryError $e ) {
186 $this->handleWriteError( $e );
187
188 return false;
189 }
190
191 return true;
192 }
193
194 public function delete( $key, $time = 0 ) {
195 $db = $this->getDB();
196
197 try {
198 $db->begin();
199 $db->delete(
200 $this->getTableByKey( $key ),
201 array( 'keyname' => $key ),
202 __METHOD__ );
203 $db->commit();
204 } catch ( DBQueryError $e ) {
205 $this->handleWriteError( $e );
206
207 return false;
208 }
209
210 return true;
211 }
212
213 public function incr( $key, $step = 1 ) {
214 $db = $this->getDB();
215 $tableName = $this->getTableByKey( $key );
216 $step = intval( $step );
217
218 try {
219 $db->begin();
220 $row = $db->selectRow(
221 $tableName,
222 array( 'value', 'exptime' ),
223 array( 'keyname' => $key ),
224 __METHOD__,
225 array( 'FOR UPDATE' ) );
226 if ( $row === false ) {
227 // Missing
228 $db->commit();
229
230 return null;
231 }
232 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
233 if ( $this->isExpired( $row->exptime ) ) {
234 // Expired, do not reinsert
235 $db->commit();
236
237 return null;
238 }
239
240 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
241 $newValue = $oldValue + $step;
242 $db->insert( $tableName,
243 array(
244 'keyname' => $key,
245 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
246 'exptime' => $row->exptime
247 ), __METHOD__, 'IGNORE' );
248
249 if ( $db->affectedRows() == 0 ) {
250 // Race condition. See bug 28611
251 $newValue = null;
252 }
253 $db->commit();
254 } catch ( DBQueryError $e ) {
255 $this->handleWriteError( $e );
256
257 return null;
258 }
259
260 return $newValue;
261 }
262
263 public function keys() {
264 $db = $this->getDB();
265 $result = array();
266
267 for ( $i = 0; $i < $this->shards; $i++ ) {
268 $res = $db->select( $this->getTableByShard( $i ),
269 array( 'keyname' ), false, __METHOD__ );
270 foreach ( $res as $row ) {
271 $result[] = $row->keyname;
272 }
273 }
274
275 return $result;
276 }
277
278 protected function isExpired( $exptime ) {
279 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
280 }
281
282 protected function getMaxDateTime() {
283 if ( time() > 0x7fffffff ) {
284 return $this->getDB()->timestamp( 1 << 62 );
285 } else {
286 return $this->getDB()->timestamp( 0x7fffffff );
287 }
288 }
289
290 protected function garbageCollect() {
291 if ( !$this->purgePeriod ) {
292 // Disabled
293 return;
294 }
295 // Only purge on one in every $this->purgePeriod requests.
296 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
297 return;
298 }
299 $now = time();
300 // Avoid repeating the delete within a few seconds
301 if ( $now > ( $this->lastExpireAll + 1 ) ) {
302 $this->lastExpireAll = $now;
303 $this->expireAll();
304 }
305 }
306
307 public function expireAll() {
308 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
309 }
310
311 /**
312 * Delete objects from the database which expire before a certain date.
313 */
314 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
315 $db = $this->getDB();
316 $dbTimestamp = $db->timestamp( $timestamp );
317 $totalSeconds = false;
318 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
319
320 try {
321 for ( $i = 0; $i < $this->shards; $i++ ) {
322 $maxExpTime = false;
323 while ( true ) {
324 $conds = $baseConds;
325 if ( $maxExpTime !== false ) {
326 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
327 }
328 $rows = $db->select(
329 $this->getTableByShard( $i ),
330 array( 'keyname', 'exptime' ),
331 $conds,
332 __METHOD__,
333 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
334 if ( !$rows->numRows() ) {
335 break;
336 }
337 $keys = array();
338 $row = $rows->current();
339 $minExpTime = $row->exptime;
340 if ( $totalSeconds === false ) {
341 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
342 - wfTimestamp( TS_UNIX, $minExpTime );
343 }
344 foreach ( $rows as $row ) {
345 $keys[] = $row->keyname;
346 $maxExpTime = $row->exptime;
347 }
348
349 $db->begin();
350 $db->delete(
351 $this->getTableByShard( $i ),
352 array(
353 'exptime >= ' . $db->addQuotes( $minExpTime ),
354 'exptime < ' . $db->addQuotes( $dbTimestamp ),
355 'keyname' => $keys
356 ),
357 __METHOD__ );
358 $db->commit();
359
360 if ( $progressCallback ) {
361 if ( intval( $totalSeconds ) === 0 ) {
362 $percent = 0;
363 } else {
364 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
365 - wfTimestamp( TS_UNIX, $maxExpTime );
366 if ( $remainingSeconds > $totalSeconds ) {
367 $totalSeconds = $remainingSeconds;
368 }
369 $percent = ( $i + $remainingSeconds / $totalSeconds )
370 / $this->shards * 100;
371 }
372 call_user_func( $progressCallback, $percent );
373 }
374 }
375 }
376 } catch ( DBQueryError $e ) {
377 $this->handleWriteError( $e );
378 }
379 return true;
380 }
381
382 public function deleteAll() {
383 $db = $this->getDB();
384
385 try {
386 for ( $i = 0; $i < $this->shards; $i++ ) {
387 $db->begin();
388 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__ );
389 $db->commit();
390 }
391 } catch ( DBQueryError $e ) {
392 $this->handleWriteError( $e );
393 }
394 }
395
396 /**
397 * Serialize an object and, if possible, compress the representation.
398 * On typical message and page data, this can provide a 3X decrease
399 * in storage requirements.
400 *
401 * @param $data mixed
402 * @return string
403 */
404 protected function serialize( &$data ) {
405 $serial = serialize( $data );
406
407 if ( function_exists( 'gzdeflate' ) ) {
408 return gzdeflate( $serial );
409 } else {
410 return $serial;
411 }
412 }
413
414 /**
415 * Unserialize and, if necessary, decompress an object.
416 * @param $serial string
417 * @return mixed
418 */
419 protected function unserialize( $serial ) {
420 if ( function_exists( 'gzinflate' ) ) {
421 wfSuppressWarnings();
422 $decomp = gzinflate( $serial );
423 wfRestoreWarnings();
424
425 if ( false !== $decomp ) {
426 $serial = $decomp;
427 }
428 }
429
430 $ret = unserialize( $serial );
431
432 return $ret;
433 }
434
435 /**
436 * Handle a DBQueryError which occurred during a write operation.
437 * Ignore errors which are due to a read-only database, rethrow others.
438 */
439 protected function handleWriteError( $exception ) {
440 $db = $this->getDB();
441
442 if ( !$db->wasReadOnlyError() ) {
443 throw $exception;
444 }
445
446 try {
447 $db->rollback();
448 } catch ( DBQueryError $e ) {
449 }
450
451 wfDebug( __METHOD__ . ": ignoring query error\n" );
452 $db->ignoreErrors( false );
453 }
454
455 /**
456 * Create shard tables. For use from eval.php.
457 */
458 public function createTables() {
459 $db = $this->getDB();
460 if ( $db->getType() !== 'mysql'
461 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
462 {
463 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
464 }
465
466 for ( $i = 0; $i < $this->shards; $i++ ) {
467 $db->begin();
468 $db->query(
469 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
470 ' LIKE ' . $db->tableName( 'objectcache' ),
471 __METHOD__ );
472 $db->commit();
473 }
474 }
475 }
476
477 /**
478 * Backwards compatibility alias
479 */
480 class MediaWikiBagOStuff extends SqlBagOStuff { }
481