MediaWiki  1.31.0
ExternalStoreDB.php
Go to the documentation of this file.
1 <?php
28 
46  public function fetchFromURL( $url ) {
47  list( $cluster, $id, $itemID ) = $this->parseURL( $url );
48  $ret = $this->fetchBlob( $cluster, $id, $itemID );
49 
50  if ( $itemID !== false && $ret !== false ) {
51  return $ret->getItem( $itemID );
52  }
53 
54  return $ret;
55  }
56 
66  public function batchFetchFromURLs( array $urls ) {
67  $batched = $inverseUrlMap = [];
68  foreach ( $urls as $url ) {
69  list( $cluster, $id, $itemID ) = $this->parseURL( $url );
70  $batched[$cluster][$id][] = $itemID;
71  // false $itemID gets cast to int, but should be ok
72  // since we do === from the $itemID in $batched
73  $inverseUrlMap[$cluster][$id][$itemID] = $url;
74  }
75  $ret = [];
76  foreach ( $batched as $cluster => $batchByCluster ) {
77  $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
79  foreach ( $res as $id => $blob ) {
80  foreach ( $batchByCluster[$id] as $itemID ) {
81  $url = $inverseUrlMap[$cluster][$id][$itemID];
82  if ( $itemID === false ) {
83  $ret[$url] = $blob;
84  } else {
85  $ret[$url] = $blob->getItem( $itemID );
86  }
87  }
88  }
89  }
90 
91  return $ret;
92  }
93 
94  public function store( $location, $data ) {
95  $dbw = $this->getMaster( $location );
96  $dbw->insert( $this->getTable( $dbw ),
97  [ 'blob_text' => $data ],
98  __METHOD__ );
99  $id = $dbw->insertId();
100  if ( !$id ) {
101  throw new MWException( __METHOD__ . ': no insert ID' );
102  }
103 
104  return "DB://$location/$id";
105  }
106 
107  public function isReadOnly( $location ) {
108  return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
109  }
110 
117  private function getLoadBalancer( $cluster ) {
118  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
119  return $lbFactory->getExternalLB( $cluster );
120  }
121 
128  public function getSlave( $cluster ) {
130 
131  $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
132  $lb = $this->getLoadBalancer( $cluster );
133 
134  if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
135  wfDebug( "read only external store\n" );
136  $lb->allowLagged( true );
137  } else {
138  wfDebug( "writable external store\n" );
139  }
140 
141  $db = $lb->getConnectionRef( DB_REPLICA, [], $wiki );
142  $db->clearFlag( DBO_TRX ); // sanity
143 
144  return $db;
145  }
146 
153  public function getMaster( $cluster ) {
154  $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
155  $lb = $this->getLoadBalancer( $cluster );
156 
157  $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $wiki );
158  $db->clearFlag( DBO_TRX ); // sanity
159 
160  return $db;
161  }
162 
169  public function getTable( $db ) {
170  $table = $db->getLBInfo( 'blobs table' );
171  if ( is_null( $table ) ) {
172  $table = 'blobs';
173  }
174 
175  return $table;
176  }
177 
187  private function fetchBlob( $cluster, $id, $itemID ) {
194  static $externalBlobCache = [];
195 
196  $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
197  if ( isset( $externalBlobCache[$cacheID] ) ) {
198  wfDebugLog( 'ExternalStoreDB-cache',
199  "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
200 
201  return $externalBlobCache[$cacheID];
202  }
203 
204  wfDebugLog( 'ExternalStoreDB-cache',
205  "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
206 
207  $dbr = $this->getSlave( $cluster );
208  $ret = $dbr->selectField( $this->getTable( $dbr ),
209  'blob_text', [ 'blob_id' => $id ], __METHOD__ );
210  if ( $ret === false ) {
211  wfDebugLog( 'ExternalStoreDB',
212  "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
213  // Try the master
214  $dbw = $this->getMaster( $cluster );
215  $ret = $dbw->selectField( $this->getTable( $dbw ),
216  'blob_text', [ 'blob_id' => $id ], __METHOD__ );
217  if ( $ret === false ) {
218  wfDebugLog( 'ExternalStoreDB',
219  "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
220  }
221  }
222  if ( $itemID !== false && $ret !== false ) {
223  // Unserialise object; caller extracts item
224  $ret = unserialize( $ret );
225  }
226 
227  $externalBlobCache = [ $cacheID => $ret ];
228 
229  return $ret;
230  }
231 
240  private function batchFetchBlobs( $cluster, array $ids ) {
241  $dbr = $this->getSlave( $cluster );
242  $res = $dbr->select( $this->getTable( $dbr ),
243  [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
244  $ret = [];
245  if ( $res !== false ) {
246  $this->mergeBatchResult( $ret, $ids, $res );
247  }
248  if ( $ids ) {
249  wfDebugLog( __CLASS__, __METHOD__ .
250  " master fallback on '$cluster' for: " .
251  implode( ',', array_keys( $ids ) ) );
252  // Try the master
253  $dbw = $this->getMaster( $cluster );
254  $res = $dbw->select( $this->getTable( $dbr ),
255  [ 'blob_id', 'blob_text' ],
256  [ 'blob_id' => array_keys( $ids ) ],
257  __METHOD__ );
258  if ( $res === false ) {
259  wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
260  } else {
261  $this->mergeBatchResult( $ret, $ids, $res );
262  }
263  }
264  if ( $ids ) {
265  wfDebugLog( __CLASS__, __METHOD__ .
266  " master on '$cluster' failed locating items: " .
267  implode( ',', array_keys( $ids ) ) );
268  }
269 
270  return $ret;
271  }
272 
279  private function mergeBatchResult( array &$ret, array &$ids, $res ) {
280  foreach ( $res as $row ) {
281  $id = $row->blob_id;
282  $itemIDs = $ids[$id];
283  unset( $ids[$id] ); // to track if everything is found
284  if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
285  // single result stored per blob
286  $ret[$id] = $row->blob_text;
287  } else {
288  // multi result stored per blob
289  $ret[$id] = unserialize( $row->blob_text );
290  }
291  }
292  }
293 
298  protected function parseURL( $url ) {
299  $path = explode( '/', $url );
300 
301  return [
302  $path[2], // cluster
303  $path[3], // id
304  isset( $path[4] ) ? $path[4] : false // itemID
305  ];
306  }
307 }
ExternalStoreDB\batchFetchBlobs
batchFetchBlobs( $cluster, array $ids)
Fetch multiple blob items out of the database.
Definition: ExternalStoreDB.php:240
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:128
ExternalStoreDB\parseURL
parseURL( $url)
Definition: ExternalStoreDB.php:298
ExternalStoreDB
DB accessible external objects.
Definition: ExternalStoreDB.php:37
ExternalStoreDB\store
store( $location, $data)
Insert a data item into a given location.
Definition: ExternalStoreDB.php:94
captcha-old.count
count
Definition: captcha-old.py:249
ExternalStoreDB\batchFetchFromURLs
batchFetchFromURLs(array $urls)
Fetch data from given external store URLs.
Definition: ExternalStoreDB.php:66
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
unserialize
unserialize( $serialized)
Definition: ApiMessage.php:192
$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:2150
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:187
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:1075
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
$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
ExternalStoreDB\getLoadBalancer
getLoadBalancer( $cluster)
Get a LoadBalancer for the specified cluster.
Definition: ExternalStoreDB.php:117
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:107
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
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:982
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:169
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:46
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:40
$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:1987
Wikimedia\Rdbms\DBConnRef
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition: DBConnRef.php:15
$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
ExternalStoreDB\mergeBatchResult
mergeBatchResult(array &$ret, array &$ids, $res)
Helper function for self::batchFetchBlobs for merging master/replica DB results.
Definition: ExternalStoreDB.php:279
ExternalStoreDB\getMaster
getMaster( $cluster)
Get a master database connection for the specified cluster.
Definition: ExternalStoreDB.php:153
array
the array() calling protocol came about after MediaWiki 1.4rc1.