MediaWiki REL1_31
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 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
110 }
111
118 private function getLoadBalancer( $cluster ) {
119 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
120 return $lbFactory->getExternalLB( $cluster );
121 }
122
129 public function getSlave( $cluster ) {
131
132 $lb = $this->getLoadBalancer( $cluster );
133 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
134
135 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
136 wfDebug( "read only external store\n" );
137 $lb->allowLagged( true );
138 } else {
139 wfDebug( "writable external store\n" );
140 }
141
142 $db = $lb->getConnectionRef( DB_REPLICA, [], $domainId );
143 $db->clearFlag( DBO_TRX ); // sanity
144
145 return $db;
146 }
147
154 public function getMaster( $cluster ) {
155 $lb = $this->getLoadBalancer( $cluster );
156 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
157
158 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $domainId );
159 $db->clearFlag( DBO_TRX ); // sanity
160
161 return $db;
162 }
163
168 private function getDomainId( array $server ) {
169 if ( isset( $this->params['wiki'] ) ) {
170 return $this->params['wiki']; // explicit domain
171 }
172
173 if ( isset( $server['dbname'] ) ) {
174 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
175 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
176 // domain, but rather assumed that the LB server configuration matched $wgDBname.
177 // This check is useful when the external storage DB for this cluster does not use
178 // the same name as the corresponding "main" DB(s) for wikis.
179 $domain = new DatabaseDomain(
180 $server['dbname'],
181 $server['schema'] ?? null,
182 $server['tablePrefix'] ?? ''
183 );
184
185 return $domain->getId();
186 }
187
188 return false; // local LB domain
189 }
190
197 public function getTable( $db ) {
198 $table = $db->getLBInfo( 'blobs table' );
199 if ( is_null( $table ) ) {
200 $table = 'blobs';
201 }
202
203 return $table;
204 }
205
215 private function fetchBlob( $cluster, $id, $itemID ) {
222 static $externalBlobCache = [];
223
224 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
225 if ( isset( $externalBlobCache[$cacheID] ) ) {
226 wfDebugLog( 'ExternalStoreDB-cache',
227 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
228
229 return $externalBlobCache[$cacheID];
230 }
231
232 wfDebugLog( 'ExternalStoreDB-cache',
233 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
234
235 $dbr = $this->getSlave( $cluster );
236 $ret = $dbr->selectField( $this->getTable( $dbr ),
237 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
238 if ( $ret === false ) {
239 wfDebugLog( 'ExternalStoreDB',
240 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
241 // Try the master
242 $dbw = $this->getMaster( $cluster );
243 $ret = $dbw->selectField( $this->getTable( $dbw ),
244 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
245 if ( $ret === false ) {
246 wfDebugLog( 'ExternalStoreDB',
247 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
248 }
249 }
250 if ( $itemID !== false && $ret !== false ) {
251 // Unserialise object; caller extracts item
252 $ret = unserialize( $ret );
253 }
254
255 $externalBlobCache = [ $cacheID => $ret ];
256
257 return $ret;
258 }
259
268 private function batchFetchBlobs( $cluster, array $ids ) {
269 $dbr = $this->getSlave( $cluster );
270 $res = $dbr->select( $this->getTable( $dbr ),
271 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
272 $ret = [];
273 if ( $res !== false ) {
274 $this->mergeBatchResult( $ret, $ids, $res );
275 }
276 if ( $ids ) {
277 wfDebugLog( __CLASS__, __METHOD__ .
278 " master fallback on '$cluster' for: " .
279 implode( ',', array_keys( $ids ) ) );
280 // Try the master
281 $dbw = $this->getMaster( $cluster );
282 $res = $dbw->select( $this->getTable( $dbr ),
283 [ 'blob_id', 'blob_text' ],
284 [ 'blob_id' => array_keys( $ids ) ],
285 __METHOD__ );
286 if ( $res === false ) {
287 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
288 } else {
289 $this->mergeBatchResult( $ret, $ids, $res );
290 }
291 }
292 if ( $ids ) {
293 wfDebugLog( __CLASS__, __METHOD__ .
294 " master on '$cluster' failed locating items: " .
295 implode( ',', array_keys( $ids ) ) );
296 }
297
298 return $ret;
299 }
300
307 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
308 foreach ( $res as $row ) {
309 $id = $row->blob_id;
310 $itemIDs = $ids[$id];
311 unset( $ids[$id] ); // to track if everything is found
312 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
313 // single result stored per blob
314 $ret[$id] = $row->blob_text;
315 } else {
316 // multi result stored per blob
317 $ret[$id] = unserialize( $row->blob_text );
318 }
319 }
320 }
321
326 protected function parseURL( $url ) {
327 $path = explode( '/', $url );
328
329 return [
330 $path[2], // cluster
331 $path[3], // id
332 isset( $path[4] ) ? $path[4] : false // itemID
333 ];
334 }
335}
unserialize( $serialized)
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
DB accessible external objects.
getSlave( $cluster)
Get a replica DB connection for the specified cluster.
batchFetchBlobs( $cluster, array $ids)
Fetch multiple blob items out of the database.
mergeBatchResult(array &$ret, array &$ids, $res)
Helper function for self::batchFetchBlobs for merging master/replica DB results.
getDomainId(array $server)
getMaster( $cluster)
Get a master database connection for the specified cluster.
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 ...
getTable( $db)
Get the 'blobs' table name for this database.
fetchFromURL( $url)
The provided URL is in the form of DB://cluster/id or DB://cluster/id/itemid for concatened storage.
store( $location, $data)
Insert a data item into a given location.
batchFetchFromURLs(array $urls)
Fetch data from given external store URLs.
isReadOnly( $location)
Check if a given location is read-only.
getLoadBalancer( $cluster)
Get a LoadBalancer for the specified cluster.
Accessable external objects in a particular storage medium.
MediaWiki exception.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
Definition DBConnRef.php:15
Class to handle database/prefix specification for IDatabase domains.
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...
$res
Definition database.txt:21
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
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:2005
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
Database cluster connection, tracking, load balancing, and transaction manager interface.
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:29
const DBO_TRX
Definition defines.php:12