Merge "Reduce selector specificity"
[lhc/web/wiklou.git] / includes / externalstore / ExternalStoreDB.php
1 <?php
2 /**
3 * External storage in SQL database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\ILoadBalancer;
25 use Wikimedia\Rdbms\IDatabase;
26 use Wikimedia\Rdbms\DBConnRef;
27 use Wikimedia\Rdbms\MaintainableDBConnRef;
28 use Wikimedia\Rdbms\DatabaseDomain;
29
30 /**
31 * DB accessible external objects.
32 *
33 * In this system, each store "location" maps to a database "cluster".
34 * The clusters must be defined in the normal LBFactory configuration.
35 *
36 * @ingroup ExternalStorage
37 */
38 class ExternalStoreDB extends ExternalStoreMedium {
39 /**
40 * The provided URL is in the form of DB://cluster/id
41 * or DB://cluster/id/itemid for concatened storage.
42 *
43 * @param string $url
44 * @return string|bool False if missing
45 * @see ExternalStoreMedium::fetchFromURL()
46 */
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
58 /**
59 * Fetch data from given external store URLs.
60 * The provided URLs are in the form of DB://cluster/id
61 * or DB://cluster/id/itemid for concatened storage.
62 *
63 * @param array $urls An array of external store URLs
64 * @return array A map from url to stored content. Failed results
65 * are not represented.
66 */
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 );
79 /** @var HistoryBlob $blob */
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 /**
96 * @inheritDoc
97 */
98 public function store( $location, $data ) {
99 $dbw = $this->getMaster( $location );
100 $dbw->insert( $this->getTable( $dbw ),
101 [ 'blob_text' => $data ],
102 __METHOD__ );
103 $id = $dbw->insertId();
104 if ( !$id ) {
105 throw new MWException( __METHOD__ . ': no insert ID' );
106 }
107
108 return "DB://$location/$id";
109 }
110
111 /**
112 * @inheritDoc
113 */
114 public function isReadOnly( $location ) {
115 $lb = $this->getLoadBalancer( $location );
116 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
117 return ( $lb->getReadOnlyReason( $domainId ) !== false );
118 }
119
120 /**
121 * Get a LoadBalancer for the specified cluster
122 *
123 * @param string $cluster Cluster name
124 * @return ILoadBalancer
125 */
126 private function getLoadBalancer( $cluster ) {
127 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
128 return $lbFactory->getExternalLB( $cluster );
129 }
130
131 /**
132 * Get a replica DB connection for the specified cluster
133 *
134 * @param string $cluster Cluster name
135 * @return DBConnRef
136 */
137 public function getSlave( $cluster ) {
138 global $wgDefaultExternalStore;
139
140 $lb = $this->getLoadBalancer( $cluster );
141 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
142
143 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
144 wfDebug( "read only external store\n" );
145 $lb->allowLagged( true );
146 } else {
147 wfDebug( "writable external store\n" );
148 }
149
150 $db = $lb->getConnectionRef( DB_REPLICA, [], $domainId );
151 $db->clearFlag( DBO_TRX ); // sanity
152
153 return $db;
154 }
155
156 /**
157 * Get a master database connection for the specified cluster
158 *
159 * @param string $cluster Cluster name
160 * @return MaintainableDBConnRef
161 */
162 public function getMaster( $cluster ) {
163 $lb = $this->getLoadBalancer( $cluster );
164 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
165
166 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $domainId );
167 $db->clearFlag( DBO_TRX ); // sanity
168
169 return $db;
170 }
171
172 /**
173 * @param array $server Master DB server configuration array for LoadBalancer
174 * @return string|bool Database domain ID or false
175 */
176 private function getDomainId( array $server ) {
177 if ( isset( $this->params['wiki'] ) && $this->params['wiki'] !== false ) {
178 return $this->params['wiki']; // explicit domain
179 }
180
181 if ( isset( $server['dbname'] ) ) {
182 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
183 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
184 // domain, but rather assumed that the LB server configuration matched $wgDBname.
185 // This check is useful when the external storage DB for this cluster does not use
186 // the same name as the corresponding "main" DB(s) for wikis.
187 $domain = new DatabaseDomain(
188 $server['dbname'],
189 $server['schema'] ?? null,
190 $server['tablePrefix'] ?? ''
191 );
192
193 return $domain->getId();
194 }
195
196 return false; // local LB domain
197 }
198
199 /**
200 * Get the 'blobs' table name for this database
201 *
202 * @param IDatabase $db
203 * @return string Table name ('blobs' by default)
204 */
205 public function getTable( $db ) {
206 $table = $db->getLBInfo( 'blobs table' );
207 if ( is_null( $table ) ) {
208 $table = 'blobs';
209 }
210
211 return $table;
212 }
213
214 /**
215 * Fetch a blob item out of the database; a cache of the last-loaded
216 * blob will be kept so that multiple loads out of a multi-item blob
217 * can avoid redundant database access and decompression.
218 * @param string $cluster
219 * @param string $id
220 * @param string $itemID
221 * @return HistoryBlob|bool Returns false if missing
222 */
223 private function fetchBlob( $cluster, $id, $itemID ) {
224 /**
225 * One-step cache variable to hold base blobs; operations that
226 * pull multiple revisions may often pull multiple times from
227 * the same blob. By keeping the last-used one open, we avoid
228 * redundant unserialization and decompression overhead.
229 */
230 static $externalBlobCache = [];
231
232 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
233
234 $wiki = $this->params['wiki'] ?? false;
235 $cacheID = ( $wiki === false ) ? $cacheID : "$cacheID@$wiki";
236
237 if ( isset( $externalBlobCache[$cacheID] ) ) {
238 wfDebugLog( 'ExternalStoreDB-cache',
239 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
240
241 return $externalBlobCache[$cacheID];
242 }
243
244 wfDebugLog( 'ExternalStoreDB-cache',
245 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
246
247 $dbr = $this->getSlave( $cluster );
248 $ret = $dbr->selectField( $this->getTable( $dbr ),
249 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
250 if ( $ret === false ) {
251 wfDebugLog( 'ExternalStoreDB',
252 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
253 // Try the master
254 $dbw = $this->getMaster( $cluster );
255 $ret = $dbw->selectField( $this->getTable( $dbw ),
256 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
257 if ( $ret === false ) {
258 wfDebugLog( 'ExternalStoreDB',
259 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
260 }
261 }
262 if ( $itemID !== false && $ret !== false ) {
263 // Unserialise object; caller extracts item
264 $ret = unserialize( $ret );
265 }
266
267 $externalBlobCache = [ $cacheID => $ret ];
268
269 return $ret;
270 }
271
272 /**
273 * Fetch multiple blob items out of the database
274 *
275 * @param string $cluster A cluster name valid for use with LBFactory
276 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
277 * @return array A map from the blob_id's requested to their content.
278 * Unlocated ids are not represented
279 */
280 private function batchFetchBlobs( $cluster, array $ids ) {
281 $dbr = $this->getSlave( $cluster );
282 $res = $dbr->select( $this->getTable( $dbr ),
283 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
284 $ret = [];
285 if ( $res !== false ) {
286 $this->mergeBatchResult( $ret, $ids, $res );
287 }
288 if ( $ids ) {
289 wfDebugLog( __CLASS__, __METHOD__ .
290 " master fallback on '$cluster' for: " .
291 implode( ',', array_keys( $ids ) ) );
292 // Try the master
293 $dbw = $this->getMaster( $cluster );
294 $res = $dbw->select( $this->getTable( $dbr ),
295 [ 'blob_id', 'blob_text' ],
296 [ 'blob_id' => array_keys( $ids ) ],
297 __METHOD__ );
298 if ( $res === false ) {
299 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
300 } else {
301 $this->mergeBatchResult( $ret, $ids, $res );
302 }
303 }
304 if ( $ids ) {
305 wfDebugLog( __CLASS__, __METHOD__ .
306 " master on '$cluster' failed locating items: " .
307 implode( ',', array_keys( $ids ) ) );
308 }
309
310 return $ret;
311 }
312
313 /**
314 * Helper function for self::batchFetchBlobs for merging master/replica DB results
315 * @param array &$ret Current self::batchFetchBlobs return value
316 * @param array &$ids Map from blob_id to requested itemIDs
317 * @param mixed $res DB result from Database::select
318 */
319 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
320 foreach ( $res as $row ) {
321 $id = $row->blob_id;
322 $itemIDs = $ids[$id];
323 unset( $ids[$id] ); // to track if everything is found
324 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
325 // single result stored per blob
326 $ret[$id] = $row->blob_text;
327 } else {
328 // multi result stored per blob
329 $ret[$id] = unserialize( $row->blob_text );
330 }
331 }
332 }
333
334 /**
335 * @param string $url
336 * @return array
337 */
338 protected function parseURL( $url ) {
339 $path = explode( '/', $url );
340
341 return [
342 $path[2], // cluster
343 $path[3], // id
344 $path[4] ?? false // itemID
345 ];
346 }
347 }