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