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