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