Merge "Exclude redirects from Special:Fewestrevisions"
[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 Wikimedia\Rdbms\LBFactory;
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 /** @var LBFactory */
40 private $lbFactory;
41
42 /**
43 * @see ExternalStoreMedium::__construct()
44 * @param array $params Additional parameters include:
45 * - lbFactory: an LBFactory instance
46 */
47 public function __construct( array $params ) {
48 parent::__construct( $params );
49 if ( !isset( $params['lbFactory'] ) || !( $params['lbFactory'] instanceof LBFactory ) ) {
50 throw new InvalidArgumentException( "LBFactory required in 'lbFactory' field." );
51 }
52 $this->lbFactory = $params['lbFactory'];
53 }
54
55 /**
56 * The provided URL is in the form of DB://cluster/id
57 * or DB://cluster/id/itemid for concatened storage.
58 *
59 * @param string $url
60 * @return string|bool False if missing
61 * @see ExternalStoreMedium::fetchFromURL()
62 */
63 public function fetchFromURL( $url ) {
64 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
65 $ret = $this->fetchBlob( $cluster, $id, $itemID );
66
67 if ( $itemID !== false && $ret !== false ) {
68 return $ret->getItem( $itemID );
69 }
70
71 return $ret;
72 }
73
74 /**
75 * Fetch data from given external store URLs.
76 * The provided URLs are in the form of DB://cluster/id
77 * or DB://cluster/id/itemid for concatened storage.
78 *
79 * @param array $urls An array of external store URLs
80 * @return array A map from url to stored content. Failed results
81 * are not represented.
82 */
83 public function batchFetchFromURLs( array $urls ) {
84 $batched = $inverseUrlMap = [];
85 foreach ( $urls as $url ) {
86 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
87 $batched[$cluster][$id][] = $itemID;
88 // false $itemID gets cast to int, but should be ok
89 // since we do === from the $itemID in $batched
90 $inverseUrlMap[$cluster][$id][$itemID] = $url;
91 }
92 $ret = [];
93 foreach ( $batched as $cluster => $batchByCluster ) {
94 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
95 /** @var HistoryBlob $blob */
96 foreach ( $res as $id => $blob ) {
97 foreach ( $batchByCluster[$id] as $itemID ) {
98 $url = $inverseUrlMap[$cluster][$id][$itemID];
99 if ( $itemID === false ) {
100 $ret[$url] = $blob;
101 } else {
102 $ret[$url] = $blob->getItem( $itemID );
103 }
104 }
105 }
106 }
107
108 return $ret;
109 }
110
111 /**
112 * @inheritDoc
113 */
114 public function store( $location, $data ) {
115 $dbw = $this->getMaster( $location );
116 $dbw->insert( $this->getTable( $dbw ), [ 'blob_text' => $data ], __METHOD__ );
117 $id = $dbw->insertId();
118 if ( !$id ) {
119 throw new MWException( __METHOD__ . ': no insert ID' );
120 }
121
122 return "DB://$location/$id";
123 }
124
125 /**
126 * @inheritDoc
127 */
128 public function isReadOnly( $location ) {
129 if ( parent::isReadOnly( $location ) ) {
130 return true;
131 }
132
133 $lb = $this->getLoadBalancer( $location );
134 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
135
136 return ( $lb->getReadOnlyReason( $domainId ) !== false );
137 }
138
139 /**
140 * Get a LoadBalancer for the specified cluster
141 *
142 * @param string $cluster Cluster name
143 * @return ILoadBalancer
144 */
145 private function getLoadBalancer( $cluster ) {
146 return $this->lbFactory->getExternalLB( $cluster );
147 }
148
149 /**
150 * Get a replica DB connection for the specified cluster
151 *
152 * @param string $cluster Cluster name
153 * @return DBConnRef
154 */
155 public function getSlave( $cluster ) {
156 $lb = $this->getLoadBalancer( $cluster );
157 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
158
159 $db = $lb->getConnectionRef( DB_REPLICA, [], $domainId );
160 $db->clearFlag( DBO_TRX ); // sanity
161
162 return $db;
163 }
164
165 /**
166 * Get a master database connection for the specified cluster
167 *
168 * @param string $cluster Cluster name
169 * @return MaintainableDBConnRef
170 */
171 public function getMaster( $cluster ) {
172 $lb = $this->getLoadBalancer( $cluster );
173 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
174
175 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $domainId );
176 $db->clearFlag( DBO_TRX ); // sanity
177
178 return $db;
179 }
180
181 /**
182 * @param array $server Master DB server configuration array for LoadBalancer
183 * @return string|bool Database domain ID or false
184 */
185 private function getDomainId( array $server ) {
186 if ( $this->isDbDomainExplicit ) {
187 return $this->dbDomain; // explicit foreign domain
188 }
189
190 if ( isset( $server['dbname'] ) ) {
191 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
192 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
193 // domain, but rather assumed that the LB server configuration matched $wgDBname.
194 // This check is useful when the external storage DB for this cluster does not use
195 // the same name as the corresponding "main" DB(s) for wikis.
196 $domain = new DatabaseDomain(
197 $server['dbname'],
198 $server['schema'] ?? null,
199 $server['tablePrefix'] ?? ''
200 );
201
202 return $domain->getId();
203 }
204
205 return false; // local LB domain
206 }
207
208 /**
209 * Get the 'blobs' table name for this database
210 *
211 * @param IDatabase $db
212 * @return string Table name ('blobs' by default)
213 */
214 public function getTable( $db ) {
215 $table = $db->getLBInfo( 'blobs table' );
216 if ( is_null( $table ) ) {
217 $table = 'blobs';
218 }
219
220 return $table;
221 }
222
223 /**
224 * Fetch a blob item out of the database; a cache of the last-loaded
225 * blob will be kept so that multiple loads out of a multi-item blob
226 * can avoid redundant database access and decompression.
227 * @param string $cluster
228 * @param string $id
229 * @param string $itemID
230 * @return HistoryBlob|bool Returns false if missing
231 */
232 private function fetchBlob( $cluster, $id, $itemID ) {
233 /**
234 * One-step cache variable to hold base blobs; operations that
235 * pull multiple revisions may often pull multiple times from
236 * the same blob. By keeping the last-used one open, we avoid
237 * redundant unserialization and decompression overhead.
238 */
239 static $externalBlobCache = [];
240
241 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
242 $cacheID = "$cacheID@{$this->dbDomain}";
243
244 if ( isset( $externalBlobCache[$cacheID] ) ) {
245 $this->logger->debug( "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
246
247 return $externalBlobCache[$cacheID];
248 }
249
250 $this->logger->debug( "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
251
252 $dbr = $this->getSlave( $cluster );
253 $ret = $dbr->selectField( $this->getTable( $dbr ),
254 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
255 if ( $ret === false ) {
256 $this->logger->info( "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
257 // Try the master
258 $dbw = $this->getMaster( $cluster );
259 $ret = $dbw->selectField( $this->getTable( $dbw ),
260 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
261 if ( $ret === false ) {
262 $this->logger->error( "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
263 }
264 }
265 if ( $itemID !== false && $ret !== false ) {
266 // Unserialise object; caller extracts item
267 $ret = unserialize( $ret );
268 }
269
270 $externalBlobCache = [ $cacheID => $ret ];
271
272 return $ret;
273 }
274
275 /**
276 * Fetch multiple blob items out of the database
277 *
278 * @param string $cluster A cluster name valid for use with LBFactory
279 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
280 * @return array A map from the blob_id's requested to their content.
281 * Unlocated ids are not represented
282 */
283 private function batchFetchBlobs( $cluster, array $ids ) {
284 $dbr = $this->getSlave( $cluster );
285 $res = $dbr->select(
286 $this->getTable( $dbr ),
287 [ 'blob_id', 'blob_text' ],
288 [ 'blob_id' => array_keys( $ids ) ],
289 __METHOD__
290 );
291
292 $ret = [];
293 if ( $res !== false ) {
294 $this->mergeBatchResult( $ret, $ids, $res );
295 }
296 if ( $ids ) {
297 $this->logger->info(
298 __METHOD__ . ": master fallback on '$cluster' for: " .
299 implode( ',', array_keys( $ids ) )
300 );
301 // Try the master
302 $dbw = $this->getMaster( $cluster );
303 $res = $dbw->select( $this->getTable( $dbr ),
304 [ 'blob_id', 'blob_text' ],
305 [ 'blob_id' => array_keys( $ids ) ],
306 __METHOD__ );
307 if ( $res === false ) {
308 $this->logger->error( __METHOD__ . ": master failed on '$cluster'" );
309 } else {
310 $this->mergeBatchResult( $ret, $ids, $res );
311 }
312 }
313 if ( $ids ) {
314 $this->logger->error(
315 __METHOD__ . ": master on '$cluster' failed locating items: " .
316 implode( ',', array_keys( $ids ) )
317 );
318 }
319
320 return $ret;
321 }
322
323 /**
324 * Helper function for self::batchFetchBlobs for merging master/replica DB results
325 * @param array &$ret Current self::batchFetchBlobs return value
326 * @param array &$ids Map from blob_id to requested itemIDs
327 * @param mixed $res DB result from Database::select
328 */
329 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
330 foreach ( $res as $row ) {
331 $id = $row->blob_id;
332 $itemIDs = $ids[$id];
333 unset( $ids[$id] ); // to track if everything is found
334 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
335 // single result stored per blob
336 $ret[$id] = $row->blob_text;
337 } else {
338 // multi result stored per blob
339 $ret[$id] = unserialize( $row->blob_text );
340 }
341 }
342 }
343
344 /**
345 * @param string $url
346 * @return array
347 */
348 protected function parseURL( $url ) {
349 $path = explode( '/', $url );
350
351 return [
352 $path[2], // cluster
353 $path[3], // id
354 $path[4] ?? false // itemID
355 ];
356 }
357 }