Merge "objectcache: define some missing methods in ReplicatedBagOStuff"
[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 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\Database;
26 use Wikimedia\Rdbms\IDatabase;
27 use Wikimedia\Rdbms\DBError;
28 use Wikimedia\Rdbms\DBQueryError;
29 use Wikimedia\Rdbms\DBConnectionError;
30 use Wikimedia\Rdbms\LoadBalancer;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\WaitConditionLoop;
33
34 /**
35 * Class to store objects in the database
36 *
37 * @ingroup Cache
38 */
39 class SqlBagOStuff extends BagOStuff {
40 /** @var array[] (server index => server config) */
41 protected $serverInfos;
42 /** @var string[] (server index => tag/host name) */
43 protected $serverTags;
44 /** @var int */
45 protected $numServers;
46 /** @var int */
47 protected $lastExpireAll = 0;
48 /** @var int */
49 protected $purgePeriod = 100;
50 /** @var int */
51 protected $shards = 1;
52 /** @var string */
53 protected $tableName = 'objectcache';
54 /** @var bool */
55 protected $replicaOnly = false;
56 /** @var int */
57 protected $syncTimeout = 3;
58
59 /** @var LoadBalancer|null */
60 protected $separateMainLB;
61 /** @var array */
62 protected $conns;
63 /** @var array UNIX timestamps */
64 protected $connFailureTimes = [];
65 /** @var array Exceptions */
66 protected $connFailureErrors = [];
67
68 /**
69 * Constructor. Parameters are:
70 * - server: A server info structure in the format required by each
71 * element in $wgDBServers.
72 *
73 * - servers: An array of server info structures describing a set of database servers
74 * to distribute keys to. If this is specified, the "server" option will be
75 * ignored. If string keys are used, then they will be used for consistent
76 * hashing *instead* of the host name (from the server config). This is useful
77 * when a cluster is replicated to another site (with different host names)
78 * but each server has a corresponding replica in the other cluster.
79 *
80 * - purgePeriod: The average number of object cache requests in between
81 * garbage collection operations, where expired entries
82 * are removed from the database. Or in other words, the
83 * reciprocal of the probability of purging on any given
84 * request. If this is set to zero, purging will never be
85 * done.
86 *
87 * - tableName: The table name to use, default is "objectcache".
88 *
89 * - shards: The number of tables to use for data storage on each server.
90 * If this is more than 1, table names will be formed in the style
91 * objectcacheNNN where NNN is the shard index, between 0 and
92 * shards-1. The number of digits will be the minimum number
93 * required to hold the largest shard index. Data will be
94 * distributed across all tables by key hash. This is for
95 * MySQL bugs 61735 <https://bugs.mysql.com/bug.php?id=61735>
96 * and 61736 <https://bugs.mysql.com/bug.php?id=61736>.
97 *
98 * - slaveOnly: Whether to only use replica DBs and avoid triggering
99 * garbage collection logic of expired items. This only
100 * makes sense if the primary DB is used and only if get()
101 * calls will be used. This is used by ReplicatedBagOStuff.
102 * - syncTimeout: Max seconds to wait for replica DBs to catch up for WRITE_SYNC.
103 *
104 * @param array $params
105 */
106 public function __construct( $params ) {
107 parent::__construct( $params );
108
109 $this->attrMap[self::ATTR_EMULATION] = self::QOS_EMULATION_SQL;
110 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_NONE;
111
112 if ( isset( $params['servers'] ) ) {
113 $this->serverInfos = [];
114 $this->serverTags = [];
115 $this->numServers = count( $params['servers'] );
116 $index = 0;
117 foreach ( $params['servers'] as $tag => $info ) {
118 $this->serverInfos[$index] = $info;
119 if ( is_string( $tag ) ) {
120 $this->serverTags[$index] = $tag;
121 } else {
122 $this->serverTags[$index] = $info['host'] ?? "#$index";
123 }
124 ++$index;
125 }
126 } elseif ( isset( $params['server'] ) ) {
127 $this->serverInfos = [ $params['server'] ];
128 $this->numServers = count( $this->serverInfos );
129 } else {
130 // Default to using the main wiki's database servers
131 $this->serverInfos = false;
132 $this->numServers = 1;
133 $this->attrMap[self::ATTR_SYNCWRITES] = self::QOS_SYNCWRITES_BE;
134 }
135 if ( isset( $params['purgePeriod'] ) ) {
136 $this->purgePeriod = intval( $params['purgePeriod'] );
137 }
138 if ( isset( $params['tableName'] ) ) {
139 $this->tableName = $params['tableName'];
140 }
141 if ( isset( $params['shards'] ) ) {
142 $this->shards = intval( $params['shards'] );
143 }
144 if ( isset( $params['syncTimeout'] ) ) {
145 $this->syncTimeout = $params['syncTimeout'];
146 }
147 $this->replicaOnly = !empty( $params['slaveOnly'] );
148 }
149
150 /**
151 * Get a connection to the specified database
152 *
153 * @param int $serverIndex
154 * @return Database
155 * @throws MWException
156 */
157 protected function getDB( $serverIndex ) {
158 if ( !isset( $this->conns[$serverIndex] ) ) {
159 if ( $serverIndex >= $this->numServers ) {
160 throw new MWException( __METHOD__ . ": Invalid server index \"$serverIndex\"" );
161 }
162
163 # Don't keep timing out trying to connect for each call if the DB is down
164 if ( isset( $this->connFailureErrors[$serverIndex] )
165 && ( time() - $this->connFailureTimes[$serverIndex] ) < 60
166 ) {
167 throw $this->connFailureErrors[$serverIndex];
168 }
169
170 if ( $this->serverInfos ) {
171 // Use custom database defined by server connection info
172 $info = $this->serverInfos[$serverIndex];
173 $type = $info['type'] ?? 'mysql';
174 $host = $info['host'] ?? '[unknown]';
175 $this->logger->debug( __CLASS__ . ": connecting to $host" );
176 $db = Database::factory( $type, $info );
177 $db->clearFlag( DBO_TRX ); // auto-commit mode
178 } else {
179 // Use the main LB database
180 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
181 $index = $this->replicaOnly ? DB_REPLICA : DB_MASTER;
182 if ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' ) {
183 // Keep a separate connection to avoid contention and deadlocks
184 $db = $lb->getConnection( $index, [], false, $lb::CONN_TRX_AUTOCOMMIT );
185 } else {
186 // However, SQLite has the opposite behavior due to DB-level locking.
187 // Stock sqlite MediaWiki installs use a separate sqlite cache DB instead.
188 $db = $lb->getConnection( $index );
189 }
190 }
191
192 $this->logger->debug( sprintf( "Connection %s will be used for SqlBagOStuff", $db ) );
193 $this->conns[$serverIndex] = $db;
194 }
195
196 return $this->conns[$serverIndex];
197 }
198
199 /**
200 * Get the server index and table name for a given key
201 * @param string $key
202 * @return array Server index and table name
203 */
204 protected function getTableByKey( $key ) {
205 if ( $this->shards > 1 ) {
206 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
207 $tableIndex = $hash % $this->shards;
208 } else {
209 $tableIndex = 0;
210 }
211 if ( $this->numServers > 1 ) {
212 $sortedServers = $this->serverTags;
213 ArrayUtils::consistentHashSort( $sortedServers, $key );
214 reset( $sortedServers );
215 $serverIndex = key( $sortedServers );
216 } else {
217 $serverIndex = 0;
218 }
219 return [ $serverIndex, $this->getTableNameByShard( $tableIndex ) ];
220 }
221
222 /**
223 * Get the table name for a given shard index
224 * @param int $index
225 * @return string
226 */
227 protected function getTableNameByShard( $index ) {
228 if ( $this->shards > 1 ) {
229 $decimals = strlen( $this->shards - 1 );
230 return $this->tableName .
231 sprintf( "%0{$decimals}d", $index );
232 } else {
233 return $this->tableName;
234 }
235 }
236
237 protected function doGet( $key, $flags = 0 ) {
238 $casToken = null;
239
240 return $this->getWithToken( $key, $casToken, $flags );
241 }
242
243 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
244 $values = $this->getMulti( [ $key ] );
245 if ( array_key_exists( $key, $values ) ) {
246 $casToken = $values[$key];
247 return $values[$key];
248 }
249 return false;
250 }
251
252 public function getMulti( array $keys, $flags = 0 ) {
253 $values = []; // array of (key => value)
254
255 $keysByTable = [];
256 foreach ( $keys as $key ) {
257 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
258 $keysByTable[$serverIndex][$tableName][] = $key;
259 }
260
261 $this->garbageCollect(); // expire old entries if any
262
263 $dataRows = [];
264 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
265 try {
266 $db = $this->getDB( $serverIndex );
267 foreach ( $serverKeys as $tableName => $tableKeys ) {
268 $res = $db->select( $tableName,
269 [ 'keyname', 'value', 'exptime' ],
270 [ 'keyname' => $tableKeys ],
271 __METHOD__,
272 // Approximate write-on-the-fly BagOStuff API via blocking.
273 // This approximation fails if a ROLLBACK happens (which is rare).
274 // We do not want to flush the TRX as that can break callers.
275 $db->trxLevel() ? [ 'LOCK IN SHARE MODE' ] : []
276 );
277 if ( $res === false ) {
278 continue;
279 }
280 foreach ( $res as $row ) {
281 $row->serverIndex = $serverIndex;
282 $row->tableName = $tableName;
283 $dataRows[$row->keyname] = $row;
284 }
285 }
286 } catch ( DBError $e ) {
287 $this->handleReadError( $e, $serverIndex );
288 }
289 }
290
291 foreach ( $keys as $key ) {
292 if ( isset( $dataRows[$key] ) ) { // HIT?
293 $row = $dataRows[$key];
294 $this->debug( "get: retrieved data; expiry time is " . $row->exptime );
295 $db = null;
296 try {
297 $db = $this->getDB( $row->serverIndex );
298 if ( $this->isExpired( $db, $row->exptime ) ) { // MISS
299 $this->debug( "get: key has expired" );
300 } else { // HIT
301 $values[$key] = $this->unserialize( $db->decodeBlob( $row->value ) );
302 }
303 } catch ( DBQueryError $e ) {
304 $this->handleWriteError( $e, $db, $row->serverIndex );
305 }
306 } else { // MISS
307 $this->debug( 'get: no matching rows' );
308 }
309 }
310
311 return $values;
312 }
313
314 public function setMulti( array $data, $expiry = 0, $flags = 0 ) {
315 return $this->insertMulti( $data, $expiry, $flags, true );
316 }
317
318 private function insertMulti( array $data, $expiry, $flags, $replace ) {
319 $keysByTable = [];
320 foreach ( $data as $key => $value ) {
321 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
322 $keysByTable[$serverIndex][$tableName][] = $key;
323 }
324
325 $this->garbageCollect(); // expire old entries if any
326
327 $result = true;
328 $exptime = (int)$expiry;
329 $silenceScope = $this->silenceTransactionProfiler();
330 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
331 $db = null;
332 try {
333 $db = $this->getDB( $serverIndex );
334 } catch ( DBError $e ) {
335 $this->handleWriteError( $e, $db, $serverIndex );
336 $result = false;
337 continue;
338 }
339
340 if ( $exptime < 0 ) {
341 $exptime = 0;
342 }
343
344 if ( $exptime == 0 ) {
345 $encExpiry = $this->getMaxDateTime( $db );
346 } else {
347 $exptime = $this->convertToExpiry( $exptime );
348 $encExpiry = $db->timestamp( $exptime );
349 }
350 foreach ( $serverKeys as $tableName => $tableKeys ) {
351 $rows = [];
352 foreach ( $tableKeys as $key ) {
353 $rows[] = [
354 'keyname' => $key,
355 'value' => $db->encodeBlob( $this->serialize( $data[$key] ) ),
356 'exptime' => $encExpiry,
357 ];
358 }
359
360 try {
361 if ( $replace ) {
362 $db->replace( $tableName, [ 'keyname' ], $rows, __METHOD__ );
363 } else {
364 $db->insert( $tableName, $rows, __METHOD__, [ 'IGNORE' ] );
365 $result = ( $db->affectedRows() > 0 && $result );
366 }
367 } catch ( DBError $e ) {
368 $this->handleWriteError( $e, $db, $serverIndex );
369 $result = false;
370 }
371
372 }
373 }
374
375 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
376 $result = $this->waitForReplication() && $result;
377 }
378
379 return $result;
380 }
381
382 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
383 $ok = $this->setMulti( [ $key => $value ], $exptime );
384
385 return $ok;
386 }
387
388 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
389 $added = $this->insertMulti( [ $key => $value ], $exptime, $flags, false );
390
391 return $added;
392 }
393
394 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
395 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
396 $db = null;
397 $silenceScope = $this->silenceTransactionProfiler();
398 try {
399 $db = $this->getDB( $serverIndex );
400 $exptime = intval( $exptime );
401
402 if ( $exptime < 0 ) {
403 $exptime = 0;
404 }
405
406 if ( $exptime == 0 ) {
407 $encExpiry = $this->getMaxDateTime( $db );
408 } else {
409 $exptime = $this->convertToExpiry( $exptime );
410 $encExpiry = $db->timestamp( $exptime );
411 }
412 // (T26425) use a replace if the db supports it instead of
413 // delete/insert to avoid clashes with conflicting keynames
414 $db->update(
415 $tableName,
416 [
417 'keyname' => $key,
418 'value' => $db->encodeBlob( $this->serialize( $value ) ),
419 'exptime' => $encExpiry
420 ],
421 [
422 'keyname' => $key,
423 'value' => $db->encodeBlob( $this->serialize( $casToken ) )
424 ],
425 __METHOD__
426 );
427 } catch ( DBQueryError $e ) {
428 $this->handleWriteError( $e, $db, $serverIndex );
429
430 return false;
431 }
432
433 return (bool)$db->affectedRows();
434 }
435
436 public function deleteMulti( array $keys, $flags = 0 ) {
437 $keysByTable = [];
438 foreach ( $keys as $key ) {
439 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
440 $keysByTable[$serverIndex][$tableName][] = $key;
441 }
442
443 $result = true;
444 $silenceScope = $this->silenceTransactionProfiler();
445 foreach ( $keysByTable as $serverIndex => $serverKeys ) {
446 $db = null;
447 try {
448 $db = $this->getDB( $serverIndex );
449 } catch ( DBError $e ) {
450 $this->handleWriteError( $e, $db, $serverIndex );
451 $result = false;
452 continue;
453 }
454
455 foreach ( $serverKeys as $tableName => $tableKeys ) {
456 try {
457 $db->delete( $tableName, [ 'keyname' => $tableKeys ], __METHOD__ );
458 } catch ( DBError $e ) {
459 $this->handleWriteError( $e, $db, $serverIndex );
460 $result = false;
461 }
462
463 }
464 }
465
466 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
467 $result = $this->waitForReplication() && $result;
468 }
469
470 return $result;
471 }
472
473 public function delete( $key, $flags = 0 ) {
474 $ok = $this->deleteMulti( [ $key ], $flags );
475
476 return $ok;
477 }
478
479 public function incr( $key, $step = 1 ) {
480 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
481 $db = null;
482 $silenceScope = $this->silenceTransactionProfiler();
483 try {
484 $db = $this->getDB( $serverIndex );
485 $step = intval( $step );
486 $row = $db->selectRow(
487 $tableName,
488 [ 'value', 'exptime' ],
489 [ 'keyname' => $key ],
490 __METHOD__,
491 [ 'FOR UPDATE' ]
492 );
493 if ( $row === false ) {
494 // Missing
495 return false;
496 }
497 $db->delete( $tableName, [ 'keyname' => $key ], __METHOD__ );
498 if ( $this->isExpired( $db, $row->exptime ) ) {
499 // Expired, do not reinsert
500 return false;
501 }
502
503 $oldValue = intval( $this->unserialize( $db->decodeBlob( $row->value ) ) );
504 $newValue = $oldValue + $step;
505 $db->insert(
506 $tableName,
507 [
508 'keyname' => $key,
509 'value' => $db->encodeBlob( $this->serialize( $newValue ) ),
510 'exptime' => $row->exptime
511 ],
512 __METHOD__,
513 'IGNORE'
514 );
515
516 if ( $db->affectedRows() == 0 ) {
517 // Race condition. See T30611
518 $newValue = false;
519 }
520 } catch ( DBError $e ) {
521 $this->handleWriteError( $e, $db, $serverIndex );
522 return false;
523 }
524
525 return $newValue;
526 }
527
528 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
529 $ok = $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
530 if ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) {
531 $ok = $this->waitForReplication() && $ok;
532 }
533
534 return $ok;
535 }
536
537 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
538 list( $serverIndex, $tableName ) = $this->getTableByKey( $key );
539 $db = null;
540 $silenceScope = $this->silenceTransactionProfiler();
541 try {
542 $db = $this->getDB( $serverIndex );
543 if ( $exptime == 0 ) {
544 $timestamp = $this->getMaxDateTime( $db );
545 } else {
546 $timestamp = $db->timestamp( $this->convertToExpiry( $exptime ) );
547 }
548 $db->update(
549 $tableName,
550 [ 'exptime' => $timestamp ],
551 [ 'keyname' => $key, 'exptime > ' . $db->addQuotes( $db->timestamp( time() ) ) ],
552 __METHOD__
553 );
554 if ( $db->affectedRows() == 0 ) {
555 $exists = (bool)$db->selectField(
556 $tableName,
557 1,
558 [ 'keyname' => $key, 'exptime' => $timestamp ],
559 __METHOD__,
560 [ 'FOR UPDATE' ]
561 );
562
563 return $exists;
564 }
565 } catch ( DBError $e ) {
566 $this->handleWriteError( $e, $db, $serverIndex );
567 return false;
568 }
569
570 return true;
571 }
572
573 /**
574 * @param IDatabase $db
575 * @param string $exptime
576 * @return bool
577 */
578 protected function isExpired( $db, $exptime ) {
579 return $exptime != $this->getMaxDateTime( $db ) && wfTimestamp( TS_UNIX, $exptime ) < time();
580 }
581
582 /**
583 * @param IDatabase $db
584 * @return string
585 */
586 protected function getMaxDateTime( $db ) {
587 if ( time() > 0x7fffffff ) {
588 return $db->timestamp( 1 << 62 );
589 } else {
590 return $db->timestamp( 0x7fffffff );
591 }
592 }
593
594 protected function garbageCollect() {
595 if ( !$this->purgePeriod || $this->replicaOnly ) {
596 // Disabled
597 return;
598 }
599 // Only purge on one in every $this->purgePeriod requests.
600 if ( $this->purgePeriod !== 1 && mt_rand( 0, $this->purgePeriod - 1 ) ) {
601 return;
602 }
603 $now = time();
604 // Avoid repeating the delete within a few seconds
605 if ( $now > ( $this->lastExpireAll + 1 ) ) {
606 $this->lastExpireAll = $now;
607 $this->expireAll();
608 }
609 }
610
611 public function expireAll() {
612 $this->deleteObjectsExpiringBefore( wfTimestampNow() );
613 }
614
615 /**
616 * Delete objects from the database which expire before a certain date.
617 * @param string $timestamp
618 * @param bool|callable $progressCallback
619 * @return bool
620 */
621 public function deleteObjectsExpiringBefore( $timestamp, $progressCallback = false ) {
622 $silenceScope = $this->silenceTransactionProfiler();
623 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
624 $db = null;
625 try {
626 $db = $this->getDB( $serverIndex );
627 $dbTimestamp = $db->timestamp( $timestamp );
628 $totalSeconds = false;
629 $baseConds = [ 'exptime < ' . $db->addQuotes( $dbTimestamp ) ];
630 for ( $i = 0; $i < $this->shards; $i++ ) {
631 $maxExpTime = false;
632 while ( true ) {
633 $conds = $baseConds;
634 if ( $maxExpTime !== false ) {
635 $conds[] = 'exptime >= ' . $db->addQuotes( $maxExpTime );
636 }
637 $rows = $db->select(
638 $this->getTableNameByShard( $i ),
639 [ 'keyname', 'exptime' ],
640 $conds,
641 __METHOD__,
642 [ 'LIMIT' => 100, 'ORDER BY' => 'exptime' ] );
643 if ( $rows === false || !$rows->numRows() ) {
644 break;
645 }
646 $keys = [];
647 $row = $rows->current();
648 $minExpTime = $row->exptime;
649 if ( $totalSeconds === false ) {
650 $totalSeconds = wfTimestamp( TS_UNIX, $timestamp )
651 - wfTimestamp( TS_UNIX, $minExpTime );
652 }
653 foreach ( $rows as $row ) {
654 $keys[] = $row->keyname;
655 $maxExpTime = $row->exptime;
656 }
657
658 $db->delete(
659 $this->getTableNameByShard( $i ),
660 [
661 'exptime >= ' . $db->addQuotes( $minExpTime ),
662 'exptime < ' . $db->addQuotes( $dbTimestamp ),
663 'keyname' => $keys
664 ],
665 __METHOD__ );
666
667 if ( $progressCallback ) {
668 if ( intval( $totalSeconds ) === 0 ) {
669 $percent = 0;
670 } else {
671 $remainingSeconds = wfTimestamp( TS_UNIX, $timestamp )
672 - wfTimestamp( TS_UNIX, $maxExpTime );
673 if ( $remainingSeconds > $totalSeconds ) {
674 $totalSeconds = $remainingSeconds;
675 }
676 $processedSeconds = $totalSeconds - $remainingSeconds;
677 $percent = ( $i + $processedSeconds / $totalSeconds )
678 / $this->shards * 100;
679 }
680 $percent = ( $percent / $this->numServers )
681 + ( $serverIndex / $this->numServers * 100 );
682 call_user_func( $progressCallback, $percent );
683 }
684 }
685 }
686 } catch ( DBError $e ) {
687 $this->handleWriteError( $e, $db, $serverIndex );
688 return false;
689 }
690 }
691 return true;
692 }
693
694 /**
695 * Delete content of shard tables in every server.
696 * Return true if the operation is successful, false otherwise.
697 * @return bool
698 */
699 public function deleteAll() {
700 $silenceScope = $this->silenceTransactionProfiler();
701 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
702 $db = null;
703 try {
704 $db = $this->getDB( $serverIndex );
705 for ( $i = 0; $i < $this->shards; $i++ ) {
706 $db->delete( $this->getTableNameByShard( $i ), '*', __METHOD__ );
707 }
708 } catch ( DBError $e ) {
709 $this->handleWriteError( $e, $db, $serverIndex );
710 return false;
711 }
712 }
713 return true;
714 }
715
716 /**
717 * Serialize an object and, if possible, compress the representation.
718 * On typical message and page data, this can provide a 3X decrease
719 * in storage requirements.
720 *
721 * @param mixed &$data
722 * @return string
723 */
724 protected function serialize( &$data ) {
725 $serial = serialize( $data );
726
727 if ( function_exists( 'gzdeflate' ) ) {
728 return gzdeflate( $serial );
729 } else {
730 return $serial;
731 }
732 }
733
734 /**
735 * Unserialize and, if necessary, decompress an object.
736 * @param string $serial
737 * @return mixed
738 */
739 protected function unserialize( $serial ) {
740 if ( function_exists( 'gzinflate' ) ) {
741 Wikimedia\suppressWarnings();
742 $decomp = gzinflate( $serial );
743 Wikimedia\restoreWarnings();
744
745 if ( $decomp !== false ) {
746 $serial = $decomp;
747 }
748 }
749
750 $ret = unserialize( $serial );
751
752 return $ret;
753 }
754
755 /**
756 * Handle a DBError which occurred during a read operation.
757 *
758 * @param DBError $exception
759 * @param int $serverIndex
760 */
761 protected function handleReadError( DBError $exception, $serverIndex ) {
762 if ( $exception instanceof DBConnectionError ) {
763 $this->markServerDown( $exception, $serverIndex );
764 }
765
766 $this->setAndLogDBError( $exception );
767 }
768
769 /**
770 * Handle a DBQueryError which occurred during a write operation.
771 *
772 * @param DBError $exception
773 * @param IDatabase|null $db DB handle or null if connection failed
774 * @param int $serverIndex
775 * @throws Exception
776 */
777 protected function handleWriteError( DBError $exception, IDatabase $db = null, $serverIndex ) {
778 if ( !$db ) {
779 $this->markServerDown( $exception, $serverIndex );
780 }
781
782 $this->setAndLogDBError( $exception );
783 }
784
785 /**
786 * @param DBError $exception
787 */
788 private function setAndLogDBError( DBError $exception ) {
789 $this->logger->error( "DBError: {$exception->getMessage()}" );
790 if ( $exception instanceof DBConnectionError ) {
791 $this->setLastError( BagOStuff::ERR_UNREACHABLE );
792 $this->logger->debug( __METHOD__ . ": ignoring connection error" );
793 } else {
794 $this->setLastError( BagOStuff::ERR_UNEXPECTED );
795 $this->logger->debug( __METHOD__ . ": ignoring query error" );
796 }
797 }
798
799 /**
800 * Mark a server down due to a DBConnectionError exception
801 *
802 * @param DBError $exception
803 * @param int $serverIndex
804 */
805 protected function markServerDown( DBError $exception, $serverIndex ) {
806 unset( $this->conns[$serverIndex] ); // bug T103435
807
808 if ( isset( $this->connFailureTimes[$serverIndex] ) ) {
809 if ( time() - $this->connFailureTimes[$serverIndex] >= 60 ) {
810 unset( $this->connFailureTimes[$serverIndex] );
811 unset( $this->connFailureErrors[$serverIndex] );
812 } else {
813 $this->logger->debug( __METHOD__ . ": Server #$serverIndex already down" );
814 return;
815 }
816 }
817 $now = time();
818 $this->logger->info( __METHOD__ . ": Server #$serverIndex down until " . ( $now + 60 ) );
819 $this->connFailureTimes[$serverIndex] = $now;
820 $this->connFailureErrors[$serverIndex] = $exception;
821 }
822
823 /**
824 * Create shard tables. For use from eval.php.
825 */
826 public function createTables() {
827 for ( $serverIndex = 0; $serverIndex < $this->numServers; $serverIndex++ ) {
828 $db = $this->getDB( $serverIndex );
829 if ( $db->getType() !== 'mysql' ) {
830 throw new MWException( __METHOD__ . ' is not supported on this DB server' );
831 }
832
833 for ( $i = 0; $i < $this->shards; $i++ ) {
834 $db->query(
835 'CREATE TABLE ' . $db->tableName( $this->getTableNameByShard( $i ) ) .
836 ' LIKE ' . $db->tableName( 'objectcache' ),
837 __METHOD__ );
838 }
839 }
840 }
841
842 /**
843 * @return bool Whether the main DB is used, e.g. wfGetDB( DB_MASTER )
844 */
845 protected function usesMainDB() {
846 return !$this->serverInfos;
847 }
848
849 protected function waitForReplication() {
850 if ( !$this->usesMainDB() ) {
851 // Custom DB server list; probably doesn't use replication
852 return true;
853 }
854
855 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
856 if ( $lb->getServerCount() <= 1 ) {
857 return true; // no replica DBs
858 }
859
860 // Main LB is used; wait for any replica DBs to catch up
861 try {
862 $masterPos = $lb->getMasterPos();
863 if ( !$masterPos ) {
864 return true; // not applicable
865 }
866
867 $loop = new WaitConditionLoop(
868 function () use ( $lb, $masterPos ) {
869 return $lb->waitForAll( $masterPos, 1 );
870 },
871 $this->syncTimeout,
872 $this->busyCallbacks
873 );
874
875 return ( $loop->invoke() === $loop::CONDITION_REACHED );
876 } catch ( DBError $e ) {
877 $this->setAndLogDBError( $e );
878
879 return false;
880 }
881 }
882
883 /**
884 * Returns a ScopedCallback which resets the silence flag in the transaction profiler when it is
885 * destroyed on the end of a scope, for example on return or throw
886 * @return ScopedCallback
887 * @since 1.32
888 */
889 protected function silenceTransactionProfiler() {
890 $trxProfiler = Profiler::instance()->getTransactionProfiler();
891 $oldSilenced = $trxProfiler->setSilenced( true );
892 return new ScopedCallback( function () use ( $trxProfiler, $oldSilenced ) {
893 $trxProfiler->setSilenced( $oldSilenced );
894 } );
895 }
896 }