MediaWiki REL1_39
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 list( $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 list( $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->insert(
120 $this->getTable( $dbw, $location ),
121 [ 'blob_text' => $data ],
122 __METHOD__
123 );
124 $id = $dbw->insertId();
125 if ( !$id ) {
126 throw new MWException( __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 $lb = $this->getLoadBalancer( $location );
141 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
142
143 return ( $lb->getReadOnlyReason( $domainId ) !== false );
144 }
145
152 private function getLoadBalancer( $cluster ) {
153 return $this->lbFactory->getExternalLB( $cluster );
154 }
155
163 public function getReplica( $cluster ) {
164 $lb = $this->getLoadBalancer( $cluster );
165
166 return $lb->getConnectionRef(
168 [],
169 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
170 $lb::CONN_TRX_AUTOCOMMIT
171 );
172 }
173
181 public function getPrimary( $cluster ) {
182 $lb = $this->getLoadBalancer( $cluster );
183
184 return $lb->getMaintenanceConnectionRef(
186 [],
187 $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) ),
188 $lb::CONN_TRX_AUTOCOMMIT
189 );
190 }
191
197 public function getMaster( $cluster ) {
198 wfDeprecated( __METHOD__, '1.37' );
199 return $this->getPrimary( $cluster );
200 }
201
206 private function getDomainId( array $server ) {
207 if ( $this->isDbDomainExplicit ) {
208 return $this->dbDomain; // explicit foreign domain
209 }
210
211 if ( isset( $server['dbname'] ) ) {
212 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
213 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
214 // domain, but rather assumed that the LB server configuration matched $wgDBname.
215 // This check is useful when the external storage DB for this cluster does not use
216 // the same name as the corresponding "main" DB(s) for wikis.
217 $domain = new DatabaseDomain(
218 $server['dbname'],
219 $server['schema'] ?? null,
220 $server['tablePrefix'] ?? ''
221 );
222
223 return $domain->getId();
224 }
225
226 return false; // local LB domain
227 }
228
236 public function getTable( $db, $cluster = null ) {
237 if ( $cluster !== null ) {
238 $lb = $this->getLoadBalancer( $cluster );
239 $info = $lb->getServerInfo( $lb->getWriterIndex() );
240 if ( isset( $info['blobs table'] ) ) {
241 return $info['blobs table'];
242 }
243 }
244
245 return $db->getLBInfo( 'blobs table' ) ?? 'blobs'; // b/c
246 }
247
255 public function initializeTable( $cluster ) {
256 global $IP;
257
258 static $supportedTypes = [ 'mysql', 'sqlite' ];
259
260 $dbw = $this->getPrimary( $cluster );
261 if ( !in_array( $dbw->getType(), $supportedTypes, true ) ) {
262 throw new DBUnexpectedError( $dbw, "RDBMS type '{$dbw->getType()}' not supported." );
263 }
264
265 $sqlFilePath = "$IP/maintenance/storage/blobs.sql";
266 $sql = file_get_contents( $sqlFilePath );
267 if ( $sql === false ) {
268 throw new RuntimeException( "Failed to read '$sqlFilePath'." );
269 }
270
271 $rawTable = $this->getTable( $dbw, $cluster ); // e.g. "blobs_cluster23"
272 $encTable = $dbw->tableName( $rawTable );
273 $dbw->query(
274 str_replace(
275 [ '/*$wgDBprefix*/blobs', '/*_*/blobs' ],
276 [ $encTable, $encTable ],
277 $sql
278 ),
279 __METHOD__,
280 $dbw::QUERY_IGNORE_DBO_TRX
281 );
282 }
283
293 private function fetchBlob( $cluster, $id, $itemID ) {
300 static $externalBlobCache = [];
301
302 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
303 $cacheID = "$cacheID@{$this->dbDomain}";
304
305 if ( isset( $externalBlobCache[$cacheID] ) ) {
306 $this->logger->debug( __METHOD__ . ": cache hit on $cacheID" );
307
308 return $externalBlobCache[$cacheID];
309 }
310
311 $this->logger->debug( __METHOD__ . ": cache miss on $cacheID" );
312
313 $dbr = $this->getReplica( $cluster );
314 $ret = $dbr->selectField(
315 $this->getTable( $dbr, $cluster ),
316 'blob_text',
317 [ 'blob_id' => $id ],
318 __METHOD__
319 );
320 if ( $ret === false ) {
321 // Try the primary DB
322 $this->logger->warning( __METHOD__ . ": primary DB fallback on $cacheID" );
323 $scope = $this->lbFactory->getTransactionProfiler()->silenceForScope();
324 $dbw = $this->getPrimary( $cluster );
325 $ret = $dbw->selectField(
326 $this->getTable( $dbw, $cluster ),
327 'blob_text',
328 [ 'blob_id' => $id ],
329 __METHOD__
330 );
331 ScopedCallback::consume( $scope );
332 if ( $ret === false ) {
333 $this->logger->warning( __METHOD__ . ": primary DB failed to find $cacheID" );
334 }
335 }
336 if ( $itemID !== false && $ret !== false ) {
337 // Unserialise object; caller extracts item
338 $ret = unserialize( $ret );
339 }
340
341 $externalBlobCache = [ $cacheID => $ret ];
342
343 return $ret;
344 }
345
354 private function batchFetchBlobs( $cluster, array $ids ) {
355 $dbr = $this->getReplica( $cluster );
356 $res = $dbr->newSelectQueryBuilder()
357 ->select( [ 'blob_id', 'blob_text' ] )
358 ->from( $this->getTable( $dbr, $cluster ) )
359 ->where( [ 'blob_id' => array_keys( $ids ) ] )
360 ->caller( __METHOD__ )
361 ->fetchResultSet();
362
363 $ret = [];
364 if ( $res !== false ) {
365 $this->mergeBatchResult( $ret, $ids, $res );
366 }
367 if ( $ids ) {
368 // Try the primary
369 $this->logger->info(
370 __METHOD__ . ": primary fallback on '$cluster' for: " .
371 implode( ',', array_keys( $ids ) )
372 );
373 $scope = $this->lbFactory->getTransactionProfiler()->silenceForScope();
374 $dbw = $this->getPrimary( $cluster );
375 $res = $dbw->newSelectQueryBuilder()
376 ->select( [ 'blob_id', 'blob_text' ] )
377 ->from( $this->getTable( $dbr, $cluster ) )
378 ->where( [ 'blob_id' => array_keys( $ids ) ] )
379 ->caller( __METHOD__ )
380 ->fetchResultSet();
381 ScopedCallback::consume( $scope );
382 if ( $res === false ) {
383 $this->logger->error( __METHOD__ . ": primary failed on '$cluster'" );
384 } else {
385 $this->mergeBatchResult( $ret, $ids, $res );
386 }
387 }
388 if ( $ids ) {
389 $this->logger->error(
390 __METHOD__ . ": primary on '$cluster' failed locating items: " .
391 implode( ',', array_keys( $ids ) )
392 );
393 }
394
395 return $ret;
396 }
397
404 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
405 foreach ( $res as $row ) {
406 $id = $row->blob_id;
407 $itemIDs = $ids[$id];
408 unset( $ids[$id] ); // to track if everything is found
409 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
410 // single result stored per blob
411 $ret[$id] = $row->blob_text;
412 } else {
413 // multi result stored per blob
414 $ret[$id] = unserialize( $row->blob_text );
415 }
416 }
417 }
418
423 protected function parseURL( $url ) {
424 $path = explode( '/', $url );
425
426 return [
427 $path[2], // cluster
428 $path[3], // id
429 $path[4] ?? false // itemID
430 ];
431 }
432}
unserialize( $serialized)
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:91
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.
MediaWiki exception.
Helper class used for automatically marking an IDatabase connection as reusable (once it no longer ma...
Definition DBConnRef.php:29
Class to handle database/schema/prefix specifications for IDatabase.
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:39
Create and track the database connections and transactions for a given database cluster.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28