MediaWiki master
ExternalStoreDB.php
Go to the documentation of this file.
1<?php
8
10use InvalidArgumentException;
11use RuntimeException;
18use Wikimedia\ScopedCallback;
19
31 private $lbFactory;
32
38 public function __construct( array $params ) {
39 parent::__construct( $params );
40 if ( !isset( $params['lbFactory'] ) || !( $params['lbFactory'] instanceof LBFactory ) ) {
41 throw new InvalidArgumentException( "LBFactory required in 'lbFactory' field." );
42 }
43 $this->lbFactory = $params['lbFactory'];
44 }
45
56 public function fetchFromURL( $url ) {
57 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
58 $ret = $this->fetchBlob( $cluster, $id, $itemID );
59
60 if ( $itemID !== false && $ret !== false ) {
61 return $ret->getItem( $itemID );
62 }
63
64 return $ret;
65 }
66
77 public function batchFetchFromURLs( array $urls ) {
78 $batched = $inverseUrlMap = [];
79 foreach ( $urls as $url ) {
80 [ $cluster, $id, $itemID ] = $this->parseURL( $url );
81 $batched[$cluster][$id][] = $itemID;
82 // false $itemID gets cast to int, but should be ok
83 // since we do === from the $itemID in $batched
84 $inverseUrlMap[$cluster][$id][$itemID] = $url;
85 }
86 $ret = [];
87 foreach ( $batched as $cluster => $batchByCluster ) {
88 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
90 foreach ( $res as $id => $blob ) {
91 foreach ( $batchByCluster[$id] as $itemID ) {
92 $url = $inverseUrlMap[$cluster][$id][$itemID];
93 if ( $itemID === false ) {
94 $ret[$url] = $blob;
95 } else {
96 $ret[$url] = $blob->getItem( $itemID );
97 }
98 }
99 }
100 }
101
102 return $ret;
103 }
104
108 public function store( $location, $data ) {
109 $blobsTable = $this->getTable( $location );
110
111 $dbw = $this->getPrimary( $location );
112 $dbw->newInsertQueryBuilder()
113 ->insertInto( $blobsTable )
114 ->row( [ 'blob_text' => $data ] )
115 ->caller( __METHOD__ )->execute();
116
117 $id = $dbw->insertId();
118 if ( !$id ) {
119 throw new ExternalStoreException( __METHOD__ . ': no insert ID' );
120 }
121
122 return "DB://$location/$id";
123 }
124
128 public function isReadOnly( $location ) {
129 if ( parent::isReadOnly( $location ) ) {
130 return true;
131 }
132
133 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
134 }
135
142 private function getLoadBalancer( $cluster ) {
143 return $this->lbFactory->getExternalLB( $cluster );
144 }
145
153 public function getReplica( $cluster ) {
154 $lb = $this->getLoadBalancer( $cluster );
155
156 return $lb->getConnection(
158 [],
159 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
160 $lb::CONN_TRX_AUTOCOMMIT
161 );
162 }
163
171 public function getPrimary( $cluster ) {
172 $lb = $this->getLoadBalancer( $cluster );
173
174 return $lb->getMaintenanceConnectionRef(
176 [],
177 $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) ),
178 $lb::CONN_TRX_AUTOCOMMIT
179 );
180 }
181
186 private function getDomainId( array $server ) {
187 if ( $this->isDbDomainExplicit ) {
188 return $this->dbDomain; // explicit foreign domain
189 }
190
191 if ( isset( $server['dbname'] ) ) {
192 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
193 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
194 // domain, but rather assumed that the LB server configuration matched $wgDBname.
195 // This check is useful when the external storage DB for this cluster does not use
196 // the same name as the corresponding "main" DB(s) for wikis.
197 $domain = new DatabaseDomain(
198 $server['dbname'],
199 $server['schema'] ?? null,
200 $server['tablePrefix'] ?? ''
201 );
202
203 return $domain->getId();
204 }
205
206 return false; // local LB domain
207 }
208
219 public function getTable( string $cluster ) {
220 $lb = $this->getLoadBalancer( $cluster );
221 $info = $lb->getServerInfo( ServerInfo::WRITER_INDEX );
222
223 return $info['blobs table'] ?? 'blobs';
224 }
225
232 public function initializeTable( $cluster ) {
233 global $IP;
234
235 static $supportedTypes = [ 'mysql', 'sqlite' ];
236
237 $dbw = $this->getPrimary( $cluster );
238 if ( !in_array( $dbw->getType(), $supportedTypes, true ) ) {
239 throw new DBUnexpectedError( $dbw, "RDBMS type '{$dbw->getType()}' not supported." );
240 }
241
242 $sqlFilePath = "$IP/maintenance/storage/blobs.sql";
243 $sql = file_get_contents( $sqlFilePath );
244 if ( $sql === false ) {
245 throw new RuntimeException( "Failed to read '$sqlFilePath'." );
246 }
247
248 $blobsTable = $this->getTable( $cluster );
249 $encTable = $dbw->tableName( $blobsTable );
250 $sqlWithReplacedVars = str_replace(
251 [ '/*$wgDBprefix*/blobs', '/*_*/blobs' ],
252 [ $encTable, $encTable ],
253 $sql
254 );
255
256 $dbw->query(
257 new Query(
258 $sqlWithReplacedVars,
259 $dbw::QUERY_CHANGE_SCHEMA,
260 'CREATE',
261 $blobsTable,
262 $sqlWithReplacedVars
263 ),
264 __METHOD__
265 );
266 }
267
277 private function fetchBlob( $cluster, $id, $itemID ) {
284 static $externalBlobCache = [];
285
286 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
287 $cacheID = "$cacheID@{$this->dbDomain}";
288
289 if ( isset( $externalBlobCache[$cacheID] ) ) {
290 $this->logger->debug( __METHOD__ . ": cache hit on $cacheID" );
291
292 return $externalBlobCache[$cacheID];
293 }
294
295 $this->logger->debug( __METHOD__ . ": cache miss on $cacheID" );
296
297 $blobsTable = $this->getTable( $cluster );
298
299 $dbr = $this->getReplica( $cluster );
300 $ret = $dbr->newSelectQueryBuilder()
301 ->select( 'blob_text' )
302 ->from( $blobsTable )
303 ->where( [ 'blob_id' => $id ] )
304 ->caller( __METHOD__ )->fetchField();
305
306 if ( $ret === false ) {
307 // Try the primary DB
308 $this->logger->warning( __METHOD__ . ": primary DB fallback on $cacheID" );
309 $trxProfiler = $this->lbFactory->getTransactionProfiler();
310 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
311 $dbw = $this->getPrimary( $cluster );
312 $ret = $dbw->newSelectQueryBuilder()
313 ->select( 'blob_text' )
314 ->from( $blobsTable )
315 ->where( [ 'blob_id' => $id ] )
316 ->caller( __METHOD__ )->fetchField();
317 ScopedCallback::consume( $scope );
318 if ( $ret === false ) {
319 $this->logger->warning( __METHOD__ . ": primary DB failed to find $cacheID" );
320 }
321 }
322 if ( $itemID !== false && $ret !== false ) {
323 // Unserialise object; caller extracts item
324 $ret = HistoryBlobUtils::unserialize( $ret );
325 }
326
327 $externalBlobCache = [ $cacheID => $ret ];
328
329 return $ret;
330 }
331
340 private function batchFetchBlobs( $cluster, array $ids ) {
341 $blobsTable = $this->getTable( $cluster );
342
343 $dbr = $this->getReplica( $cluster );
344 $res = $dbr->newSelectQueryBuilder()
345 ->select( [ 'blob_id', 'blob_text' ] )
346 ->from( $blobsTable )
347 ->where( [ 'blob_id' => array_keys( $ids ) ] )
348 ->caller( __METHOD__ )
349 ->fetchResultSet();
350
351 $ret = [];
352 $this->mergeBatchResult( $ret, $ids, $res );
353 if ( $ids ) {
354 // Try the primary
355 $this->logger->info(
356 __METHOD__ . ": primary fallback on '$cluster' for: " .
357 implode( ',', array_keys( $ids ) )
358 );
359 $trxProfiler = $this->lbFactory->getTransactionProfiler();
360 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
361 $dbw = $this->getPrimary( $cluster );
362 $res = $dbw->newSelectQueryBuilder()
363 ->select( [ 'blob_id', 'blob_text' ] )
364 ->from( $blobsTable )
365 ->where( [ 'blob_id' => array_keys( $ids ) ] )
366 ->caller( __METHOD__ )
367 ->fetchResultSet();
368 ScopedCallback::consume( $scope );
369 $this->mergeBatchResult( $ret, $ids, $res );
370 }
371 if ( $ids ) {
372 $this->logger->error(
373 __METHOD__ . ": primary on '$cluster' failed locating items: " .
374 implode( ',', array_keys( $ids ) )
375 );
376 }
377
378 return $ret;
379 }
380
387 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
388 foreach ( $res as $row ) {
389 $id = $row->blob_id;
390 $itemIDs = $ids[$id];
391 unset( $ids[$id] ); // to track if everything is found
392 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
393 // single result stored per blob
394 $ret[$id] = $row->blob_text;
395 } else {
396 // multi result stored per blob
397 $ret[$id] = HistoryBlobUtils::unserialize( $row->blob_text );
398 }
399 }
400 }
401
406 protected function parseURL( $url ) {
407 $path = explode( '/', $url );
408
409 return [
410 $path[2], // cluster
411 $path[3], // id
412 $path[4] ?? false // itemID
413 ];
414 }
415
423 public function getClusterForUrl( $url ) {
424 $parts = explode( '/', $url );
425 return $parts[2] ?? null;
426 }
427
435 public function getDomainIdForCluster( $cluster ) {
436 $lb = $this->getLoadBalancer( $cluster );
437 return $this->getDomainId( $lb->getServerInfo( ServerInfo::WRITER_INDEX ) );
438 }
439}
440
442class_alias( ExternalStoreDB::class, 'ExternalStoreDB' );
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
if(!defined('MEDIAWIKI')) if(!defined( 'MW_ENTRY_POINT')) $IP
Environment checks.
Definition Setup.php:103
static unserialize(string $str, bool $allowDouble=false)
Unserialize a HistoryBlob.
External storage in a SQL database.
initializeTable( $cluster)
Create the appropriate blobs table on this cluster.
getReplica( $cluster)
Get a replica DB connection for the specified cluster.
getTable(string $cluster)
Get the configured blobs table name for this database.
isReadOnly( $location)
Check if a given location is read-only.bool Whether this location is read-only 1.31
getClusterForUrl( $url)
Get the cluster part of a URL.
getPrimary( $cluster)
Get a primary database connection for the specified cluster.
batchFetchFromURLs(array $urls)
Fetch multiple URLs from given external store.
store( $location, $data)
Insert a data item into a given location.string|bool The URL of the stored data item,...
fetchFromURL( $url)
Fetch data from given external store URL.
getDomainIdForCluster( $cluster)
Get the domain ID for a given cluster, which is false for the local wiki ID.
string $dbDomain
Default database domain to store content under.
array $params
Usage context options for this instance.
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.