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