3 * External storage in 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
23 use Wikimedia\Rdbms\LBFactory
;
24 use Wikimedia\Rdbms\ILoadBalancer
;
25 use Wikimedia\Rdbms\IDatabase
;
26 use Wikimedia\Rdbms\DBConnRef
;
27 use Wikimedia\Rdbms\MaintainableDBConnRef
;
28 use Wikimedia\Rdbms\DatabaseDomain
;
31 * DB accessible external objects.
33 * In this system, each store "location" maps to a database "cluster".
34 * The clusters must be defined in the normal LBFactory configuration.
36 * @ingroup ExternalStorage
38 class ExternalStoreDB
extends ExternalStoreMedium
{
43 * @see ExternalStoreMedium::__construct()
44 * @param array $params Additional parameters include:
45 * - lbFactory: an LBFactory instance
47 public function __construct( array $params ) {
48 parent
::__construct( $params );
49 if ( !isset( $params['lbFactory'] ) ||
!( $params['lbFactory'] instanceof LBFactory
) ) {
50 throw new InvalidArgumentException( "LBFactory required in 'lbFactory' field." );
52 $this->lbFactory
= $params['lbFactory'];
56 * The provided URL is in the form of DB://cluster/id
57 * or DB://cluster/id/itemid for concatened storage.
60 * @return string|bool False if missing
61 * @see ExternalStoreMedium::fetchFromURL()
63 public function fetchFromURL( $url ) {
64 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
65 $ret = $this->fetchBlob( $cluster, $id, $itemID );
67 if ( $itemID !== false && $ret !== false ) {
68 return $ret->getItem( $itemID );
75 * Fetch data from given external store URLs.
76 * The provided URLs are in the form of DB://cluster/id
77 * or DB://cluster/id/itemid for concatened storage.
79 * @param array $urls An array of external store URLs
80 * @return array A map from url to stored content. Failed results
81 * are not represented.
83 public function batchFetchFromURLs( array $urls ) {
84 $batched = $inverseUrlMap = [];
85 foreach ( $urls as $url ) {
86 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
87 $batched[$cluster][$id][] = $itemID;
88 // false $itemID gets cast to int, but should be ok
89 // since we do === from the $itemID in $batched
90 $inverseUrlMap[$cluster][$id][$itemID] = $url;
93 foreach ( $batched as $cluster => $batchByCluster ) {
94 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
95 /** @var HistoryBlob $blob */
96 foreach ( $res as $id => $blob ) {
97 foreach ( $batchByCluster[$id] as $itemID ) {
98 $url = $inverseUrlMap[$cluster][$id][$itemID];
99 if ( $itemID === false ) {
102 $ret[$url] = $blob->getItem( $itemID );
114 public function store( $location, $data ) {
115 $dbw = $this->getMaster( $location );
116 $dbw->insert( $this->getTable( $dbw ), [ 'blob_text' => $data ], __METHOD__
);
117 $id = $dbw->insertId();
119 throw new MWException( __METHOD__
. ': no insert ID' );
122 return "DB://$location/$id";
128 public function isReadOnly( $location ) {
129 if ( parent
::isReadOnly( $location ) ) {
133 $lb = $this->getLoadBalancer( $location );
134 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
136 return ( $lb->getReadOnlyReason( $domainId ) !== false );
140 * Get a LoadBalancer for the specified cluster
142 * @param string $cluster Cluster name
143 * @return ILoadBalancer
145 private function getLoadBalancer( $cluster ) {
146 return $this->lbFactory
->getExternalLB( $cluster );
150 * Get a replica DB connection for the specified cluster
152 * @param string $cluster Cluster name
155 public function getSlave( $cluster ) {
156 $lb = $this->getLoadBalancer( $cluster );
158 return $lb->getConnectionRef(
161 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
162 $lb::CONN_TRX_AUTOCOMMIT
167 * Get a master database connection for the specified cluster
169 * @param string $cluster Cluster name
170 * @return MaintainableDBConnRef
172 public function getMaster( $cluster ) {
173 $lb = $this->getLoadBalancer( $cluster );
175 return $lb->getMaintenanceConnectionRef(
178 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
179 $lb::CONN_TRX_AUTOCOMMIT
184 * @param array $server Master DB server configuration array for LoadBalancer
185 * @return string|bool Database domain ID or false
187 private function getDomainId( array $server ) {
188 if ( $this->isDbDomainExplicit
) {
189 return $this->dbDomain
; // explicit foreign domain
192 if ( isset( $server['dbname'] ) ) {
193 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
194 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
195 // domain, but rather assumed that the LB server configuration matched $wgDBname.
196 // This check is useful when the external storage DB for this cluster does not use
197 // the same name as the corresponding "main" DB(s) for wikis.
198 $domain = new DatabaseDomain(
200 $server['schema'] ??
null,
201 $server['tablePrefix'] ??
''
204 return $domain->getId();
207 return false; // local LB domain
211 * Get the 'blobs' table name for this database
213 * @param IDatabase $db
214 * @return string Table name ('blobs' by default)
216 public function getTable( $db ) {
217 $table = $db->getLBInfo( 'blobs table' );
218 if ( is_null( $table ) ) {
226 * Fetch a blob item out of the database; a cache of the last-loaded
227 * blob will be kept so that multiple loads out of a multi-item blob
228 * can avoid redundant database access and decompression.
229 * @param string $cluster
231 * @param string $itemID
232 * @return HistoryBlob|bool Returns false if missing
234 private function fetchBlob( $cluster, $id, $itemID ) {
236 * One-step cache variable to hold base blobs; operations that
237 * pull multiple revisions may often pull multiple times from
238 * the same blob. By keeping the last-used one open, we avoid
239 * redundant unserialization and decompression overhead.
241 static $externalBlobCache = [];
243 $cacheID = ( $itemID === false ) ?
"$cluster/$id" : "$cluster/$id/";
244 $cacheID = "$cacheID@{$this->dbDomain}";
246 if ( isset( $externalBlobCache[$cacheID] ) ) {
247 $this->logger
->debug( "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
249 return $externalBlobCache[$cacheID];
252 $this->logger
->debug( "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
254 $dbr = $this->getSlave( $cluster );
255 $ret = $dbr->selectField( $this->getTable( $dbr ),
256 'blob_text', [ 'blob_id' => $id ], __METHOD__
);
257 if ( $ret === false ) {
258 $this->logger
->info( "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
260 $dbw = $this->getMaster( $cluster );
261 $ret = $dbw->selectField( $this->getTable( $dbw ),
262 'blob_text', [ 'blob_id' => $id ], __METHOD__
);
263 if ( $ret === false ) {
264 $this->logger
->error( "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
267 if ( $itemID !== false && $ret !== false ) {
268 // Unserialise object; caller extracts item
269 $ret = unserialize( $ret );
272 $externalBlobCache = [ $cacheID => $ret ];
278 * Fetch multiple blob items out of the database
280 * @param string $cluster A cluster name valid for use with LBFactory
281 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
282 * @return array A map from the blob_id's requested to their content.
283 * Unlocated ids are not represented
285 private function batchFetchBlobs( $cluster, array $ids ) {
286 $dbr = $this->getSlave( $cluster );
288 $this->getTable( $dbr ),
289 [ 'blob_id', 'blob_text' ],
290 [ 'blob_id' => array_keys( $ids ) ],
295 if ( $res !== false ) {
296 $this->mergeBatchResult( $ret, $ids, $res );
300 __METHOD__
. ": master fallback on '$cluster' for: " .
301 implode( ',', array_keys( $ids ) )
304 $dbw = $this->getMaster( $cluster );
305 $res = $dbw->select( $this->getTable( $dbr ),
306 [ 'blob_id', 'blob_text' ],
307 [ 'blob_id' => array_keys( $ids ) ],
309 if ( $res === false ) {
310 $this->logger
->error( __METHOD__
. ": master failed on '$cluster'" );
312 $this->mergeBatchResult( $ret, $ids, $res );
316 $this->logger
->error(
317 __METHOD__
. ": master on '$cluster' failed locating items: " .
318 implode( ',', array_keys( $ids ) )
326 * Helper function for self::batchFetchBlobs for merging master/replica DB results
327 * @param array &$ret Current self::batchFetchBlobs return value
328 * @param array &$ids Map from blob_id to requested itemIDs
329 * @param mixed $res DB result from Database::select
331 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
332 foreach ( $res as $row ) {
334 $itemIDs = $ids[$id];
335 unset( $ids[$id] ); // to track if everything is found
336 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
337 // single result stored per blob
338 $ret[$id] = $row->blob_text
;
340 // multi result stored per blob
341 $ret[$id] = unserialize( $row->blob_text
);
350 protected function parseURL( $url ) {
351 $path = explode( '/', $url );
356 $path[4] ??
false // itemID