4dfa5743ddbe9c0e862bdbbd70c51b0c86b07954
[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 * @return string
96 */
97 protected function getTableByKey( $key ) {
98 if ( $this->shards > 1 ) {
99 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
100 return $this->getTableByShard( $hash % $this->shards );
101 } else {
102 return $this->tableName;
103 }
104 }
105
106 /**
107 * Get the table name for a given shard index
108 * @return string
109 */
110 protected function getTableByShard( $index ) {
111 if ( $this->shards > 1 ) {
112 $decimals = strlen( $this->shards - 1 );
113 return $this->tableName .
114 sprintf( "%0{$decimals}d", $index );
115 } else {
116 return $this->tableName;
117 }
118 }
119
120 public function get( $key ) {
121 # expire old entries if any
122 $this->garbageCollect();
123 $db = $this->getDB();
124 $tableName = $this->getTableByKey( $key );
125 $row = $db->selectRow( $tableName, array( 'value', 'exptime' ),
126 array( 'keyname' => $key ), __METHOD__ );
127
128 if ( !$row ) {
129 $this->debug( 'get: no matching rows' );
130 return false;
131 }
132
133 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
134
135 if ( $this->isExpired( $row->exptime ) ) {
136 $this->debug( "get: key has expired, deleting" );
137 try {
138 $db->begin( __METHOD__ );
139 # Put the expiry time in the WHERE condition to avoid deleting a
140 # newly-inserted value
141 $db->delete( $tableName,
142 array(
143 'keyname' => $key,
144 'exptime' => $row->exptime
145 ), __METHOD__ );
146 $db->commit( __METHOD__ );
147 } catch ( DBQueryError $e ) {
148 $this->handleWriteError( $e );
149 }
150
151 return false;
152 }
153
154 return $this->unserialize( $db->decodeBlob( $row->value ) );
155 }
156
157 public function set( $key, $value, $exptime = 0 ) {
158 $db = $this->getDB();
159 $exptime = intval( $exptime );
160
161 if ( $exptime < 0 ) {
162 $exptime = 0;
163 }
164
165 if ( $exptime == 0 ) {
166 $encExpiry = $this->getMaxDateTime();
167 } else {
168 if ( $exptime < 3.16e8 ) { # ~10 years
169 $exptime += time();
170 }
171
172 $encExpiry = $db->timestamp( $exptime );
173 }
174 try {
175 $db->begin( __METHOD__ );
176 // (bug 24425) use a replace if the db supports it instead of
177 // delete/insert to avoid clashes with conflicting keynames
178 $db->replace(
179 $this->getTableByKey( $key ),
180 array( 'keyname' ),
181 array(
182 'keyname' => $key,
183 'value' => $db->encodeBlob( $this->serialize( $value ) ),
184 'exptime' => $encExpiry
185 ), __METHOD__ );
186 $db->commit( __METHOD__ );
187 } catch ( DBQueryError $e ) {
188 $this->handleWriteError( $e );
189
190 return false;
191 }
192
193 return true;
194 }
195
196 public function delete( $key, $time = 0 ) {
197 $db = $this->getDB();
198
199 try {
200 $db->begin( __METHOD__ );
201 $db->delete(
202 $this->getTableByKey( $key ),
203 array( 'keyname' => $key ),
204 __METHOD__ );
205 $db->commit( __METHOD__ );
206 } catch ( DBQueryError $e ) {
207 $this->handleWriteError( $e );
208
209 return false;
210 }
211
212 return true;
213 }
214
215 public function incr( $key, $step = 1 ) {
216 $db = $this->getDB();
217 $tableName = $this->getTableByKey( $key );
218 $step = intval( $step );
219
220 try {
221 $db->begin( __METHOD__ );
222 $row = $db->selectRow(
223 $tableName,
224 array( 'value', 'exptime' ),
225 array( 'keyname' => $key ),
226 __METHOD__,
227 array( 'FOR UPDATE' ) );
228 if ( $row === false ) {
229 // Missing
230 $db->commit( __METHOD__ );
231
232 return null;
233 }
234 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
235 if ( $this->isExpired( $row->exptime ) ) {
236 // Expired, do not reinsert
237 $db->commit( __METHOD__ );
238
239 return null;
240 }
241
242 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
243 $newValue = $oldValue + $step;
244 $db->insert( $tableName,
245 array(
246 'keyname' => $key,
247 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
248 'exptime' => $row->exptime
249 ), __METHOD__, 'IGNORE' );
250
251 if ( $db->affectedRows() == 0 ) {
252 // Race condition. See bug 28611
253 $newValue = null;
254 }
255 $db->commit( __METHOD__ );
256 } catch ( DBQueryError $e ) {
257 $this->handleWriteError( $e );
258
259 return null;
260 }
261
262 return $newValue;
263 }
264
265 public function keys() {
266 $db = $this->getDB();
267 $result = array();
268
269 for ( $i = 0; $i < $this->shards; $i++ ) {
270 $res = $db->select( $this->getTableByShard( $i ),
271 array( 'keyname' ), false, __METHOD__ );
272 foreach ( $res as $row ) {
273 $result[] = $row->keyname;
274 }
275 }
276
277 return $result;
278 }
279
280 protected function isExpired( $exptime ) {
281 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
282 }
283
284 protected function getMaxDateTime() {
285 if ( time() > 0x7fffffff ) {
286 return $this->getDB()->timestamp( 1 << 62 );
287 } else {
288 return $this->getDB()->timestamp( 0x7fffffff );
289 }
290 }
291
292 protected function garbageCollect() {
293 if ( !$this->purgePeriod ) {
294 // Disabled
295 return;
296 }
297 // Only purge on one in every $this->purgePeriod requests.
298 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
299 return;
300 }
301 $now = time();
302 // Avoid repeating the delete within a few seconds
303 if ( $now > ( $this->lastExpireAll + 1 ) ) {
304 $this->lastExpireAll = $now;
305 $this->expireAll();
306 }
307 }
308
309 public function expireAll() {
310 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
311 }
312
313 /**
314 * Delete objects from the database which expire before a certain date.
315 * @return bool
316 */
317 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
318 $db = $this->getDB();
319 $dbTimestamp = $db->timestamp( $timestamp );
320 $totalSeconds = false;
321 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
322
323 try {
324 for ( $i = 0; $i < $this->shards; $i++ ) {
325 $maxExpTime = false;
326 while ( true ) {
327 $conds = $baseConds;
328 if ( $maxExpTime !== false ) {
329 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
330 }
331 $rows = $db->select(
332 $this->getTableByShard( $i ),
333 array( 'keyname', 'exptime' ),
334 $conds,
335 __METHOD__,
336 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
337 if ( !$rows->numRows() ) {
338 break;
339 }
340 $keys = array();
341 $row = $rows->current();
342 $minExpTime = $row->exptime;
343 if ( $totalSeconds === false ) {
344 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
345 - wfTimestamp( TS_UNIX, $minExpTime );
346 }
347 foreach ( $rows as $row ) {
348 $keys[] = $row->keyname;
349 $maxExpTime = $row->exptime;
350 }
351
352 $db->begin( __METHOD__ );
353 $db->delete(
354 $this->getTableByShard( $i ),
355 array(
356 'exptime >= ' . $db->addQuotes( $minExpTime ),
357 'exptime < ' . $db->addQuotes( $dbTimestamp ),
358 'keyname' => $keys
359 ),
360 __METHOD__ );
361 $db->commit( __METHOD__ );
362
363 if ( $progressCallback ) {
364 if ( intval( $totalSeconds ) === 0 ) {
365 $percent = 0;
366 } else {
367 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
368 - wfTimestamp( TS_UNIX, $maxExpTime );
369 if ( $remainingSeconds > $totalSeconds ) {
370 $totalSeconds = $remainingSeconds;
371 }
372 $percent = ( $i + $remainingSeconds / $totalSeconds )
373 / $this->shards * 100;
374 }
375 call_user_func( $progressCallback, $percent );
376 }
377 }
378 }
379 } catch ( DBQueryError $e ) {
380 $this->handleWriteError( $e );
381 }
382 return true;
383 }
384
385 public function deleteAll() {
386 $db = $this->getDB();
387
388 try {
389 for ( $i = 0; $i < $this->shards; $i++ ) {
390 $db->begin( __METHOD__ );
391 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__ );
392 $db->commit( __METHOD__ );
393 }
394 } catch ( DBQueryError $e ) {
395 $this->handleWriteError( $e );
396 }
397 }
398
399 /**
400 * Serialize an object and, if possible, compress the representation.
401 * On typical message and page data, this can provide a 3X decrease
402 * in storage requirements.
403 *
404 * @param $data mixed
405 * @return string
406 */
407 protected function serialize( &$data ) {
408 $serial = serialize( $data );
409
410 if ( function_exists( 'gzdeflate' ) ) {
411 return gzdeflate( $serial );
412 } else {
413 return $serial;
414 }
415 }
416
417 /**
418 * Unserialize and, if necessary, decompress an object.
419 * @param $serial string
420 * @return mixed
421 */
422 protected function unserialize( $serial ) {
423 if ( function_exists( 'gzinflate' ) ) {
424 wfSuppressWarnings();
425 $decomp = gzinflate( $serial );
426 wfRestoreWarnings();
427
428 if ( false !== $decomp ) {
429 $serial = $decomp;
430 }
431 }
432
433 $ret = unserialize( $serial );
434
435 return $ret;
436 }
437
438 /**
439 * Handle a DBQueryError which occurred during a write operation.
440 * Ignore errors which are due to a read-only database, rethrow others.
441 */
442 protected function handleWriteError( $exception ) {
443 $db = $this->getDB();
444
445 if ( !$db->wasReadOnlyError() ) {
446 throw $exception;
447 }
448
449 try {
450 $db->rollback( __METHOD__ );
451 } catch ( DBQueryError $e ) {
452 }
453
454 wfDebug( __METHOD__ . ": ignoring query error\n" );
455 $db->ignoreErrors( false );
456 }
457
458 /**
459 * Create shard tables. For use from eval.php.
460 */
461 public function createTables() {
462 $db = $this->getDB();
463 if ( $db->getType() !== 'mysql'
464 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
465 {
466 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
467 }
468
469 for ( $i = 0; $i < $this->shards; $i++ ) {
470 $db->begin( __METHOD__ );
471 $db->query(
472 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
473 ' LIKE ' . $db->tableName( 'objectcache' ),
474 __METHOD__ );
475 $db->commit( __METHOD__ );
476 }
477 }
478 }
479
480 /**
481 * Backwards compatibility alias
482 */
483 class MediaWikiBagOStuff extends SqlBagOStuff { }
484