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