style: normalize end of files
[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 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';
43
44 protected $connFailureTimes = array(); // UNIX timestamps
45 protected $connFailureErrors = array(); // exceptions
46
47 /**
48 * Constructor. Parameters are:
49 * - server: A server info structure in the format required by each
50 * element in $wgDBServers.
51 *
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.
55 *
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.
62 *
63 * - tableName: The table name to use, default is "objectcache".
64 *
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.
72 *
73 * @param $params array
74 */
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";
82 }
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;
89 }
90 if ( isset( $params['purgePeriod'] ) ) {
91 $this->purgePeriod = intval( $params['purgePeriod'] );
92 }
93 if ( isset( $params['tableName'] ) ) {
94 $this->tableName = $params['tableName'];
95 }
96 if ( isset( $params['shards'] ) ) {
97 $this->shards = intval( $params['shards'] );
98 }
99 }
100
101 /**
102 * Get a connection to the specified database
103 *
104 * @param $serverIndex integer
105 * @return DatabaseBase
106 */
107 protected function getDB( $serverIndex ) {
108 global $wgDebugDBTransactions;
109
110 if ( !isset( $this->conns[$serverIndex] ) ) {
111 if ( $serverIndex >= $this->numServers ) {
112 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
113 }
114
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 )
118 {
119 throw $this->connFailureErrors[$serverIndex];
120 }
121
122 # If server connection info was given, use that
123 if ( $this->serverInfos ) {
124 if ( $wgDebugDBTransactions ) {
125 wfDebug( "Using provided serverInfo for SqlBagOStuff\n" );
126 }
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 {
134 /*
135 * We must keep a separate connection to MySQL in order to avoid deadlocks
136 * However, SQLite has an opposite behaviour. And PostgreSQL needs to know
137 * if we are in transaction or no
138 */
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 );
145 }
146 }
147 if ( $wgDebugDBTransactions ) {
148 wfDebug( sprintf( "Connection %s will be used for SqlBagOStuff\n", $db ) );
149 }
150 $this->conns[$serverIndex] = $db;
151 }
152
153 return $this->conns[$serverIndex];
154 }
155
156 /**
157 * Get the server index and table name for a given key
158 * @param $key string
159 * @return Array: server index and table name
160 */
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;
167 }
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;
175 }
176 return array( $serverIndex, $this->getTableNameByShard( $tableIndex ) );
177 }
178
179 /**
180 * Get the table name for a given shard index
181 * @param $index int
182 * @return string
183 */
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;
191 }
192 }
193
194 /**
195 * @param $key string
196 * @param $casToken[optional] mixed
197 * @return mixed
198 */
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];
204 }
205 return false;
206 }
207
208 /**
209 * @param $keys array
210 * @return Array
211 */
212 public function getMulti( array $keys ) {
213 $values = array(); // array of (key => value)
214
215 $keysByTable = array();
216 foreach ( $keys as $key ) {
217 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
218 $keysByTable[$serverIndex][$tableName][] = $key;
219 }
220
221 $this->garbageCollect(); // expire old entries if any
222
223 $dataRows = array();
224 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
225 $db = $this->getDB( $serverIndex );
226 try {
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;
236 }
237 }
238 } catch ( DBError $e ) {
239 $this->handleReadError( $e, $serverIndex );
240 }
241 }
242
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 $db = $this->getDB( $row->serverIndex );
248 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
249 $this->debug( "get: key has expired, deleting" );
250 try {
251 $db->begin( __METHOD__ );
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__ );
258 } catch ( DBQueryError $e ) {
259 $this->handleWriteError( $e, $row->serverIndex );
260 }
261 $values[$key] = false;
262 } else { // HIT
263 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
264 }
265 } else { // MISS
266 $values[$key] = false;
267 $this->debug( 'get: no matching rows' );
268 }
269 }
270
271 return $values;
272 }
273
274 /**
275 * @param $key string
276 * @param $value mixed
277 * @param $exptime int
278 * @return bool
279 */
280 public function set( $key, $value, $exptime = 0 ) {
281 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
282 try {
283 $db = $this->getDB( $serverIndex );
284 $exptime = intval( $exptime );
285
286 if ( $exptime < 0 ) {
287 $exptime = 0;
288 }
289
290 if ( $exptime == 0 ) {
291 $encExpiry = $this->getMaxDateTime( $db );
292 } else {
293 if ( $exptime < 3.16e8 ) { # ~10 years
294 $exptime += time();
295 }
296
297 $encExpiry = $db->timestamp( $exptime );
298 }
299 $db->begin( __METHOD__ );
300 // (bug 24425) use a replace if the db supports it instead of
301 // delete/insert to avoid clashes with conflicting keynames
302 $db->replace(
303 $tableName,
304 array( 'keyname' ),
305 array(
306 'keyname' => $key,
307 'value' => $db->encodeBlob( $this->serialize( $value ) ),
308 'exptime' => $encExpiry
309 ), __METHOD__ );
310 $db->commit( __METHOD__ );
311 } catch ( DBError $e ) {
312 $this->handleWriteError( $e, $serverIndex );
313 return false;
314 }
315
316 return true;
317 }
318
319 /**
320 * @param $casToken mixed
321 * @param $key string
322 * @param $value mixed
323 * @param $exptime int
324 * @return bool
325 */
326 public function cas( $casToken, $key, $value, $exptime = 0 ) {
327 $db = $this->getDB();
328 $exptime = intval( $exptime );
329
330 if ( $exptime < 0 ) {
331 $exptime = 0;
332 }
333
334 if ( $exptime == 0 ) {
335 $encExpiry = $this->getMaxDateTime();
336 } else {
337 if ( $exptime < 3.16e8 ) { # ~10 years
338 $exptime += time();
339 }
340
341 $encExpiry = $db->timestamp( $exptime );
342 }
343 try {
344 $db->begin( __METHOD__ );
345 // (bug 24425) use a replace if the db supports it instead of
346 // delete/insert to avoid clashes with conflicting keynames
347 $db->update(
348 $this->getTableByKey( $key ),
349 array(
350 'keyname' => $key,
351 'value' => $db->encodeBlob( $this->serialize( $value ) ),
352 'exptime' => $encExpiry
353 ),
354 array(
355 'keyname' => $key,
356 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
357 ), __METHOD__ );
358 $db->commit( __METHOD__ );
359 } catch ( DBQueryError $e ) {
360 $this->handleWriteError( $e );
361
362 return false;
363 }
364
365 return (bool) $db->affectedRows();
366 }
367
368 /**
369 * @param $key string
370 * @param $time int
371 * @return bool
372 */
373 public function delete( $key, $time = 0 ) {
374 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
375 try {
376 $db = $this->getDB( $serverIndex );
377 $db->begin( __METHOD__ );
378 $db->delete(
379 $tableName,
380 array( 'keyname' => $key ),
381 __METHOD__ );
382 $db->commit( __METHOD__ );
383 } catch ( DBError $e ) {
384 $this->handleWriteError( $e, $serverIndex );
385 return false;
386 }
387
388 return true;
389 }
390
391 /**
392 * @param $key string
393 * @param $step int
394 * @return int|null
395 */
396 public function incr( $key, $step = 1 ) {
397 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
398 try {
399 $db = $this->getDB( $serverIndex );
400 $step = intval( $step );
401 $db->begin( __METHOD__ );
402 $row = $db->selectRow(
403 $tableName,
404 array( 'value', 'exptime' ),
405 array( 'keyname' => $key ),
406 __METHOD__,
407 array( 'FOR UPDATE' ) );
408 if ( $row === false ) {
409 // Missing
410 $db->commit( __METHOD__ );
411
412 return null;
413 }
414 $db->delete( $tableName, array( 'keyname' => $key ), __METHOD__ );
415 if ( $this->isExpired( $db, $row->exptime ) ) {
416 // Expired, do not reinsert
417 $db->commit( __METHOD__ );
418
419 return null;
420 }
421
422 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
423 $newValue = $oldValue + $step;
424 $db->insert( $tableName,
425 array(
426 'keyname' => $key,
427 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
428 'exptime' => $row->exptime
429 ), __METHOD__, 'IGNORE' );
430
431 if ( $db->affectedRows() == 0 ) {
432 // Race condition. See bug 28611
433 $newValue = null;
434 }
435 $db->commit( __METHOD__ );
436 } catch ( DBError $e ) {
437 $this->handleWriteError( $e, $serverIndex );
438 return null;
439 }
440
441 return $newValue;
442 }
443
444 /**
445 * @param $exptime string
446 * @return bool
447 */
448 protected function isExpired( $db, $exptime ) {
449 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
450 }
451
452 /**
453 * @return string
454 */
455 protected function getMaxDateTime( $db ) {
456 if ( time() > 0x7fffffff ) {
457 return $db->timestamp( 1 << 62 );
458 } else {
459 return $db->timestamp( 0x7fffffff );
460 }
461 }
462
463 protected function garbageCollect() {
464 if ( !$this->purgePeriod ) {
465 // Disabled
466 return;
467 }
468 // Only purge on one in every $this->purgePeriod requests.
469 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
470 return;
471 }
472 $now = time();
473 // Avoid repeating the delete within a few seconds
474 if ( $now > ( $this->lastExpireAll + 1 ) ) {
475 $this->lastExpireAll = $now;
476 $this->expireAll();
477 }
478 }
479
480 public function expireAll() {
481 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
482 }
483
484 /**
485 * Delete objects from the database which expire before a certain date.
486 * @param $timestamp string
487 * @param $progressCallback bool|callback
488 * @return bool
489 */
490 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
491 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
492 try {
493 $db = $this->getDB( $serverIndex );
494 $dbTimestamp = $db->timestamp( $timestamp );
495 $totalSeconds = false;
496 $baseConds = array( 'exptime < ' . $db->addQuotes( $dbTimestamp ) );
497 for ( $i = 0; $i < $this->shards; $i++ ) {
498 $maxExpTime = false;
499 while ( true ) {
500 $conds = $baseConds;
501 if ( $maxExpTime !== false ) {
502 $conds[] = 'exptime > ' . $db->addQuotes( $maxExpTime );
503 }
504 $rows = $db->select(
505 $this->getTableNameByShard( $i ),
506 array( 'keyname', 'exptime' ),
507 $conds,
508 __METHOD__,
509 array( 'LIMIT' => 100, 'ORDER BY' => 'exptime' ) );
510 if ( !$rows->numRows() ) {
511 break;
512 }
513 $keys = array();
514 $row = $rows->current();
515 $minExpTime = $row->exptime;
516 if ( $totalSeconds === false ) {
517 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
518 - wfTimestamp( TS_UNIX, $minExpTime );
519 }
520 foreach ( $rows as $row ) {
521 $keys[] = $row->keyname;
522 $maxExpTime = $row->exptime;
523 }
524
525 $db->begin( __METHOD__ );
526 $db->delete(
527 $this->getTableNameByShard( $i ),
528 array(
529 'exptime >= ' . $db->addQuotes( $minExpTime ),
530 'exptime < ' . $db->addQuotes( $dbTimestamp ),
531 'keyname' => $keys
532 ),
533 __METHOD__ );
534 $db->commit( __METHOD__ );
535
536 if ( $progressCallback ) {
537 if ( intval( $totalSeconds ) === 0 ) {
538 $percent = 0;
539 } else {
540 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
541 - wfTimestamp( TS_UNIX, $maxExpTime );
542 if ( $remainingSeconds > $totalSeconds ) {
543 $totalSeconds = $remainingSeconds;
544 }
545 $percent = ( $i + $remainingSeconds / $totalSeconds )
546 / $this->shards * 100;
547 }
548 $percent = ( $percent / $this->numServers )
549 + ( $serverIndex / $this->numServers * 100 );
550 call_user_func( $progressCallback, $percent );
551 }
552 }
553 }
554 } catch ( DBError $e ) {
555 $this->handleWriteError( $e, $serverIndex );
556 return false;
557 }
558 }
559 return true;
560 }
561
562 public function deleteAll() {
563 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
564 try {
565 $db = $this->getDB( $serverIndex );
566 for ( $i = 0; $i < $this->shards; $i++ ) {
567 $db->begin( __METHOD__ );
568 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
569 $db->commit( __METHOD__ );
570 }
571 } catch ( DBError $e ) {
572 $this->handleWriteError( $e, $serverIndex );
573 return false;
574 }
575 }
576 return true;
577 }
578
579 /**
580 * Serialize an object and, if possible, compress the representation.
581 * On typical message and page data, this can provide a 3X decrease
582 * in storage requirements.
583 *
584 * @param $data mixed
585 * @return string
586 */
587 protected function serialize( &$data ) {
588 $serial = serialize( $data );
589
590 if ( function_exists( 'gzdeflate' ) ) {
591 return gzdeflate( $serial );
592 } else {
593 return $serial;
594 }
595 }
596
597 /**
598 * Unserialize and, if necessary, decompress an object.
599 * @param $serial string
600 * @return mixed
601 */
602 protected function unserialize( $serial ) {
603 if ( function_exists( 'gzinflate' ) ) {
604 wfSuppressWarnings();
605 $decomp = gzinflate( $serial );
606 wfRestoreWarnings();
607
608 if ( false !== $decomp ) {
609 $serial = $decomp;
610 }
611 }
612
613 $ret = unserialize( $serial );
614
615 return $ret;
616 }
617
618 /**
619 * Handle a DBError which occurred during a read operation.
620 */
621 protected function handleReadError( DBError $exception, $serverIndex ) {
622 if ( $exception instanceof DBConnectionError ) {
623 $this->markServerDown( $exception, $serverIndex );
624 }
625 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
626 if ( $exception instanceof DBConnectionError ) {
627 wfDebug( __METHOD__ . ": ignoring connection error\n" );
628 } else {
629 wfDebug( __METHOD__ . ": ignoring query error\n" );
630 }
631 }
632
633 /**
634 * Handle a DBQueryError which occurred during a write operation.
635 */
636 protected function handleWriteError( DBError $exception, $serverIndex ) {
637 if ( $exception instanceof DBConnectionError ) {
638 $this->markServerDown( $exception, $serverIndex );
639 }
640 if ( $exception->db && $exception->db->wasReadOnlyError() ) {
641 try {
642 $exception->db->rollback( __METHOD__ );
643 } catch ( DBError $e ) {}
644 }
645 wfDebugLog( 'SQLBagOStuff', "DBError: {$exception->getMessage()}" );
646 if ( $exception instanceof DBConnectionError ) {
647 wfDebug( __METHOD__ . ": ignoring connection error\n" );
648 } else {
649 wfDebug( __METHOD__ . ": ignoring query error\n" );
650 }
651 }
652
653 /**
654 * Mark a server down due to a DBConnectionError exception
655 */
656 protected function markServerDown( $exception, $serverIndex ) {
657 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
658 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
659 unset( $this->connFailureTimes[$serverIndex] );
660 unset( $this->connFailureErrors[$serverIndex] );
661 } else {
662 wfDebug( __METHOD__.": Server #$serverIndex already down\n" );
663 return;
664 }
665 }
666 $now = time();
667 wfDebug( __METHOD__.": Server #$serverIndex down until " . ( $now + 60 ) . "\n" );
668 $this->connFailureTimes[$serverIndex] = $now;
669 $this->connFailureErrors[$serverIndex] = $exception;
670 }
671
672 /**
673 * Create shard tables. For use from eval.php.
674 */
675 public function createTables() {
676 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
677 $db = $this->getDB( $serverIndex );
678 if ( $db->getType() !== 'mysql'
679 || version_compare( $db->getServerVersion(), '4.1.0', '<' ) )
680 {
681 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
682 }
683
684 for ( $i = 0; $i < $this->shards; $i++ ) {
685 $db->begin( __METHOD__ );
686 $db->query(
687 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
688 ' LIKE ' . $db->tableName( 'objectcache' ),
689 __METHOD__ );
690 $db->commit( __METHOD__ );
691 }
692 }
693 }
694 }
695
696 /**
697 * Backwards compatibility alias
698 */
699 class MediaWikiBagOStuff extends SqlBagOStuff { }