Merge "(Bug 42616) Remove extra newline from redirect wikitext"
[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 * @var LoadBalancer
32 */
33 var $lb;
34
35 /**
36 * @var DatabaseBase
37 */
38 var $db;
39 var $serverInfo;
40 var $lastExpireAll = 0;
41 var $purgePeriod = 100;
42 var $shards = 1;
43 var $tableName = 'objectcache';
44
45 protected $connFailureTime = 0; // UNIX timestamp
46 protected $connFailureError; // exception
47
48 /**
49 * Constructor. Parameters are:
50 * - server: A server info structure in the format required by each
51 * element in $wgDBServers.
52 *
53 * - purgePeriod: The average number of object cache requests in between
54 * garbage collection operations, where expired entries
55 * are removed from the database. Or in other words, the
56 * reciprocal of the probability of purging on any given
57 * request. If this is set to zero, purging will never be
58 * done.
59 *
60 * - tableName: The table name to use, default is "objectcache".
61 *
62 * - shards: The number of tables to use for data storage. If this is
63 * more than 1, table names will be formed in the style
64 * objectcacheNNN where NNN is the shard index, between 0 and
65 * shards-1. The number of digits will be the minimum number
66 * required to hold the largest shard index. Data will be
67 * distributed across all tables by key hash. This is for
68 * MySQL bugs 61735 and 61736.
69 *
70 * @param $params array
71 */
72 public function __construct( $params ) {
73 if ( isset( $params['server'] ) ) {
74 $this->serverInfo = $params['server'];
75 $this->serverInfo['load'] = 1;
76 }
77 if ( isset( $params['purgePeriod'] ) ) {
78 $this->purgePeriod = intval( $params['purgePeriod'] );
79 }
80 if ( isset( $params['tableName'] ) ) {
81 $this->tableName = $params['tableName'];
82 }
83 if ( isset( $params['shards'] ) ) {
84 $this->shards = intval( $params['shards'] );
85 }
86 }
87
88 /**
89 * @throws
90 * @return DatabaseBase
91 */
92 protected function getDB() {
93 global $wgDebugDBTransactions;
94
95 # Don't keep timing out trying to connect for each call if the DB is down
96 if ( $this->connFailureError && ( time() - $this->connFailureTime ) < 60 ) {
97 throw $this->connFailureError;
98 }
99
100 if ( !isset( $this->db ) ) {
101 # If server connection info was given, use that
102 if ( $this->serverInfo ) {
103 if ( $wgDebugDBTransactions ) {
104 wfDebug( sprintf( "Using provided serverInfo for SqlBagOStuff\n" ) );
105 }
106 $this->lb = new LoadBalancer( array(
107 'servers' => array( $this->serverInfo ) ) );
108 $this->db = $this->lb->getConnection( DB_MASTER );
109 $this->db->clearFlag( DBO_TRX );
110 } else {
111 /*
112 * We must keep a separate connection to MySQL in order to avoid deadlocks
113 * However, SQLite has an opposite behaviour. And PostgreSQL needs to know
114 * if we are in transaction or no
115 */
116 if ( wfGetDB( DB_MASTER )->getType() == 'mysql' ) {
117 $this->lb = wfGetLBFactory()->newMainLB();
118 $this->db = $this->lb->getConnection( DB_MASTER );
119 $this->db->clearFlag( DBO_TRX ); // auto-commit mode
120 } else {
121 $this->db = wfGetDB( DB_MASTER );
122 }
123 }
124 if ( $wgDebugDBTransactions ) {
125 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $this->db ) );
126 }
127 }
128
129 return $this->db;
130 }
131
132 /**
133 * Get the table name for a given key
134 * @param $key string
135 * @return string
136 */
137 protected function getTableByKey( $key ) {
138 if ( $this->shards > 1 ) {
139 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
140 return $this->getTableByShard( $hash % $this->shards );
141 } else {
142 return $this->tableName;
143 }
144 }
145
146 /**
147 * Get the table name for a given shard index
148 * @param $index int
149 * @return string
150 */
151 protected function getTableByShard( $index ) {
152 if ( $this->shards > 1 ) {
153 $decimals = strlen( $this->shards - 1 );
154 return $this->tableName .
155 sprintf( "%0{$decimals}d", $index );
156 } else {
157 return $this->tableName;
158 }
159 }
160
161 /**
162 * @param $key string
163 * @return mixed
164 */
165 public function get( $key ) {
166 $values = $this->getMulti( array( $key ) );
167 return array_key_exists( $key, $values ) ? $values[$key] : false;
168 }
169
170 /**
171 * @param $keys array
172 * @return Array
173 */
174 public function getMulti( array $keys ) {
175 $values = array(); // array of (key => value)
176
177 try {
178 $db = $this->getDB();
179 $keysByTableName = array();
180 foreach ( $keys as $key ) {
181 $tableName = $this->getTableByKey( $key );
182 if ( !isset( $keysByTableName[$tableName] ) ) {
183 $keysByTableName[$tableName] = array();
184 }
185 $keysByTableName[$tableName][] = $key;
186 }
187
188 $this->garbageCollect(); // expire old entries if any
189
190 $dataRows = array();
191 foreach ( $keysByTableName as $tableName => $tableKeys ) {
192 $res = $db->select( $tableName,
193 array( 'keyname', 'value', 'exptime' ),
194 array( 'keyname' => $tableKeys ),
195 __METHOD__ );
196 foreach ( $res as $row ) {
197 $dataRows[$row->keyname] = $row;
198 }
199 }
200
201 foreach ( $keys as $key ) {
202 if ( isset( $dataRows[$key] ) ) { // HIT?
203 $row = $dataRows[$key];
204 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
205 if ( $this->isExpired( $row->exptime ) ) { // MISS
206 $this->debug( "get: key has expired, deleting" );
207 try {
208 $db->begin( __METHOD__ );
209 # Put the expiry time in the WHERE condition to avoid deleting a
210 # newly-inserted value
211 $db->delete( $this->getTableByKey( $key ),
212 array( 'keyname' => $key, 'exptime' => $row->exptime ),
213 __METHOD__ );
214 $db->commit( __METHOD__ );
215 } catch ( DBQueryError $e ) {
216 $this->handleWriteError( $e );
217 }
218 $values[$key] = false;
219 } else { // HIT
220 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
221 }
222 } else { // MISS
223 $values[$key] = false;
224 $this->debug( 'get: no matching rows' );
225 }
226 }
227 } catch ( DBError $e ) {
228 $this->handleReadError( $e );
229 };
230
231 return $values;
232 }
233
234 /**
235 * @param $key string
236 * @param $value mixed
237 * @param $exptime int
238 * @return bool
239 */
240 public function set( $key, $value, $exptime = 0 ) {
241 try {
242 $db = $this->getDB();
243 $exptime = intval( $exptime );
244
245 if ( $exptime < 0 ) {
246 $exptime = 0;
247 }
248
249 if ( $exptime == 0 ) {
250 $encExpiry = $this->getMaxDateTime();
251 } else {
252 if ( $exptime < 3.16e8 ) { # ~10 years
253 $exptime += time();
254 }
255
256 $encExpiry = $db->timestamp( $exptime );
257 }
258 $db->begin( __METHOD__ );
259 // (bug 24425) use a replace if the db supports it instead of
260 // delete/insert to avoid clashes with conflicting keynames
261 $db->replace(
262 $this->getTableByKey( $key ),
263 array( 'keyname' ),
264 array(
265 'keyname' => $key,
266 'value' => $db->encodeBlob( $this->serialize( $value ) ),
267 'exptime' => $encExpiry
268 ), __METHOD__ );
269 $db->commit( __METHOD__ );
270 } catch ( DBError $e ) {
271 $this->handleWriteError( $e );
272 return false;
273 }
274
275 return true;
276 }
277
278 /**
279 * @param $key string
280 * @param $time int
281 * @return bool
282 */
283 public function delete( $key, $time = 0 ) {
284 try {
285 $db = $this->getDB();
286 $db->begin( __METHOD__ );
287 $db->delete(
288 $this->getTableByKey( $key ),
289 array( 'keyname' => $key ),
290 __METHOD__ );
291 $db->commit( __METHOD__ );
292 } catch ( DBError $e ) {
293 $this->handleWriteError( $e );
294 return false;
295 }
296
297 return true;
298 }
299
300 /**
301 * @param $key string
302 * @param $step int
303 * @return int|null
304 */
305 public function incr( $key, $step = 1 ) {
306 try {
307 $db = $this->getDB();
308 $tableName = $this->getTableByKey( $key );
309 $step = intval( $step );
310 $db->begin( __METHOD__ );
311 $row = $db->selectRow(
312 $tableName,
313 array( 'value', 'exptime' ),
314 array( 'keyname' => $key ),
315 __METHOD__,
316 array( 'FOR UPDATE' ) );
317 if ( $row === false ) {
318 // Missing
319 $db->commit( __METHOD__ );
320
321 return null;
322 }
323 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
324 if ( $this->isExpired( $row->exptime ) ) {
325 // Expired, do not reinsert
326 $db->commit( __METHOD__ );
327
328 return null;
329 }
330
331 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
332 $newValue = $oldValue + $step;
333 $db->insert( $tableName,
334 array(
335 'keyname' => $key,
336 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
337 'exptime' => $row->exptime
338 ), __METHOD__, 'IGNORE' );
339
340 if ( $db->affectedRows() == 0 ) {
341 // Race condition. See bug 28611
342 $newValue = null;
343 }
344 $db->commit( __METHOD__ );
345 } catch ( DBError $e ) {
346 $this->handleWriteError( $e );
347 return null;
348 }
349
350 return $newValue;
351 }
352
353 /**
354 * @return Array
355 */
356 public function keys() {
357 $result = array();
358
359 try {
360 $db = $this->getDB();
361 for ( $i = 0; $i < $this->shards; $i++ ) {
362 $res = $db->select( $this->getTableByShard( $i ),
363 array( 'keyname' ), false, __METHOD__ );
364 foreach ( $res as $row ) {
365 $result[] = $row->keyname;
366 }
367 }
368 } catch ( DBError $e ) {
369 $this->handleReadError( $e );
370 }
371
372 return $result;
373 }
374
375 /**
376 * @param $exptime string
377 * @return bool
378 */
379 protected function isExpired( $exptime ) {
380 return $exptime != $this->getMaxDateTime() && wfTimestamp( TS_UNIX, $exptime ) < time();
381 }
382
383 /**
384 * @return string
385 */
386 protected function getMaxDateTime() {
387 if ( time() > 0x7fffffff ) {
388 return $this->getDB()->timestamp( 1 << 62 );
389 } else {
390 return $this->getDB()->timestamp( 0x7fffffff );
391 }
392 }
393
394 protected function garbageCollect() {
395 if ( !$this->purgePeriod ) {
396 // Disabled
397 return;
398 }
399 // Only purge on one in every $this->purgePeriod requests.
400 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
401 return;
402 }
403 $now = time();
404 // Avoid repeating the delete within a few seconds
405 if ( $now > ( $this->lastExpireAll + 1 ) ) {
406 $this->lastExpireAll = $now;
407 $this->expireAll();
408 }
409 }
410
411 public function expireAll() {
412 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
413 }
414
415 /**
416 * Delete objects from the database which expire before a certain date.
417 * @param $timestamp string
418 * @param $progressCallback bool|callback
419 * @return bool
420 */
421 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
422 try {
423 $db = $this->getDB();
424 $dbTimestamp = $db->timestamp( $timestamp );
425 $totalSeconds = false;
426 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
427 for ( $i = 0; $i < $this->shards; $i++ ) {
428 $maxExpTime = false;
429 while ( true ) {
430 $conds = $baseConds;
431 if ( $maxExpTime !== false ) {
432 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
433 }
434 $rows = $db->select(
435 $this->getTableByShard( $i ),
436 array( 'keyname', 'exptime' ),
437 $conds,
438 __METHOD__,
439 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
440 if ( !$rows->numRows() ) {
441 break;
442 }
443 $keys = array();
444 $row = $rows->current();
445 $minExpTime = $row->exptime;
446 if ( $totalSeconds === false ) {
447 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
448 - wfTimestamp( TS_UNIX, $minExpTime );
449 }
450 foreach ( $rows as $row ) {
451 $keys[] = $row->keyname;
452 $maxExpTime = $row->exptime;
453 }
454
455 $db->begin( __METHOD__ );
456 $db->delete(
457 $this->getTableByShard( $i ),
458 array(
459 'exptime >= ' . $db->addQuotes( $minExpTime ),
460 'exptime < ' . $db->addQuotes( $dbTimestamp ),
461 'keyname' => $keys
462 ),
463 __METHOD__ );
464 $db->commit( __METHOD__ );
465
466 if ( $progressCallback ) {
467 if ( intval( $totalSeconds ) === 0 ) {
468 $percent = 0;
469 } else {
470 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
471 - wfTimestamp( TS_UNIX, $maxExpTime );
472 if ( $remainingSeconds > $totalSeconds ) {
473 $totalSeconds = $remainingSeconds;
474 }
475 $percent = ( $i + $remainingSeconds / $totalSeconds )
476 / $this->shards * 100;
477 }
478 call_user_func( $progressCallback, $percent );
479 }
480 }
481 }
482 } catch ( DBError $e ) {
483 $this->handleWriteError( $e );
484 return false;
485 }
486
487 return true;
488 }
489
490 public function deleteAll() {
491 try {
492 $db = $this->getDB();
493 for ( $i = 0; $i < $this->shards; $i++ ) {
494 $db->begin( __METHOD__ );
495 $db->delete( $this->getTableByShard( $i ), '*', __METHOD__ );
496 $db->commit( __METHOD__ );
497 }
498 } catch ( DBError $e ) {
499 $this->handleWriteError( $e );
500 return false;
501 }
502
503 return true;
504 }
505
506 /**
507 * Serialize an object and, if possible, compress the representation.
508 * On typical message and page data, this can provide a 3X decrease
509 * in storage requirements.
510 *
511 * @param $data mixed
512 * @return string
513 */
514 protected function serialize( &$data ) {
515 $serial = serialize( $data );
516
517 if ( function_exists( 'gzdeflate' ) ) {
518 return gzdeflate( $serial );
519 } else {
520 return $serial;
521 }
522 }
523
524 /**
525 * Unserialize and, if necessary, decompress an object.
526 * @param $serial string
527 * @return mixed
528 */
529 protected function unserialize( $serial ) {
530 if ( function_exists( 'gzinflate' ) ) {
531 wfSuppressWarnings();
532 $decomp = gzinflate( $serial );
533 wfRestoreWarnings();
534
535 if ( false !== $decomp ) {
536 $serial = $decomp;
537 }
538 }
539
540 $ret = unserialize( $serial );
541
542 return $ret;
543 }
544
545 /**
546 * Handle a DBError which occurred during a read operation.
547 */
548 protected function handleReadError( DBError $exception ) {
549 if ( $exception instanceof DBConnectionError ) {
550 $this->connFailureTime = time();
551 $this->connFailureError = $exception;
552 }
553 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
554 if ( $this->db ) {
555 wfDebug( __METHOD__ . ": ignoring query error\n" );
556 } else {
557 wfDebug( __METHOD__ . ": ignoring connection error\n" );
558 }
559 }
560
561 /**
562 * Handle a DBQueryError which occurred during a write operation.
563 */
564 protected function handleWriteError( DBError $exception ) {
565 if ( $exception instanceof DBConnectionError ) {
566 $this->connFailureTime = time();
567 $this->connFailureError = $exception;
568 }
569 if ( $this->db && $this->db->wasReadOnlyError() ) {
570 try {
571 $this->db->rollback( __METHOD__ );
572 } catch ( DBError $e ) {}
573 }
574 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
575 if ( $this->db ) {
576 wfDebug( __METHOD__ . ": ignoring query error\n" );
577 } else {
578 wfDebug( __METHOD__ . ": ignoring connection error\n" );
579 }
580 }
581
582 /**
583 * Create shard tables. For use from eval.php.
584 */
585 public function createTables() {
586 $db = $this->getDB();
587 if ( $db->getType() !== 'mysql'
588 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
589 {
590 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
591 }
592
593 for ( $i = 0; $i < $this->shards; $i++ ) {
594 $db->begin( __METHOD__ );
595 $db->query(
596 'CREATE TABLE ' . $db->tableName( $this->getTableByShard( $i ) ) .
597 ' LIKE ' . $db->tableName( 'objectcache' ),
598 __METHOD__ );
599 $db->commit( __METHOD__ );
600 }
601 }
602 }
603
604 /**
605 * Backwards compatibility alias
606 */
607 class MediaWikiBagOStuff extends SqlBagOStuff { }
608