MWException: Don't send headers multiple times
[mediawiki.git] / includes / objectcache / SqlBagOStuff.php
blobbcd5942879987f8dc60f0577f30cbdc79a56df4a
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 /** @var LoadBalancer */
31 protected $lb;
33 protected $serverInfos;
35 /** @var array */
36 protected $serverNames;
38 /** @var int */
39 protected $numServers;
41 /** @var array */
42 protected $conns;
44 /** @var int */
45 protected $lastExpireAll = 0;
47 /** @var int */
48 protected $purgePeriod = 100;
50 /** @var int */
51 protected $shards = 1;
53 /** @var string */
54 protected $tableName = 'objectcache';
56 /** @var array UNIX timestamps */
57 protected $connFailureTimes = array();
59 /** @var array Exceptions */
60 protected $connFailureErrors = array();
62 /**
63 * Constructor. Parameters are:
64 * - server: A server info structure in the format required by each
65 * element in $wgDBServers.
67 * - servers: An array of server info structures describing a set of
68 * database servers to distribute keys to. If this is
69 * specified, the "server" option will be ignored.
71 * - purgePeriod: The average number of object cache requests in between
72 * garbage collection operations, where expired entries
73 * are removed from the database. Or in other words, the
74 * reciprocal of the probability of purging on any given
75 * request. If this is set to zero, purging will never be
76 * done.
78 * - tableName: The table name to use, default is "objectcache".
80 * - shards: The number of tables to use for data storage on each server.
81 * If this is more than 1, table names will be formed in the style
82 * objectcacheNNN where NNN is the shard index, between 0 and
83 * shards-1. The number of digits will be the minimum number
84 * required to hold the largest shard index. Data will be
85 * distributed across all tables by key hash. This is for
86 * MySQL bugs 61735 and 61736.
88 * @param array $params
90 public function __construct( $params ) {
91 if ( isset( $params['servers'] ) ) {
92 $this->serverInfos = $params['servers'];
93 $this->numServers = count( $this->serverInfos );
94 $this->serverNames = array();
95 foreach ( $this->serverInfos as $i => $info ) {
96 $this->serverNames[$i] = isset( $info['host'] ) ? $info['host'] : "#$i";
98 } elseif ( isset( $params['server'] ) ) {
99 $this->serverInfos = array( $params['server'] );
100 $this->numServers = count( $this->serverInfos );
101 } else {
102 $this->serverInfos = false;
103 $this->numServers = 1;
105 if ( isset( $params['purgePeriod'] ) ) {
106 $this->purgePeriod = intval( $params['purgePeriod'] );
108 if ( isset( $params['tableName'] ) ) {
109 $this->tableName = $params['tableName'];
111 if ( isset( $params['shards'] ) ) {
112 $this->shards = intval( $params['shards'] );
117 * Get a connection to the specified database
119 * @param int $serverIndex
120 * @return DatabaseBase
122 protected function getDB( $serverIndex ) {
123 global $wgDebugDBTransactions;
125 if ( !isset( $this->conns[$serverIndex] ) ) {
126 if ( $serverIndex >= $this->numServers ) {
127 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
130 # Don't keep timing out trying to connect for each call if the DB is down
131 if ( isset( $this->connFailureErrors[$serverIndex] )
132 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
134 throw $this->connFailureErrors[$serverIndex];
137 # If server connection info was given, use that
138 if ( $this->serverInfos ) {
139 if ( $wgDebugDBTransactions ) {
140 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
142 $info = $this->serverInfos[$serverIndex];
143 $type = isset( $info['type'] ) ? $info['type'] : 'mysql';
144 $host = isset( $info['host'] ) ? $info['host'] : '[unknown]';
145 wfDebug( __CLASS__ . ": connecting to $host\n" );
146 $db = DatabaseBase::factory( $type, $info );
147 $db->clearFlag( DBO_TRX );
148 } else {
150 * We must keep a separate connection to MySQL in order to avoid deadlocks
151 * However, SQLite has an opposite behavior. And PostgreSQL needs to know
152 * if we are in transaction or no
154 if ( wfGetDB( DB_MASTER )->getType() == 'mysql' ) {
155 $this->lb = wfGetLBFactory()->newMainLB();
156 $db = $this->lb->getConnection( DB_MASTER );
157 $db->clearFlag( DBO_TRX ); // auto-commit mode
158 } else {
159 $db = wfGetDB( DB_MASTER );
162 if ( $wgDebugDBTransactions ) {
163 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
165 $this->conns[$serverIndex] = $db;
168 return $this->conns[$serverIndex];
172 * Get the server index and table name for a given key
173 * @param string $key
174 * @return array Server index and table name
176 protected function getTableByKey( $key ) {
177 if ( $this->shards > 1 ) {
178 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
179 $tableIndex = $hash % $this->shards;
180 } else {
181 $tableIndex = 0;
183 if ( $this->numServers > 1 ) {
184 $sortedServers = $this->serverNames;
185 ArrayUtils::consistentHashSort( $sortedServers, $key );
186 reset( $sortedServers );
187 $serverIndex = key( $sortedServers );
188 } else {
189 $serverIndex = 0;
191 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
195 * Get the table name for a given shard index
196 * @param int $index
197 * @return string
199 protected function getTableNameByShard( $index ) {
200 if ( $this->shards > 1 ) {
201 $decimals = strlen( $this->shards - 1 );
202 return $this->tableName .
203 sprintf( "%0{$decimals}d", $index );
204 } else {
205 return $this->tableName;
210 * @param string $key
211 * @param mixed $casToken [optional]
212 * @return mixed
214 public function get( $key, &$casToken = null ) {
215 $values = $this->getMulti( array( $key ) );
216 if ( array_key_exists( $key, $values ) ) {
217 $casToken = $values[$key];
218 return $values[$key];
220 return false;
224 * @param array $keys
225 * @return array
227 public function getMulti( array $keys ) {
228 $values = array(); // array of (key => value)
230 $keysByTable = array();
231 foreach ( $keys as $key ) {
232 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
233 $keysByTable[$serverIndex][$tableName][] = $key;
236 $this->garbageCollect(); // expire old entries if any
238 $dataRows = array();
239 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
240 try {
241 $db = $this->getDB( $serverIndex );
242 foreach ( $serverKeys as $tableName => $tableKeys ) {
243 $res = $db->select( $tableName,
244 array( 'keyname', 'value', 'exptime' ),
245 array( 'keyname' => $tableKeys ),
246 __METHOD__ );
247 foreach ( $res as $row ) {
248 $row->serverIndex = $serverIndex;
249 $row->tableName = $tableName;
250 $dataRows[$row->keyname] = $row;
253 } catch ( DBError $e ) {
254 $this->handleReadError( $e, $serverIndex );
258 foreach ( $keys as $key ) {
259 if ( isset( $dataRows[$key] ) ) { // HIT?
260 $row = $dataRows[$key];
261 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
262 try {
263 $db = $this->getDB( $row->serverIndex );
264 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
265 $this->debug( "get: key has expired, deleting" );
266 $db->commit( __METHOD__, 'flush' );
267 # Put the expiry time in the WHERE condition to avoid deleting a
268 # newly-inserted value
269 $db->delete( $row->tableName,
270 array( 'keyname' => $key, 'exptime' => $row->exptime ),
271 __METHOD__ );
272 $db->commit( __METHOD__, 'flush' );
273 $values[$key] = false;
274 } else { // HIT
275 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
277 } catch ( DBQueryError $e ) {
278 $this->handleWriteError( $e, $row->serverIndex );
280 } else { // MISS
281 $values[$key] = false;
282 $this->debug( 'get: no matching rows' );
286 return $values;
290 * @param array $data
291 * @param int $expiry
292 * @return bool
294 public function setMulti( array $data, $expiry = 0 ) {
295 $keysByTable = array();
296 foreach ( $data as $key => $value ) {
297 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
298 $keysByTable[$serverIndex][$tableName][] = $key;
301 $this->garbageCollect(); // expire old entries if any
303 $result = true;
304 $exptime = (int)$expiry;
305 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
306 try {
307 $db = $this->getDB( $serverIndex );
308 } catch ( DBError $e ) {
309 $this->handleWriteError( $e, $serverIndex );
310 $result = false;
311 continue;
314 if ( $exptime < 0 ) {
315 $exptime = 0;
318 if ( $exptime == 0 ) {
319 $encExpiry = $this->getMaxDateTime( $db );
320 } else {
321 if ( $exptime < 3.16e8 ) { # ~10 years
322 $exptime += time();
324 $encExpiry = $db->timestamp( $exptime );
326 foreach ( $serverKeys as $tableName => $tableKeys ) {
327 $rows = array();
328 foreach ( $tableKeys as $key ) {
329 $rows[] = array(
330 'keyname' => $key,
331 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
332 'exptime' => $encExpiry,
336 try {
337 $db->commit( __METHOD__, 'flush' );
338 $db->replace(
339 $tableName,
340 array( 'keyname' ),
341 $rows,
342 __METHOD__
344 $db->commit( __METHOD__, 'flush' );
345 } catch ( DBError $e ) {
346 $this->handleWriteError( $e, $serverIndex );
347 $result = false;
354 return $result;
360 * @param string $key
361 * @param mixed $value
362 * @param int $exptime
363 * @return bool
365 public function set( $key, $value, $exptime = 0 ) {
366 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
367 try {
368 $db = $this->getDB( $serverIndex );
369 $exptime = intval( $exptime );
371 if ( $exptime < 0 ) {
372 $exptime = 0;
375 if ( $exptime == 0 ) {
376 $encExpiry = $this->getMaxDateTime( $db );
377 } else {
378 if ( $exptime < 3.16e8 ) { # ~10 years
379 $exptime += time();
382 $encExpiry = $db->timestamp( $exptime );
384 $db->commit( __METHOD__, 'flush' );
385 // (bug 24425) use a replace if the db supports it instead of
386 // delete/insert to avoid clashes with conflicting keynames
387 $db->replace(
388 $tableName,
389 array( 'keyname' ),
390 array(
391 'keyname' => $key,
392 'value' => $db->encodeBlob( $this->serialize( $value ) ),
393 'exptime' => $encExpiry
394 ), __METHOD__ );
395 $db->commit( __METHOD__, 'flush' );
396 } catch ( DBError $e ) {
397 $this->handleWriteError( $e, $serverIndex );
398 return false;
401 return true;
405 * @param mixed $casToken
406 * @param string $key
407 * @param mixed $value
408 * @param int $exptime
409 * @return bool
411 public function cas( $casToken, $key, $value, $exptime = 0 ) {
412 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
413 try {
414 $db = $this->getDB( $serverIndex );
415 $exptime = intval( $exptime );
417 if ( $exptime < 0 ) {
418 $exptime = 0;
421 if ( $exptime == 0 ) {
422 $encExpiry = $this->getMaxDateTime( $db );
423 } else {
424 if ( $exptime < 3.16e8 ) { # ~10 years
425 $exptime += time();
427 $encExpiry = $db->timestamp( $exptime );
429 $db->commit( __METHOD__, 'flush' );
430 // (bug 24425) use a replace if the db supports it instead of
431 // delete/insert to avoid clashes with conflicting keynames
432 $db->update(
433 $tableName,
434 array(
435 'keyname' => $key,
436 'value' => $db->encodeBlob( $this->serialize( $value ) ),
437 'exptime' => $encExpiry
439 array(
440 'keyname' => $key,
441 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
443 __METHOD__
445 $db->commit( __METHOD__, 'flush' );
446 } catch ( DBQueryError $e ) {
447 $this->handleWriteError( $e, $serverIndex );
449 return false;
452 return (bool)$db->affectedRows();
456 * @param string $key
457 * @param int $time
458 * @return bool
460 public function delete( $key, $time = 0 ) {
461 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
462 try {
463 $db = $this->getDB( $serverIndex );
464 $db->commit( __METHOD__, 'flush' );
465 $db->delete(
466 $tableName,
467 array( 'keyname' => $key ),
468 __METHOD__ );
469 $db->commit( __METHOD__, 'flush' );
470 } catch ( DBError $e ) {
471 $this->handleWriteError( $e, $serverIndex );
472 return false;
475 return true;
479 * @param string $key
480 * @param int $step
481 * @return int|null
483 public function incr( $key, $step = 1 ) {
484 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
485 try {
486 $db = $this->getDB( $serverIndex );
487 $step = intval( $step );
488 $db->commit( __METHOD__, 'flush' );
489 $row = $db->selectRow(
490 $tableName,
491 array( 'value', 'exptime' ),
492 array( 'keyname' => $key ),
493 __METHOD__,
494 array( 'FOR UPDATE' ) );
495 if ( $row === false ) {
496 // Missing
497 $db->commit( __METHOD__, 'flush' );
499 return null;
501 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
502 if ( $this->isExpired( $db, $row->exptime ) ) {
503 // Expired, do not reinsert
504 $db->commit( __METHOD__, 'flush' );
506 return null;
509 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
510 $newValue = $oldValue + $step;
511 $db->insert( $tableName,
512 array(
513 'keyname' => $key,
514 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
515 'exptime' => $row->exptime
516 ), __METHOD__, 'IGNORE' );
518 if ( $db->affectedRows() == 0 ) {
519 // Race condition. See bug 28611
520 $newValue = null;
522 $db->commit( __METHOD__, 'flush' );
523 } catch ( DBError $e ) {
524 $this->handleWriteError( $e, $serverIndex );
525 return null;
528 return $newValue;
532 * @param string $exptime
533 * @return bool
535 protected function isExpired( $db, $exptime ) {
536 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
540 * @param DatabaseBase $db
541 * @return string
543 protected function getMaxDateTime( $db ) {
544 if ( time() > 0x7fffffff ) {
545 return $db->timestamp( 1 << 62 );
546 } else {
547 return $db->timestamp( 0x7fffffff );
551 protected function garbageCollect() {
552 if ( !$this->purgePeriod ) {
553 // Disabled
554 return;
556 // Only purge on one in every $this->purgePeriod requests.
557 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
558 return;
560 $now = time();
561 // Avoid repeating the delete within a few seconds
562 if ( $now > ( $this->lastExpireAll + 1 ) ) {
563 $this->lastExpireAll = $now;
564 $this->expireAll();
568 public function expireAll() {
569 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
573 * Delete objects from the database which expire before a certain date.
574 * @param string $timestamp
575 * @param bool|callable $progressCallback
576 * @return bool
578 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
579 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
580 try {
581 $db = $this->getDB( $serverIndex );
582 $dbTimestamp = $db->timestamp( $timestamp );
583 $totalSeconds = false;
584 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
585 for ( $i = 0; $i < $this->shards; $i++ ) {
586 $maxExpTime = false;
587 while ( true ) {
588 $conds = $baseConds;
589 if ( $maxExpTime !== false ) {
590 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
592 $rows = $db->select(
593 $this->getTableNameByShard( $i ),
594 array( 'keyname', 'exptime' ),
595 $conds,
596 __METHOD__,
597 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
598 if ( !$rows->numRows() ) {
599 break;
601 $keys = array();
602 $row = $rows->current();
603 $minExpTime = $row->exptime;
604 if ( $totalSeconds === false ) {
605 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
606 - wfTimestamp( TS_UNIX, $minExpTime );
608 foreach ( $rows as $row ) {
609 $keys[] = $row->keyname;
610 $maxExpTime = $row->exptime;
613 $db->commit( __METHOD__, 'flush' );
614 $db->delete(
615 $this->getTableNameByShard( $i ),
616 array(
617 'exptime >= ' . $db->addQuotes( $minExpTime ),
618 'exptime < ' . $db->addQuotes( $dbTimestamp ),
619 'keyname' => $keys
621 __METHOD__ );
622 $db->commit( __METHOD__, 'flush' );
624 if ( $progressCallback ) {
625 if ( intval( $totalSeconds ) === 0 ) {
626 $percent = 0;
627 } else {
628 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
629 - wfTimestamp( TS_UNIX, $maxExpTime );
630 if ( $remainingSeconds > $totalSeconds ) {
631 $totalSeconds = $remainingSeconds;
633 $percent = ( $i + $remainingSeconds / $totalSeconds )
634 / $this->shards * 100;
636 $percent = ( $percent / $this->numServers )
637 + ( $serverIndex / $this->numServers * 100 );
638 call_user_func( $progressCallback, $percent );
642 } catch ( DBError $e ) {
643 $this->handleWriteError( $e, $serverIndex );
644 return false;
647 return true;
650 public function deleteAll() {
651 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
652 try {
653 $db = $this->getDB( $serverIndex );
654 for ( $i = 0; $i < $this->shards; $i++ ) {
655 $db->commit( __METHOD__, 'flush' );
656 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
657 $db->commit( __METHOD__, 'flush' );
659 } catch ( DBError $e ) {
660 $this->handleWriteError( $e, $serverIndex );
661 return false;
664 return true;
668 * Serialize an object and, if possible, compress the representation.
669 * On typical message and page data, this can provide a 3X decrease
670 * in storage requirements.
672 * @param mixed $data
673 * @return string
675 protected function serialize( &$data ) {
676 $serial = serialize( $data );
678 if ( function_exists( 'gzdeflate' ) ) {
679 return gzdeflate( $serial );
680 } else {
681 return $serial;
686 * Unserialize and, if necessary, decompress an object.
687 * @param string $serial
688 * @return mixed
690 protected function unserialize( $serial ) {
691 if ( function_exists( 'gzinflate' ) ) {
692 wfSuppressWarnings();
693 $decomp = gzinflate( $serial );
694 wfRestoreWarnings();
696 if ( false !== $decomp ) {
697 $serial = $decomp;
701 $ret = unserialize( $serial );
703 return $ret;
707 * Handle a DBError which occurred during a read operation.
709 * @param DBError $exception
710 * @param int $serverIndex
712 protected function handleReadError( DBError $exception, $serverIndex ) {
713 if ( $exception instanceof DBConnectionError ) {
714 $this->markServerDown( $exception, $serverIndex );
716 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
717 if ( $exception instanceof DBConnectionError ) {
718 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
719 wfDebug( __METHOD__ . ": ignoring connection error\n" );
720 } else {
721 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
722 wfDebug( __METHOD__ . ": ignoring query error\n" );
727 * Handle a DBQueryError which occurred during a write operation.
729 * @param DBError $exception
730 * @param int $serverIndex
732 protected function handleWriteError( DBError $exception, $serverIndex ) {
733 if ( $exception instanceof DBConnectionError ) {
734 $this->markServerDown( $exception, $serverIndex );
736 if ( $exception->db && $exception->db->wasReadOnlyError() ) {
737 try {
738 $exception->db->rollback( __METHOD__ );
739 } catch ( DBError $e ) {
742 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
743 if ( $exception instanceof DBConnectionError ) {
744 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
745 wfDebug( __METHOD__ . ": ignoring connection error\n" );
746 } else {
747 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
748 wfDebug( __METHOD__ . ": ignoring query error\n" );
753 * Mark a server down due to a DBConnectionError exception
755 * @param DBError $exception
756 * @param int $serverIndex
758 protected function markServerDown( $exception, $serverIndex ) {
759 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
760 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
761 unset( $this->connFailureTimes[$serverIndex] );
762 unset( $this->connFailureErrors[$serverIndex] );
763 } else {
764 wfDebug( __METHOD__ . ": Server #$serverIndex already down\n" );
765 return;
768 $now = time();
769 wfDebug( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) . "\n" );
770 $this->connFailureTimes[$serverIndex] = $now;
771 $this->connFailureErrors[$serverIndex] = $exception;
775 * Create shard tables. For use from eval.php.
777 public function createTables() {
778 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
779 $db = $this->getDB( $serverIndex );
780 if ( $db->getType() !== 'mysql' ) {
781 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
784 for ( $i = 0; $i < $this->shards; $i++ ) {
785 $db->commit( __METHOD__, 'flush' );
786 $db->query(
787 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
788 ' LIKE ' . $db->tableName( 'objectcache' ),
789 __METHOD__ );
790 $db->commit( __METHOD__, 'flush' );
797 * Backwards compatibility alias
799 class MediaWikiBagOStuff extends SqlBagOStuff {