MediaWiki master
ExternalStoreDB.php
Go to the documentation of this file.
1<?php
13use Wikimedia\ScopedCallback;
14
26 private $lbFactory;
27
33 public function __construct( array $params ) {
34 parent::__construct( $params );
35 if ( !isset( $params['lbFactory'] ) || !( $params['lbFactory'] instanceof LBFactory ) ) {
36 throw new InvalidArgumentException( "LBFactory required in 'lbFactory' field." );
37 }
38 $this->lbFactory = $params['lbFactory'];
39 }
40
51 public function fetchFromURL( $url ) {
52 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
53 $ret = $this->fetchBlob( $cluster, $id, $itemID );
54
55 if ( $itemID !== false && $ret !== false ) {
56 return $ret->getItem( $itemID );
57 }
58
59 return $ret;
60 }
61
72 public function batchFetchFromURLs( array $urls ) {
73 $batched = $inverseUrlMap = [];
74 foreach ( $urls as $url ) {
75 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
76 $batched[$cluster][$id][] = $itemID;
77 // false $itemID gets cast to int, but should be ok
78 // since we do === from the $itemID in $batched
79 $inverseUrlMap[$cluster][$id][$itemID] = $url;
80 }
81 $ret = [];
82 foreach ( $batched as $cluster => $batchByCluster ) {
83 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
85 foreach ( $res as $id => $blob ) {
86 foreach ( $batchByCluster[$id] as $itemID ) {
87 $url = $inverseUrlMap[$cluster][$id][$itemID];
88 if ( $itemID === false ) {
89 $ret[$url] = $blob;
90 } else {
91 $ret[$url] = $blob->getItem( $itemID );
92 }
93 }
94 }
95 }
96
97 return $ret;
98 }
99
103 public function store( $location, $data ) {
104 $blobsTable = $this->getTable( $location );
105
106 $dbw = $this->getPrimary( $location );
107 $dbw->newInsertQueryBuilder()
108 ->insertInto( $blobsTable )
109 ->row( [ 'blob_text' => $data ] )
110 ->caller( __METHOD__ )->execute();
111
112 $id = $dbw->insertId();
113 if ( !$id ) {
114 throw new ExternalStoreException( __METHOD__ . ': no insert ID' );
115 }
116
117 return "DB://$location/$id";
118 }
119
123 public function isReadOnly( $location ) {
124 if ( parent::isReadOnly( $location ) ) {
125 return true;
126 }
127
128 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
129 }
130
137 private function getLoadBalancer( $cluster ) {
138 return $this->lbFactory->getExternalLB( $cluster );
139 }
140
148 public function getReplica( $cluster ) {
149 $lb = $this->getLoadBalancer( $cluster );
150
151 return $lb->getConnection(
153 [],
154 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
155 $lb::CONN_TRX_AUTOCOMMIT
156 );
157 }
158
166 public function getPrimary( $cluster ) {
167 $lb = $this->getLoadBalancer( $cluster );
168
169 return $lb->getMaintenanceConnectionRef(
171 [],
172 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
173 $lb::CONN_TRX_AUTOCOMMIT
174 );
175 }
176
181 private function getDomainId( array $server ) {
182 if ( $this->isDbDomainExplicit ) {
183 return $this->dbDomain; // explicit foreign domain
184 }
185
186 if ( isset( $server['dbname'] ) ) {
187 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
188 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
189 // domain, but rather assumed that the LB server configuration matched $wgDBname.
190 // This check is useful when the external storage DB for this cluster does not use
191 // the same name as the corresponding "main" DB(s) for wikis.
192 $domain = new DatabaseDomain(
193 $server['dbname'],
194 $server['schema'] ?? null,
195 $server['tablePrefix'] ?? ''
196 );
197
198 return $domain->getId();
199 }
200
201 return false; // local LB domain
202 }
203
214 public function getTable( string $cluster ) {
215 $lb = $this->getLoadBalancer( $cluster );
216 $info = $lb->getServerInfo( ServerInfo::WRITER_INDEX );
217
218 return $info['blobs table'] ?? 'blobs';
219 }
220
227 public function initializeTable( $cluster ) {
228 global $IP;
229
230 static $supportedTypes = [ 'mysql', 'sqlite' ];
231
232 $dbw = $this->getPrimary( $cluster );
233 if ( !in_array( $dbw->getType(), $supportedTypes, true ) ) {
234 throw new DBUnexpectedError( $dbw, "RDBMS type '{$dbw->getType()}' not supported." );
235 }
236
237 $sqlFilePath = "$IP/maintenance/storage/blobs.sql";
238 $sql = file_get_contents( $sqlFilePath );
239 if ( $sql === false ) {
240 throw new RuntimeException( "Failed to read '$sqlFilePath'." );
241 }
242
243 $blobsTable = $this->getTable( $cluster );
244 $encTable = $dbw->tableName( $blobsTable );
245 $sqlWithReplacedVars = str_replace(
246 [ '/*$wgDBprefix*/blobs', '/*_*/blobs' ],
247 [ $encTable, $encTable ],
248 $sql
249 );
250
251 $dbw->query(
252 new Query(
253 $sqlWithReplacedVars,
254 $dbw::QUERY_CHANGE_SCHEMA,
255 'CREATE',
256 $blobsTable,
257 $sqlWithReplacedVars
258 ),
259 __METHOD__
260 );
261 }
262
272 private function fetchBlob( $cluster, $id, $itemID ) {
279 static $externalBlobCache = [];
280
281 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
282 $cacheID = "$cacheID@{$this->dbDomain}";
283
284 if ( isset( $externalBlobCache[$cacheID] ) ) {
285 $this->logger->debug( __METHOD__ . ": cache hit on $cacheID" );
286
287 return $externalBlobCache[$cacheID];
288 }
289
290 $this->logger->debug( __METHOD__ . ": cache miss on $cacheID" );
291
292 $blobsTable = $this->getTable( $cluster );
293
294 $dbr = $this->getReplica( $cluster );
295 $ret = $dbr->newSelectQueryBuilder()
296 ->select( 'blob_text' )
297 ->from( $blobsTable )
298 ->where( [ 'blob_id' => $id ] )
299 ->caller( __METHOD__ )->fetchField();
300
301 if ( $ret === false ) {
302 // Try the primary DB
303 $this->logger->warning( __METHOD__ . ": primary DB fallback on $cacheID" );
304 $trxProfiler = $this->lbFactory->getTransactionProfiler();
305 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
306 $dbw = $this->getPrimary( $cluster );
307 $ret = $dbw->newSelectQueryBuilder()
308 ->select( 'blob_text' )
309 ->from( $blobsTable )
310 ->where( [ 'blob_id' => $id ] )
311 ->caller( __METHOD__ )->fetchField();
312 ScopedCallback::consume( $scope );
313 if ( $ret === false ) {
314 $this->logger->warning( __METHOD__ . ": primary DB failed to find $cacheID" );
315 }
316 }
317 if ( $itemID !== false && $ret !== false ) {
318 // Unserialise object; caller extracts item
319 $ret = HistoryBlobUtils::unserialize( $ret );
320 }
321
322 $externalBlobCache = [ $cacheID => $ret ];
323
324 return $ret;
325 }
326
335 private function batchFetchBlobs( $cluster, array $ids ) {
336 $blobsTable = $this->getTable( $cluster );
337
338 $dbr = $this->getReplica( $cluster );
339 $res = $dbr->newSelectQueryBuilder()
340 ->select( [ 'blob_id', 'blob_text' ] )
341 ->from( $blobsTable )
342 ->where( [ 'blob_id' => array_keys( $ids ) ] )
343 ->caller( __METHOD__ )
344 ->fetchResultSet();
345
346 $ret = [];
347 $this->mergeBatchResult( $ret, $ids, $res );
348 if ( $ids ) {
349 // Try the primary
350 $this->logger->info(
351 __METHOD__ . ": primary fallback on '$cluster' for: " .
352 implode( ',', array_keys( $ids ) )
353 );
354 $trxProfiler = $this->lbFactory->getTransactionProfiler();
355 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
356 $dbw = $this->getPrimary( $cluster );
357 $res = $dbw->newSelectQueryBuilder()
358 ->select( [ 'blob_id', 'blob_text' ] )
359 ->from( $blobsTable )
360 ->where( [ 'blob_id' => array_keys( $ids ) ] )
361 ->caller( __METHOD__ )
362 ->fetchResultSet();
363 ScopedCallback::consume( $scope );
364 $this->mergeBatchResult( $ret, $ids, $res );
365 }
366 if ( $ids ) {
367 $this->logger->error(
368 __METHOD__ . ": primary on '$cluster' failed locating items: " .
369 implode( ',', array_keys( $ids ) )
370 );
371 }
372
373 return $ret;
374 }
375
382 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
383 foreach ( $res as $row ) {
384 $id = $row->blob_id;
385 $itemIDs = $ids[$id];
386 unset( $ids[$id] ); // to track if everything is found
387 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
388 // single result stored per blob
389 $ret[$id] = $row->blob_text;
390 } else {
391 // multi result stored per blob
392 $ret[$id] = HistoryBlobUtils::unserialize( $row->blob_text );
393 }
394 }
395 }
396
401 protected function parseURL( $url ) {
402 $path = explode( '/', $url );
403
404 return [
405 $path[2], // cluster
406 $path[3], // id
407 $path[4] ?? false // itemID
408 ];
409 }
410
418 public function getClusterForUrl( $url ) {
419 $parts = explode( '/', $url );
420 return $parts[2] ?? null;
421 }
422
430 public function getDomainIdForCluster( $cluster ) {
431 $lb = $this->getLoadBalancer( $cluster );
432 return $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) );
433 }
434}
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
if(!defined('MEDIAWIKI')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:90
External storage in a SQL database.
getPrimary( $cluster)
Get a primary database connection for the specified cluster.
__construct(array $params)
getDomainIdForCluster( $cluster)
Get the domain ID for a given cluster, which is false for the local wiki ID.
getTable(string $cluster)
Get the configured blobs table name for this database.
getReplica( $cluster)
Get a replica DB connection for the specified cluster.
getClusterForUrl( $url)
Get the cluster part of a URL.
initializeTable( $cluster)
Create the appropriate blobs table on this cluster.
fetchFromURL( $url)
Fetch data from given external store URL.
store( $location, $data)
Insert a data item into a given location.string|bool The URL of the stored data item,...
batchFetchFromURLs(array $urls)
Fetch multiple URLs from given external store.
isReadOnly( $location)
Check if a given location is read-only.bool Whether this location is read-only 1.31
Base class for external storage.
static unserialize(string $str, bool $allowDouble=false)
Unserialize a HistoryBlob.
Class to handle database/schema/prefix specifications for IDatabase.
Holds information on Query to be executed.
Definition Query.php:17
Container for accessing information about the database servers in a database cluster.
Base class for general text storage via the "object" flag in old_flags, or two-part external storage ...
This class is a delegate to ILBFactory for a given database cluster.