MediaWiki master
ExternalStoreDB.php
Go to the documentation of this file.
1<?php
27use Wikimedia\ScopedCallback;
28
40 private $lbFactory;
41
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." );
51 }
52 $this->lbFactory = $params['lbFactory'];
53 }
54
65 public function fetchFromURL( $url ) {
66 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
67 $ret = $this->fetchBlob( $cluster, $id, $itemID );
68
69 if ( $itemID !== false && $ret !== false ) {
70 return $ret->getItem( $itemID );
71 }
72
73 return $ret;
74 }
75
86 public function batchFetchFromURLs( array $urls ) {
87 $batched = $inverseUrlMap = [];
88 foreach ( $urls as $url ) {
89 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
90 $batched[$cluster][$id][] = $itemID;
91 // false $itemID gets cast to int, but should be ok
92 // since we do === from the $itemID in $batched
93 $inverseUrlMap[$cluster][$id][$itemID] = $url;
94 }
95 $ret = [];
96 foreach ( $batched as $cluster => $batchByCluster ) {
97 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
99 foreach ( $res as $id => $blob ) {
100 foreach ( $batchByCluster[$id] as $itemID ) {
101 $url = $inverseUrlMap[$cluster][$id][$itemID];
102 if ( $itemID === false ) {
103 $ret[$url] = $blob;
104 } else {
105 $ret[$url] = $blob->getItem( $itemID );
106 }
107 }
108 }
109 }
110
111 return $ret;
112 }
113
117 public function store( $location, $data ) {
118 $dbw = $this->getPrimary( $location );
119 $dbw->newInsertQueryBuilder()
120 ->insertInto( $this->getTable( $dbw, $location ) )
121 ->row( [ 'blob_text' => $data ] )
122 ->caller( __METHOD__ )->execute();
123 $id = $dbw->insertId();
124 if ( !$id ) {
125 throw new ExternalStoreException( __METHOD__ . ': no insert ID' );
126 }
127
128 return "DB://$location/$id";
129 }
130
134 public function isReadOnly( $location ) {
135 if ( parent::isReadOnly( $location ) ) {
136 return true;
137 }
138
139 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
140 }
141
148 private function getLoadBalancer( $cluster ) {
149 return $this->lbFactory->getExternalLB( $cluster );
150 }
151
159 public function getReplica( $cluster ) {
160 $lb = $this->getLoadBalancer( $cluster );
161
162 return $lb->getConnection(
164 [],
165 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
166 $lb::CONN_TRX_AUTOCOMMIT
167 );
168 }
169
177 public function getPrimary( $cluster ) {
178 $lb = $this->getLoadBalancer( $cluster );
179
180 return $lb->getMaintenanceConnectionRef(
182 [],
183 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
184 $lb::CONN_TRX_AUTOCOMMIT
185 );
186 }
187
192 private function getDomainId( array $server ) {
193 if ( $this->isDbDomainExplicit ) {
194 return $this->dbDomain; // explicit foreign domain
195 }
196
197 if ( isset( $server['dbname'] ) ) {
198 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
199 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
200 // domain, but rather assumed that the LB server configuration matched $wgDBname.
201 // This check is useful when the external storage DB for this cluster does not use
202 // the same name as the corresponding "main" DB(s) for wikis.
203 $domain = new DatabaseDomain(
204 $server['dbname'],
205 $server['schema'] ?? null,
206 $server['tablePrefix'] ?? ''
207 );
208
209 return $domain->getId();
210 }
211
212 return false; // local LB domain
213 }
214
222 public function getTable( $db, $cluster = null ) {
223 if ( $cluster !== null ) {
224 $lb = $this->getLoadBalancer( $cluster );
225 $info = $lb->getServerInfo( ServerInfo::WRITER_INDEX );
226 if ( isset( $info['blobs table'] ) ) {
227 return $info['blobs table'];
228 }
229 }
230
231 return 'blobs';
232 }
233
241 public function initializeTable( $cluster ) {
242 global $IP;
243
244 static $supportedTypes = [ 'mysql', 'sqlite' ];
245
246 $dbw = $this->getPrimary( $cluster );
247 if ( !in_array( $dbw->getType(), $supportedTypes, true ) ) {
248 throw new DBUnexpectedError( $dbw, "RDBMS type '{$dbw->getType()}' not supported." );
249 }
250
251 $sqlFilePath = "$IP/maintenance/storage/blobs.sql";
252 $sql = file_get_contents( $sqlFilePath );
253 if ( $sql === false ) {
254 throw new RuntimeException( "Failed to read '$sqlFilePath'." );
255 }
256
257 $rawTable = $this->getTable( $dbw, $cluster ); // e.g. "blobs_cluster23"
258 $encTable = $dbw->tableName( $rawTable );
259
260 $sqlWithReplacedVars = str_replace(
261 [ '/*$wgDBprefix*/blobs', '/*_*/blobs' ],
262 [ $encTable, $encTable ],
263 $sql
264 );
265
266 $dbw->query(
267 new Query(
268 $sqlWithReplacedVars,
269 $dbw::QUERY_CHANGE_SCHEMA,
270 'CREATE',
271 $rawTable,
272 $sqlWithReplacedVars
273 ),
274 __METHOD__
275 );
276 }
277
287 private function fetchBlob( $cluster, $id, $itemID ) {
294 static $externalBlobCache = [];
295
296 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
297 $cacheID = "$cacheID@{$this->dbDomain}";
298
299 if ( isset( $externalBlobCache[$cacheID] ) ) {
300 $this->logger->debug( __METHOD__ . ": cache hit on $cacheID" );
301
302 return $externalBlobCache[$cacheID];
303 }
304
305 $this->logger->debug( __METHOD__ . ": cache miss on $cacheID" );
306
307 $dbr = $this->getReplica( $cluster );
308 $ret = $dbr->newSelectQueryBuilder()
309 ->select( 'blob_text' )
310 ->from( $this->getTable( $dbr, $cluster ) )
311 ->where( [ 'blob_id' => $id ] )
312 ->caller( __METHOD__ )->fetchField();
313 if ( $ret === false ) {
314 // Try the primary DB
315 $this->logger->warning( __METHOD__ . ": primary DB fallback on $cacheID" );
316 $trxProfiler = $this->lbFactory->getTransactionProfiler();
317 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
318 $dbw = $this->getPrimary( $cluster );
319 $ret = $dbw->newSelectQueryBuilder()
320 ->select( 'blob_text' )
321 ->from( $this->getTable( $dbw, $cluster ) )
322 ->where( [ 'blob_id' => $id ] )
323 ->caller( __METHOD__ )->fetchField();
324 ScopedCallback::consume( $scope );
325 if ( $ret === false ) {
326 $this->logger->warning( __METHOD__ . ": primary DB failed to find $cacheID" );
327 }
328 }
329 if ( $itemID !== false && $ret !== false ) {
330 // Unserialise object; caller extracts item
331 $ret = HistoryBlobUtils::unserialize( $ret );
332 }
333
334 $externalBlobCache = [ $cacheID => $ret ];
335
336 return $ret;
337 }
338
347 private function batchFetchBlobs( $cluster, array $ids ) {
348 $dbr = $this->getReplica( $cluster );
349 $res = $dbr->newSelectQueryBuilder()
350 ->select( [ 'blob_id', 'blob_text' ] )
351 ->from( $this->getTable( $dbr, $cluster ) )
352 ->where( [ 'blob_id' => array_keys( $ids ) ] )
353 ->caller( __METHOD__ )
354 ->fetchResultSet();
355
356 $ret = [];
357 $this->mergeBatchResult( $ret, $ids, $res );
358 if ( $ids ) {
359 // Try the primary
360 $this->logger->info(
361 __METHOD__ . ": primary fallback on '$cluster' for: " .
362 implode( ',', array_keys( $ids ) )
363 );
364 $trxProfiler = $this->lbFactory->getTransactionProfiler();
365 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
366 $dbw = $this->getPrimary( $cluster );
367 $res = $dbw->newSelectQueryBuilder()
368 ->select( [ 'blob_id', 'blob_text' ] )
369 ->from( $this->getTable( $dbr, $cluster ) )
370 ->where( [ 'blob_id' => array_keys( $ids ) ] )
371 ->caller( __METHOD__ )
372 ->fetchResultSet();
373 ScopedCallback::consume( $scope );
374 $this->mergeBatchResult( $ret, $ids, $res );
375 }
376 if ( $ids ) {
377 $this->logger->error(
378 __METHOD__ . ": primary on '$cluster' failed locating items: " .
379 implode( ',', array_keys( $ids ) )
380 );
381 }
382
383 return $ret;
384 }
385
392 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
393 foreach ( $res as $row ) {
394 $id = $row->blob_id;
395 $itemIDs = $ids[$id];
396 unset( $ids[$id] ); // to track if everything is found
397 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
398 // single result stored per blob
399 $ret[$id] = $row->blob_text;
400 } else {
401 // multi result stored per blob
402 $ret[$id] = HistoryBlobUtils::unserialize( $row->blob_text );
403 }
404 }
405 }
406
411 protected function parseURL( $url ) {
412 $path = explode( '/', $url );
413
414 return [
415 $path[2], // cluster
416 $path[3], // id
417 $path[4] ?? false // itemID
418 ];
419 }
420}
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:100
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.
Class to handle database/schema/prefix specifications for IDatabase.
Holds information on Query to be executed.
Definition Query.php:31
Information about an individual database host.
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.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28