MediaWiki master
ExternalStoreDB.php
Go to the documentation of this file.
1<?php
28use Wikimedia\ScopedCallback;
29
41 private $lbFactory;
42
48 public function __construct( array $params ) {
49 parent::__construct( $params );
50 if ( !isset( $params['lbFactory'] ) || !( $params['lbFactory'] instanceof LBFactory ) ) {
51 throw new InvalidArgumentException( "LBFactory required in 'lbFactory' field." );
52 }
53 $this->lbFactory = $params['lbFactory'];
54 }
55
66 public function fetchFromURL( $url ) {
67 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
68 $ret = $this->fetchBlob( $cluster, $id, $itemID );
69
70 if ( $itemID !== false && $ret !== false ) {
71 return $ret->getItem( $itemID );
72 }
73
74 return $ret;
75 }
76
87 public function batchFetchFromURLs( array $urls ) {
88 $batched = $inverseUrlMap = [];
89 foreach ( $urls as $url ) {
90 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
91 $batched[$cluster][$id][] = $itemID;
92 // false $itemID gets cast to int, but should be ok
93 // since we do === from the $itemID in $batched
94 $inverseUrlMap[$cluster][$id][$itemID] = $url;
95 }
96 $ret = [];
97 foreach ( $batched as $cluster => $batchByCluster ) {
98 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
100 foreach ( $res as $id => $blob ) {
101 foreach ( $batchByCluster[$id] as $itemID ) {
102 $url = $inverseUrlMap[$cluster][$id][$itemID];
103 if ( $itemID === false ) {
104 $ret[$url] = $blob;
105 } else {
106 $ret[$url] = $blob->getItem( $itemID );
107 }
108 }
109 }
110 }
111
112 return $ret;
113 }
114
118 public function store( $location, $data ) {
119 $dbw = $this->getPrimary( $location );
120 $dbw->newInsertQueryBuilder()
121 ->insertInto( $this->getTable( $dbw, $location ) )
122 ->row( [ 'blob_text' => $data ] )
123 ->caller( __METHOD__ )->execute();
124 $id = $dbw->insertId();
125 if ( !$id ) {
126 throw new ExternalStoreException( __METHOD__ . ': no insert ID' );
127 }
128
129 return "DB://$location/$id";
130 }
131
135 public function isReadOnly( $location ) {
136 if ( parent::isReadOnly( $location ) ) {
137 return true;
138 }
139
140 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
141 }
142
149 private function getLoadBalancer( $cluster ) {
150 return $this->lbFactory->getExternalLB( $cluster );
151 }
152
160 public function getReplica( $cluster ) {
161 $lb = $this->getLoadBalancer( $cluster );
162
163 return $lb->getConnectionRef(
165 [],
166 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
167 $lb::CONN_TRX_AUTOCOMMIT
168 );
169 }
170
178 public function getPrimary( $cluster ) {
179 $lb = $this->getLoadBalancer( $cluster );
180
181 return $lb->getMaintenanceConnectionRef(
183 [],
184 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
185 $lb::CONN_TRX_AUTOCOMMIT
186 );
187 }
188
193 private function getDomainId( array $server ) {
194 if ( $this->isDbDomainExplicit ) {
195 return $this->dbDomain; // explicit foreign domain
196 }
197
198 if ( isset( $server['dbname'] ) ) {
199 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
200 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
201 // domain, but rather assumed that the LB server configuration matched $wgDBname.
202 // This check is useful when the external storage DB for this cluster does not use
203 // the same name as the corresponding "main" DB(s) for wikis.
204 $domain = new DatabaseDomain(
205 $server['dbname'],
206 $server['schema'] ?? null,
207 $server['tablePrefix'] ?? ''
208 );
209
210 return $domain->getId();
211 }
212
213 return false; // local LB domain
214 }
215
223 public function getTable( $db, $cluster = null ) {
224 if ( $cluster !== null ) {
225 $lb = $this->getLoadBalancer( $cluster );
226 $info = $lb->getServerInfo( $lb->getWriterIndex() );
227 if ( isset( $info['blobs table'] ) ) {
228 return $info['blobs table'];
229 }
230 }
231
232 return $db->getLBInfo( 'blobs table' ) ?? 'blobs'; // b/c
233 }
234
242 public function initializeTable( $cluster ) {
243 global $IP;
244
245 static $supportedTypes = [ 'mysql', 'sqlite' ];
246
247 $dbw = $this->getPrimary( $cluster );
248 if ( !in_array( $dbw->getType(), $supportedTypes, true ) ) {
249 throw new DBUnexpectedError( $dbw, "RDBMS type '{$dbw->getType()}' not supported." );
250 }
251
252 $sqlFilePath = "$IP/maintenance/storage/blobs.sql";
253 $sql = file_get_contents( $sqlFilePath );
254 if ( $sql === false ) {
255 throw new RuntimeException( "Failed to read '$sqlFilePath'." );
256 }
257
258 $rawTable = $this->getTable( $dbw, $cluster ); // e.g. "blobs_cluster23"
259 $encTable = $dbw->tableName( $rawTable );
260
261 $sqlWithReplacedVars = str_replace(
262 [ '/*$wgDBprefix*/blobs', '/*_*/blobs' ],
263 [ $encTable, $encTable ],
264 $sql
265 );
266
267 $dbw->query(
268 new Query(
269 $sqlWithReplacedVars,
270 $dbw::QUERY_CHANGE_SCHEMA,
271 'CREATE',
272 $rawTable,
273 $sqlWithReplacedVars
274 ),
275 __METHOD__
276 );
277 }
278
288 private function fetchBlob( $cluster, $id, $itemID ) {
295 static $externalBlobCache = [];
296
297 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
298 $cacheID = "$cacheID@{$this->dbDomain}";
299
300 if ( isset( $externalBlobCache[$cacheID] ) ) {
301 $this->logger->debug( __METHOD__ . ": cache hit on $cacheID" );
302
303 return $externalBlobCache[$cacheID];
304 }
305
306 $this->logger->debug( __METHOD__ . ": cache miss on $cacheID" );
307
308 $dbr = $this->getReplica( $cluster );
309 $ret = $dbr->newSelectQueryBuilder()
310 ->select( 'blob_text' )
311 ->from( $this->getTable( $dbr, $cluster ) )
312 ->where( [ 'blob_id' => $id ] )
313 ->caller( __METHOD__ )->fetchField();
314 if ( $ret === false ) {
315 // Try the primary DB
316 $this->logger->warning( __METHOD__ . ": primary DB fallback on $cacheID" );
317 $trxProfiler = $this->lbFactory->getTransactionProfiler();
318 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
319 $dbw = $this->getPrimary( $cluster );
320 $ret = $dbw->newSelectQueryBuilder()
321 ->select( 'blob_text' )
322 ->from( $this->getTable( $dbw, $cluster ) )
323 ->where( [ 'blob_id' => $id ] )
324 ->caller( __METHOD__ )->fetchField();
325 ScopedCallback::consume( $scope );
326 if ( $ret === false ) {
327 $this->logger->warning( __METHOD__ . ": primary DB failed to find $cacheID" );
328 }
329 }
330 if ( $itemID !== false && $ret !== false ) {
331 // Unserialise object; caller extracts item
332 $ret = HistoryBlobUtils::unserialize( $ret );
333 }
334
335 $externalBlobCache = [ $cacheID => $ret ];
336
337 return $ret;
338 }
339
348 private function batchFetchBlobs( $cluster, array $ids ) {
349 $dbr = $this->getReplica( $cluster );
350 $res = $dbr->newSelectQueryBuilder()
351 ->select( [ 'blob_id', 'blob_text' ] )
352 ->from( $this->getTable( $dbr, $cluster ) )
353 ->where( [ 'blob_id' => array_keys( $ids ) ] )
354 ->caller( __METHOD__ )
355 ->fetchResultSet();
356
357 $ret = [];
358 if ( $res !== false ) {
359 $this->mergeBatchResult( $ret, $ids, $res );
360 }
361 if ( $ids ) {
362 // Try the primary
363 $this->logger->info(
364 __METHOD__ . ": primary fallback on '$cluster' for: " .
365 implode( ',', array_keys( $ids ) )
366 );
367 $trxProfiler = $this->lbFactory->getTransactionProfiler();
368 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
369 $dbw = $this->getPrimary( $cluster );
370 $res = $dbw->newSelectQueryBuilder()
371 ->select( [ 'blob_id', 'blob_text' ] )
372 ->from( $this->getTable( $dbr, $cluster ) )
373 ->where( [ 'blob_id' => array_keys( $ids ) ] )
374 ->caller( __METHOD__ )
375 ->fetchResultSet();
376 ScopedCallback::consume( $scope );
377 if ( $res === false ) {
378 $this->logger->error( __METHOD__ . ": primary failed on '$cluster'" );
379 } else {
380 $this->mergeBatchResult( $ret, $ids, $res );
381 }
382 }
383 if ( $ids ) {
384 $this->logger->error(
385 __METHOD__ . ": primary on '$cluster' failed locating items: " .
386 implode( ',', array_keys( $ids ) )
387 );
388 }
389
390 return $ret;
391 }
392
399 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
400 foreach ( $res as $row ) {
401 $id = $row->blob_id;
402 $itemIDs = $ids[$id];
403 unset( $ids[$id] ); // to track if everything is found
404 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
405 // single result stored per blob
406 $ret[$id] = $row->blob_text;
407 } else {
408 // multi result stored per blob
409 $ret[$id] = HistoryBlobUtils::unserialize( $row->blob_text );
410 }
411 }
412 }
413
418 protected function parseURL( $url ) {
419 $path = explode( '/', $url );
420
421 return [
422 $path[2], // cluster
423 $path[3], // id
424 $path[4] ?? false // itemID
425 ];
426 }
427}
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:98
External storage in a SQL database.
getPrimary( $cluster)
Get a primary database connection for the specified cluster.
__construct(array $params)
getReplica( $cluster)
Get a replica DB connection for the specified cluster.
initializeTable( $cluster)
Create the appropriate blobs table on this cluster.
fetchFromURL( $url)
Fetch data from given external store URL.
getTable( $db, $cluster=null)
Get the 'blobs' table name for this database.
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.
array $params
Usage context options for this instance.
string $dbDomain
Default database domain to store content under.
static unserialize(string $str, bool $allowDouble=false)
Unserialize a HistoryBlob.
Helper class used for automatically re-using IDatabase connections and lazily establishing the actual...
Definition DBConnRef.php:36
Class to handle database/schema/prefix specifications for IDatabase.
Holds information on Query to be executed.
Definition Query.php:31
Base class for general text storage via the "object" flag in old_flags, or two-part external storage ...
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
This class is a delegate to ILBFactory for a given database cluster.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28