Don't bother showing prev/next links navigation when there's few results
[mediawiki.git] / includes / objectcache / SqlBagOStuff.php
blobe6a8c45ed954974ee6cf02bf036f898bff79cd19
1 <?php
2 /**
3 * Object caching using a SQL database.
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.
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.
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
20 * @file
21 * @ingroup Cache
24 /**
25 * Class to store objects in the database
27 * @ingroup Cache
29 class SqlBagOStuff extends BagOStuff {
30 /**
31 * @var LoadBalancer
33 var $lb;
35 var $serverInfos;
36 var $serverNames;
37 var $numServers;
38 var $conns;
39 var $lastExpireAll = 0;
40 var $purgePeriod = 100;
41 var $shards = 1;
42 var $tableName = 'objectcache';
44 protected $connFailureTimes = array(); // UNIX timestamps
45 protected $connFailureErrors = array(); // exceptions
47 /**
48 * Constructor. Parameters are:
49 * - server: A server info structure in the format required by each
50 * element in $wgDBServers.
52 * - servers: An array of server info structures describing a set of
53 * database servers to distribute keys to. If this is
54 * specified, the "server" option will be ignored.
56 * - purgePeriod: The average number of object cache requests in between
57 * garbage collection operations, where expired entries
58 * are removed from the database. Or in other words, the
59 * reciprocal of the probability of purging on any given
60 * request. If this is set to zero, purging will never be
61 * done.
63 * - tableName: The table name to use, default is "objectcache".
65 * - shards: The number of tables to use for data storage on each server.
66 * If this is more than 1, table names will be formed in the style
67 * objectcacheNNN where NNN is the shard index, between 0 and
68 * shards-1. The number of digits will be the minimum number
69 * required to hold the largest shard index. Data will be
70 * distributed across all tables by key hash. This is for
71 * MySQL bugs 61735 and 61736.
73 * @param array $params
75 public function __construct( $params ) {
76 if ( isset( $params['servers'] ) ) {
77 $this->serverInfos = $params['servers'];
78 $this->numServers = count( $this->serverInfos );
79 $this->serverNames = array();
80 foreach ( $this->serverInfos as $i => $info ) {
81 $this->serverNames[$i] = isset( $info['host'] ) ? $info['host'] : "#$i";
83 } elseif ( isset( $params['server'] ) ) {
84 $this->serverInfos = array( $params['server'] );
85 $this->numServers = count( $this->serverInfos );
86 } else {
87 $this->serverInfos = false;
88 $this->numServers = 1;
90 if ( isset( $params['purgePeriod'] ) ) {
91 $this->purgePeriod = intval( $params['purgePeriod'] );
93 if ( isset( $params['tableName'] ) ) {
94 $this->tableName = $params['tableName'];
96 if ( isset( $params['shards'] ) ) {
97 $this->shards = intval( $params['shards'] );
102 * Get a connection to the specified database
104 * @param int $serverIndex
105 * @return DatabaseBase
107 protected function getDB( $serverIndex ) {
108 global $wgDebugDBTransactions;
110 if ( !isset( $this->conns[$serverIndex] ) ) {
111 if ( $serverIndex >= $this->numServers ) {
112 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
115 # Don't keep timing out trying to connect for each call if the DB is down
116 if ( isset( $this->connFailureErrors[$serverIndex] )
117 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
119 throw $this->connFailureErrors[$serverIndex];
122 # If server connection info was given, use that
123 if ( $this->serverInfos ) {
124 if ( $wgDebugDBTransactions ) {
125 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
127 $info = $this->serverInfos[$serverIndex];
128 $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
129 $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
130 wfDebug( __CLASS__ . ": connecting to $host\n" );
131 $db = DatabaseBase::factory( $type, $info );
132 $db->clearFlag( DBO_TRX );
133 } else {
135 * We must keep a separate connection to MySQL in order to avoid deadlocks
136 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
137 * if we are in transaction or no
139 if ( wfGetDB( DB_MASTER )->getType() == 'mysql' ) {
140 $this->lb = wfGetLBFactory()->newMainLB();
141 $db = $this->lb->getConnection( DB_MASTER );
142 $db->clearFlag( DBO_TRX ); // auto-commit mode
143 } else {
144 $db = wfGetDB( DB_MASTER );
147 if ( $wgDebugDBTransactions ) {
148 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
150 $this->conns[$serverIndex] = $db;
153 return $this->conns[$serverIndex];
157 * Get the server index and table name for a given key
158 * @param string $key
159 * @return array Server index and table name
161 protected function getTableByKey( $key ) {
162 if ( $this->shards > 1 ) {
163 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
164 $tableIndex = $hash % $this->shards;
165 } else {
166 $tableIndex = 0;
168 if ( $this->numServers > 1 ) {
169 $sortedServers = $this->serverNames;
170 ArrayUtils::consistentHashSort( $sortedServers, $key );
171 reset( $sortedServers );
172 $serverIndex = key( $sortedServers );
173 } else {
174 $serverIndex = 0;
176 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
180 * Get the table name for a given shard index
181 * @param int $index
182 * @return string
184 protected function getTableNameByShard( $index ) {
185 if ( $this->shards > 1 ) {
186 $decimals = strlen( $this->shards - 1 );
187 return $this->tableName .
188 sprintf( "%0{$decimals}d", $index );
189 } else {
190 return $this->tableName;
195 * @param string $key
196 * @param mixed $casToken [optional]
197 * @return mixed
199 public function get( $key, &$casToken = null ) {
200 $values = $this->getMulti( array( $key ) );
201 if ( array_key_exists( $key, $values ) ) {
202 $casToken = $values[$key];
203 return $values[$key];
205 return false;
209 * @param array $keys
210 * @return array
212 public function getMulti( array $keys ) {
213 $values = array(); // array of (key => value)
215 $keysByTable = array();
216 foreach ( $keys as $key ) {
217 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
218 $keysByTable[$serverIndex][$tableName][] = $key;
221 $this->garbageCollect(); // expire old entries if any
223 $dataRows = array();
224 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
225 try {
226 $db = $this->getDB( $serverIndex );
227 foreach ( $serverKeys as $tableName => $tableKeys ) {
228 $res = $db->select( $tableName,
229 array( 'keyname', 'value', 'exptime' ),
230 array( 'keyname' => $tableKeys ),
231 __METHOD__ );
232 foreach ( $res as $row ) {
233 $row->serverIndex = $serverIndex;
234 $row->tableName = $tableName;
235 $dataRows[$row->keyname] = $row;
238 } catch ( DBError $e ) {
239 $this->handleReadError( $e, $serverIndex );
243 foreach ( $keys as $key ) {
244 if ( isset( $dataRows[$key] ) ) { // HIT?
245 $row = $dataRows[$key];
246 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
247 try {
248 $db = $this->getDB( $row->serverIndex );
249 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
250 $this->debug( "get: key has expired, deleting" );
251 $db->commit( __METHOD__, 'flush' );
252 # Put the expiry time in the WHERE condition to avoid deleting a
253 # newly-inserted value
254 $db->delete( $row->tableName,
255 array( 'keyname' => $key, 'exptime' => $row->exptime ),
256 __METHOD__ );
257 $db->commit( __METHOD__, 'flush' );
258 $values[$key] = false;
259 } else { // HIT
260 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
262 } catch ( DBQueryError $e ) {
263 $this->handleWriteError( $e, $row->serverIndex );
265 } else { // MISS
266 $values[$key] = false;
267 $this->debug( 'get: no matching rows' );
271 return $values;
275 * @param array $data
276 * @param int $expiry
277 * @return bool
279 public function setMulti( array $data, $expiry = 0 ) {
280 $keysByTable = array();
281 foreach ( $data as $key => $value ) {
282 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
283 $keysByTable[$serverIndex][$tableName][] = $key;
286 $this->garbageCollect(); // expire old entries if any
288 $result = true;
289 $exptime = (int)$expiry;
290 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
291 try {
292 $db = $this->getDB( $serverIndex );
293 } catch ( DBError $e ) {
294 $this->handleWriteError( $e, $serverIndex );
295 $result = false;
296 continue;
299 if ( $exptime < 0 ) {
300 $exptime = 0;
303 if ( $exptime == 0 ) {
304 $encExpiry = $this->getMaxDateTime( $db );
305 } else {
306 if ( $exptime < 3.16e8 ) { # ~10 years
307 $exptime += time();
309 $encExpiry = $db->timestamp( $exptime );
311 foreach ( $serverKeys as $tableName => $tableKeys ) {
312 $rows = array();
313 foreach ( $tableKeys as $key ) {
314 $rows[] = array(
315 'keyname' => $key,
316 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
317 'exptime' => $encExpiry,
321 try {
322 $db->commit( __METHOD__, 'flush' );
323 $db->replace(
324 $tableName,
325 array( 'keyname' ),
326 $rows,
327 __METHOD__
329 $db->commit( __METHOD__, 'flush' );
330 } catch ( DBError $e ) {
331 $this->handleWriteError( $e, $serverIndex );
332 $result = false;
339 return $result;
345 * @param string $key
346 * @param mixed $value
347 * @param int $exptime
348 * @return bool
350 public function set( $key, $value, $exptime = 0 ) {
351 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
352 try {
353 $db = $this->getDB( $serverIndex );
354 $exptime = intval( $exptime );
356 if ( $exptime < 0 ) {
357 $exptime = 0;
360 if ( $exptime == 0 ) {
361 $encExpiry = $this->getMaxDateTime( $db );
362 } else {
363 if ( $exptime < 3.16e8 ) { # ~10 years
364 $exptime += time();
367 $encExpiry = $db->timestamp( $exptime );
369 $db->commit( __METHOD__, 'flush' );
370 // (bug 24425) use a replace if the db supports it instead of
371 // delete/insert to avoid clashes with conflicting keynames
372 $db->replace(
373 $tableName,
374 array( 'keyname' ),
375 array(
376 'keyname' => $key,
377 'value' => $db->encodeBlob( $this->serialize( $value ) ),
378 'exptime' => $encExpiry
379 ), __METHOD__ );
380 $db->commit( __METHOD__, 'flush' );
381 } catch ( DBError $e ) {
382 $this->handleWriteError( $e, $serverIndex );
383 return false;
386 return true;
390 * @param mixed $casToken
391 * @param string $key
392 * @param mixed $value
393 * @param int $exptime
394 * @return bool
396 public function cas( $casToken, $key, $value, $exptime = 0 ) {
397 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
398 try {
399 $db = $this->getDB( $serverIndex );
400 $exptime = intval( $exptime );
402 if ( $exptime < 0 ) {
403 $exptime = 0;
406 if ( $exptime == 0 ) {
407 $encExpiry = $this->getMaxDateTime( $db );
408 } else {
409 if ( $exptime < 3.16e8 ) { # ~10 years
410 $exptime += time();
412 $encExpiry = $db->timestamp( $exptime );
414 $db->commit( __METHOD__, 'flush' );
415 // (bug 24425) use a replace if the db supports it instead of
416 // delete/insert to avoid clashes with conflicting keynames
417 $db->update(
418 $tableName,
419 array(
420 'keyname' => $key,
421 'value' => $db->encodeBlob( $this->serialize( $value ) ),
422 'exptime' => $encExpiry
424 array(
425 'keyname' => $key,
426 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
428 __METHOD__
430 $db->commit( __METHOD__, 'flush' );
431 } catch ( DBQueryError $e ) {
432 $this->handleWriteError( $e, $serverIndex );
434 return false;
437 return (bool)$db->affectedRows();
441 * @param string $key
442 * @param int $time
443 * @return bool
445 public function delete( $key, $time = 0 ) {
446 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
447 try {
448 $db = $this->getDB( $serverIndex );
449 $db->commit( __METHOD__, 'flush' );
450 $db->delete(
451 $tableName,
452 array( 'keyname' => $key ),
453 __METHOD__ );
454 $db->commit( __METHOD__, 'flush' );
455 } catch ( DBError $e ) {
456 $this->handleWriteError( $e, $serverIndex );
457 return false;
460 return true;
464 * @param string $key
465 * @param int $step
466 * @return int|null
468 public function incr( $key, $step = 1 ) {
469 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
470 try {
471 $db = $this->getDB( $serverIndex );
472 $step = intval( $step );
473 $db->commit( __METHOD__, 'flush' );
474 $row = $db->selectRow(
475 $tableName,
476 array( 'value', 'exptime' ),
477 array( 'keyname' => $key ),
478 __METHOD__,
479 array( 'FOR UPDATE' ) );
480 if ( $row === false ) {
481 // Missing
482 $db->commit( __METHOD__, 'flush' );
484 return null;
486 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
487 if ( $this->isExpired( $db, $row->exptime ) ) {
488 // Expired, do not reinsert
489 $db->commit( __METHOD__, 'flush' );
491 return null;
494 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
495 $newValue = $oldValue + $step;
496 $db->insert( $tableName,
497 array(
498 'keyname' => $key,
499 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
500 'exptime' => $row->exptime
501 ), __METHOD__, 'IGNORE' );
503 if ( $db->affectedRows() == 0 ) {
504 // Race condition. See bug 28611
505 $newValue = null;
507 $db->commit( __METHOD__, 'flush' );
508 } catch ( DBError $e ) {
509 $this->handleWriteError( $e, $serverIndex );
510 return null;
513 return $newValue;
517 * @param string $exptime
518 * @return bool
520 protected function isExpired( $db, $exptime ) {
521 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
525 * @param DatabaseBase $db
526 * @return string
528 protected function getMaxDateTime( $db ) {
529 if ( time() > 0x7fffffff ) {
530 return $db->timestamp( 1 << 62 );
531 } else {
532 return $db->timestamp( 0x7fffffff );
536 protected function garbageCollect() {
537 if ( !$this->purgePeriod ) {
538 // Disabled
539 return;
541 // Only purge on one in every $this->purgePeriod requests.
542 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
543 return;
545 $now = time();
546 // Avoid repeating the delete within a few seconds
547 if ( $now > ( $this->lastExpireAll + 1 ) ) {
548 $this->lastExpireAll = $now;
549 $this->expireAll();
553 public function expireAll() {
554 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
558 * Delete objects from the database which expire before a certain date.
559 * @param string $timestamp
560 * @param bool|callable $progressCallback
561 * @return bool
563 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
564 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
565 try {
566 $db = $this->getDB( $serverIndex );
567 $dbTimestamp = $db->timestamp( $timestamp );
568 $totalSeconds = false;
569 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
570 for ( $i = 0; $i < $this->shards; $i++ ) {
571 $maxExpTime = false;
572 while ( true ) {
573 $conds = $baseConds;
574 if ( $maxExpTime !== false ) {
575 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
577 $rows = $db->select(
578 $this->getTableNameByShard( $i ),
579 array( 'keyname', 'exptime' ),
580 $conds,
581 __METHOD__,
582 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
583 if ( !$rows->numRows() ) {
584 break;
586 $keys = array();
587 $row = $rows->current();
588 $minExpTime = $row->exptime;
589 if ( $totalSeconds === false ) {
590 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
591 - wfTimestamp( TS_UNIX, $minExpTime );
593 foreach ( $rows as $row ) {
594 $keys[] = $row->keyname;
595 $maxExpTime = $row->exptime;
598 $db->commit( __METHOD__, 'flush' );
599 $db->delete(
600 $this->getTableNameByShard( $i ),
601 array(
602 'exptime >= ' . $db->addQuotes( $minExpTime ),
603 'exptime < ' . $db->addQuotes( $dbTimestamp ),
604 'keyname' => $keys
606 __METHOD__ );
607 $db->commit( __METHOD__, 'flush' );
609 if ( $progressCallback ) {
610 if ( intval( $totalSeconds ) === 0 ) {
611 $percent = 0;
612 } else {
613 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
614 - wfTimestamp( TS_UNIX, $maxExpTime );
615 if ( $remainingSeconds > $totalSeconds ) {
616 $totalSeconds = $remainingSeconds;
618 $percent = ( $i + $remainingSeconds / $totalSeconds )
619 / $this->shards * 100;
621 $percent = ( $percent / $this->numServers )
622 + ( $serverIndex / $this->numServers * 100 );
623 call_user_func( $progressCallback, $percent );
627 } catch ( DBError $e ) {
628 $this->handleWriteError( $e, $serverIndex );
629 return false;
632 return true;
635 public function deleteAll() {
636 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
637 try {
638 $db = $this->getDB( $serverIndex );
639 for ( $i = 0; $i < $this->shards; $i++ ) {
640 $db->commit( __METHOD__, 'flush' );
641 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
642 $db->commit( __METHOD__, 'flush' );
644 } catch ( DBError $e ) {
645 $this->handleWriteError( $e, $serverIndex );
646 return false;
649 return true;
653 * Serialize an object and, if possible, compress the representation.
654 * On typical message and page data, this can provide a 3X decrease
655 * in storage requirements.
657 * @param mixed $data
658 * @return string
660 protected function serialize( &$data ) {
661 $serial = serialize( $data );
663 if ( function_exists( 'gzdeflate' ) ) {
664 return gzdeflate( $serial );
665 } else {
666 return $serial;
671 * Unserialize and, if necessary, decompress an object.
672 * @param string $serial
673 * @return mixed
675 protected function unserialize( $serial ) {
676 if ( function_exists( 'gzinflate' ) ) {
677 wfSuppressWarnings();
678 $decomp = gzinflate( $serial );
679 wfRestoreWarnings();
681 if ( false !== $decomp ) {
682 $serial = $decomp;
686 $ret = unserialize( $serial );
688 return $ret;
692 * Handle a DBError which occurred during a read operation.
694 * @param DBError $exception
695 * @param int $serverIndex
697 protected function handleReadError( DBError $exception, $serverIndex ) {
698 if ( $exception instanceof DBConnectionError ) {
699 $this->markServerDown( $exception, $serverIndex );
701 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
702 if ( $exception instanceof DBConnectionError ) {
703 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
704 wfDebug( __METHOD__ . ": ignoring connection error\n" );
705 } else {
706 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
707 wfDebug( __METHOD__ . ": ignoring query error\n" );
712 * Handle a DBQueryError which occurred during a write operation.
714 * @param DBError $exception
715 * @param int $serverIndex
717 protected function handleWriteError( DBError $exception, $serverIndex ) {
718 if ( $exception instanceof DBConnectionError ) {
719 $this->markServerDown( $exception, $serverIndex );
721 if ( $exception->db && $exception->db->wasReadOnlyError() ) {
722 try {
723 $exception->db->rollback( __METHOD__ );
724 } catch ( DBError $e ) {}
726 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
727 if ( $exception instanceof DBConnectionError ) {
728 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
729 wfDebug( __METHOD__ . ": ignoring connection error\n" );
730 } else {
731 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
732 wfDebug( __METHOD__ . ": ignoring query error\n" );
737 * Mark a server down due to a DBConnectionError exception
739 * @param DBError $exception
740 * @param int $serverIndex
742 protected function markServerDown( $exception, $serverIndex ) {
743 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
744 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
745 unset( $this->connFailureTimes[$serverIndex] );
746 unset( $this->connFailureErrors[$serverIndex] );
747 } else {
748 wfDebug( __METHOD__ . ": Server #$serverIndex already down\n" );
749 return;
752 $now = time();
753 wfDebug( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) . "\n" );
754 $this->connFailureTimes[$serverIndex] = $now;
755 $this->connFailureErrors[$serverIndex] = $exception;
759 * Create shard tables. For use from eval.php.
761 public function createTables() {
762 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
763 $db = $this->getDB( $serverIndex );
764 if ( $db->getType() !== 'mysql' ) {
765 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
768 for ( $i = 0; $i < $this->shards; $i++ ) {
769 $db->commit( __METHOD__, 'flush' );
770 $db->query(
771 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
772 ' LIKE ' . $db->tableName( 'objectcache' ),
773 __METHOD__ );
774 $db->commit( __METHOD__, 'flush' );
781 * Backwards compatibility alias
783 class MediaWikiBagOStuff extends SqlBagOStuff { }