MediaWiki  1.33.0
ExternalStoreDB.php
Go to the documentation of this file.
1 <?php
29 
47  public function fetchFromURL( $url ) {
48  list( $cluster, $id, $itemID ) = $this->parseURL( $url );
49  $ret = $this->fetchBlob( $cluster, $id, $itemID );
50 
51  if ( $itemID !== false && $ret !== false ) {
52  return $ret->getItem( $itemID );
53  }
54 
55  return $ret;
56  }
57 
67  public function batchFetchFromURLs( array $urls ) {
68  $batched = $inverseUrlMap = [];
69  foreach ( $urls as $url ) {
70  list( $cluster, $id, $itemID ) = $this->parseURL( $url );
71  $batched[$cluster][$id][] = $itemID;
72  // false $itemID gets cast to int, but should be ok
73  // since we do === from the $itemID in $batched
74  $inverseUrlMap[$cluster][$id][$itemID] = $url;
75  }
76  $ret = [];
77  foreach ( $batched as $cluster => $batchByCluster ) {
78  $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
80  foreach ( $res as $id => $blob ) {
81  foreach ( $batchByCluster[$id] as $itemID ) {
82  $url = $inverseUrlMap[$cluster][$id][$itemID];
83  if ( $itemID === false ) {
84  $ret[$url] = $blob;
85  } else {
86  $ret[$url] = $blob->getItem( $itemID );
87  }
88  }
89  }
90  }
91 
92  return $ret;
93  }
94 
95  public function store( $location, $data ) {
96  $dbw = $this->getMaster( $location );
97  $dbw->insert( $this->getTable( $dbw ),
98  [ 'blob_text' => $data ],
99  __METHOD__ );
100  $id = $dbw->insertId();
101  if ( !$id ) {
102  throw new MWException( __METHOD__ . ': no insert ID' );
103  }
104 
105  return "DB://$location/$id";
106  }
107 
108  public function isReadOnly( $location ) {
109  $lb = $this->getLoadBalancer( $location );
110  $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
111  return ( $lb->getReadOnlyReason( $domainId ) !== false );
112  }
113 
120  private function getLoadBalancer( $cluster ) {
121  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
122  return $lbFactory->getExternalLB( $cluster );
123  }
124 
131  public function getSlave( $cluster ) {
133 
134  $lb = $this->getLoadBalancer( $cluster );
135  $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
136 
137  if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
138  wfDebug( "read only external store\n" );
139  $lb->allowLagged( true );
140  } else {
141  wfDebug( "writable external store\n" );
142  }
143 
144  $db = $lb->getConnectionRef( DB_REPLICA, [], $domainId );
145  $db->clearFlag( DBO_TRX ); // sanity
146 
147  return $db;
148  }
149 
156  public function getMaster( $cluster ) {
157  $lb = $this->getLoadBalancer( $cluster );
158  $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
159 
160  $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $domainId );
161  $db->clearFlag( DBO_TRX ); // sanity
162 
163  return $db;
164  }
165 
170  private function getDomainId( array $server ) {
171  if ( isset( $this->params['wiki'] ) && $this->params['wiki'] !== false ) {
172  return $this->params['wiki']; // explicit domain
173  }
174 
175  if ( isset( $server['dbname'] ) ) {
176  // T200471: for b/c, treat any "dbname" field as forcing which database to use.
177  // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
178  // domain, but rather assumed that the LB server configuration matched $wgDBname.
179  // This check is useful when the external storage DB for this cluster does not use
180  // the same name as the corresponding "main" DB(s) for wikis.
181  $domain = new DatabaseDomain(
182  $server['dbname'],
183  $server['schema'] ?? null,
184  $server['tablePrefix'] ?? ''
185  );
186 
187  return $domain->getId();
188  }
189 
190  return false; // local LB domain
191  }
192 
199  public function getTable( $db ) {
200  $table = $db->getLBInfo( 'blobs table' );
201  if ( is_null( $table ) ) {
202  $table = 'blobs';
203  }
204 
205  return $table;
206  }
207 
217  private function fetchBlob( $cluster, $id, $itemID ) {
224  static $externalBlobCache = [];
225 
226  $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
227 
228  $wiki = $this->params['wiki'] ?? false;
229  $cacheID = ( $wiki === false ) ? $cacheID : "$cacheID@$wiki";
230 
231  if ( isset( $externalBlobCache[$cacheID] ) ) {
232  wfDebugLog( 'ExternalStoreDB-cache',
233  "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
234 
235  return $externalBlobCache[$cacheID];
236  }
237 
238  wfDebugLog( 'ExternalStoreDB-cache',
239  "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
240 
241  $dbr = $this->getSlave( $cluster );
242  $ret = $dbr->selectField( $this->getTable( $dbr ),
243  'blob_text', [ 'blob_id' => $id ], __METHOD__ );
244  if ( $ret === false ) {
245  wfDebugLog( 'ExternalStoreDB',
246  "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
247  // Try the master
248  $dbw = $this->getMaster( $cluster );
249  $ret = $dbw->selectField( $this->getTable( $dbw ),
250  'blob_text', [ 'blob_id' => $id ], __METHOD__ );
251  if ( $ret === false ) {
252  wfDebugLog( 'ExternalStoreDB',
253  "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
254  }
255  }
256  if ( $itemID !== false && $ret !== false ) {
257  // Unserialise object; caller extracts item
258  $ret = unserialize( $ret );
259  }
260 
261  $externalBlobCache = [ $cacheID => $ret ];
262 
263  return $ret;
264  }
265 
274  private function batchFetchBlobs( $cluster, array $ids ) {
275  $dbr = $this->getSlave( $cluster );
276  $res = $dbr->select( $this->getTable( $dbr ),
277  [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
278  $ret = [];
279  if ( $res !== false ) {
280  $this->mergeBatchResult( $ret, $ids, $res );
281  }
282  if ( $ids ) {
283  wfDebugLog( __CLASS__, __METHOD__ .
284  " master fallback on '$cluster' for: " .
285  implode( ',', array_keys( $ids ) ) );
286  // Try the master
287  $dbw = $this->getMaster( $cluster );
288  $res = $dbw->select( $this->getTable( $dbr ),
289  [ 'blob_id', 'blob_text' ],
290  [ 'blob_id' => array_keys( $ids ) ],
291  __METHOD__ );
292  if ( $res === false ) {
293  wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
294  } else {
295  $this->mergeBatchResult( $ret, $ids, $res );
296  }
297  }
298  if ( $ids ) {
299  wfDebugLog( __CLASS__, __METHOD__ .
300  " master on '$cluster' failed locating items: " .
301  implode( ',', array_keys( $ids ) ) );
302  }
303 
304  return $ret;
305  }
306 
313  private function mergeBatchResult( array &$ret, array &$ids, $res ) {
314  foreach ( $res as $row ) {
315  $id = $row->blob_id;
316  $itemIDs = $ids[$id];
317  unset( $ids[$id] ); // to track if everything is found
318  if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
319  // single result stored per blob
320  $ret[$id] = $row->blob_text;
321  } else {
322  // multi result stored per blob
323  $ret[$id] = unserialize( $row->blob_text );
324  }
325  }
326  }
327 
332  protected function parseURL( $url ) {
333  $path = explode( '/', $url );
334 
335  return [
336  $path[2], // cluster
337  $path[3], // id
338  $path[4] ?? false // itemID
339  ];
340  }
341 }
ExternalStoreDB\batchFetchBlobs
batchFetchBlobs( $cluster, array $ids)
Fetch multiple blob items out of the database.
Definition: ExternalStoreDB.php:274
ExternalStoreMedium
Accessable external objects in a particular storage medium.
Definition: ExternalStoreMedium.php:30
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
ExternalStoreDB\getSlave
getSlave( $cluster)
Get a replica DB connection for the specified cluster.
Definition: ExternalStoreDB.php:131
ExternalStoreDB\parseURL
parseURL( $url)
Definition: ExternalStoreDB.php:332
ExternalStoreDB
DB accessible external objects.
Definition: ExternalStoreDB.php:38
ExternalStoreDB\store
store( $location, $data)
Insert a data item into a given location.
Definition: ExternalStoreDB.php:95
captcha-old.count
count
Definition: captcha-old.py:249
ExternalStoreDB\batchFetchFromURLs
batchFetchFromURLs(array $urls)
Fetch data from given external store URLs.
Definition: ExternalStoreDB.php:67
$res
$res
Definition: database.txt:21
$wgDefaultExternalStore
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
Definition: DefaultSettings.php:2236
ExternalStoreDB\fetchBlob
fetchBlob( $cluster, $id, $itemID)
Fetch a blob item out of the database; a cache of the last-loaded blob will be kept so that multiple ...
Definition: ExternalStoreDB.php:217
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1043
DBO_TRX
const DBO_TRX
Definition: defines.php:12
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
ExternalStoreDB\getDomainId
getDomainId(array $server)
Definition: ExternalStoreDB.php:170
$dbr
$dbr
Definition: testCompression.php:50
Wikimedia\Rdbms\MaintainableDBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: MaintainableDBConnRef.php:13
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
ExternalStoreDB\getLoadBalancer
getLoadBalancer( $cluster)
Get a LoadBalancer for the specified cluster.
Definition: ExternalStoreDB.php:120
MWException
MediaWiki exception.
Definition: MWException.php:26
$blob
$blob
Definition: testCompression.php:65
ExternalStoreDB\isReadOnly
isReadOnly( $location)
Check if a given location is read-only.
Definition: ExternalStoreDB.php:108
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:949
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
ExternalStoreDB\getTable
getTable( $db)
Get the 'blobs' table name for this database.
Definition: ExternalStoreDB.php:199
ExternalStoreDB\fetchFromURL
fetchFromURL( $url)
The provided URL is in the form of DB://cluster/id or DB://cluster/id/itemid for concatened storage.
Definition: ExternalStoreDB.php:47
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1985
Wikimedia\Rdbms\DBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: DBConnRef.php:14
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:142
$path
$path
Definition: NoLocalSettings.php:25
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/prefix specification for IDatabase domains.
Definition: DatabaseDomain.php:28
ExternalStoreDB\mergeBatchResult
mergeBatchResult(array &$ret, array &$ids, $res)
Helper function for self::batchFetchBlobs for merging master/replica DB results.
Definition: ExternalStoreDB.php:313
ExternalStoreDB\getMaster
getMaster( $cluster)
Get a master database connection for the specified cluster.
Definition: ExternalStoreDB.php:156
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:78