Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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 if ( !in_array( $cluster, $this->writableLocations, true ) ) {
160 $this->logger->debug( "read only external store\n" );
161 $lb->allowLagged( true );
162 } else {
163 $this->logger->debug( "writable external store\n" );
164 }
165
166 $db = $lb->getConnectionRef( DB_REPLICA, [], $domainId );
167 $db->clearFlag( DBO_TRX ); // sanity
168
169 return $db;
170 }
171
172 /**
173 * Get a master database connection for the specified cluster
174 *
175 * @param string $cluster Cluster name
176 * @return MaintainableDBConnRef
177 */
178 public function getMaster( $cluster ) {
179 $lb = $this->getLoadBalancer( $cluster );
180 $domainId = $this->getDomainId( $lb->getServerInfo( $lb->getWriterIndex() ) );
181
182 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $domainId );
183 $db->clearFlag( DBO_TRX ); // sanity
184
185 return $db;
186 }
187
188 /**
189 * @param array $server Master DB server configuration array for LoadBalancer
190 * @return string|bool Database domain ID or false
191 */
192 private function getDomainId( array $server ) {
193 if ( $this->isDbDomainExplicit ) {
194 return $this->dbDomain; // explicit foreign domain
195 }
196
197 if ( isset( $server['dbname'] ) ) {
198 // T200471: for b/c, treat any "dbname" field as forcing which database to use.
199 // MediaWiki/LoadBalancer previously did not enforce any concept of a local DB
200 // domain, but rather assumed that the LB server configuration matched $wgDBname.
201 // This check is useful when the external storage DB for this cluster does not use
202 // the same name as the corresponding "main" DB(s) for wikis.
203 $domain = new DatabaseDomain(
204 $server['dbname'],
205 $server['schema'] ?? null,
206 $server['tablePrefix'] ?? ''
207 );
208
209 return $domain->getId();
210 }
211
212 return false; // local LB domain
213 }
214
215 /**
216 * Get the 'blobs' table name for this database
217 *
218 * @param IDatabase $db
219 * @return string Table name ('blobs' by default)
220 */
221 public function getTable( $db ) {
222 $table = $db->getLBInfo( 'blobs table' );
223 if ( is_null( $table ) ) {
224 $table = 'blobs';
225 }
226
227 return $table;
228 }
229
230 /**
231 * Fetch a blob item out of the database; a cache of the last-loaded
232 * blob will be kept so that multiple loads out of a multi-item blob
233 * can avoid redundant database access and decompression.
234 * @param string $cluster
235 * @param string $id
236 * @param string $itemID
237 * @return HistoryBlob|bool Returns false if missing
238 */
239 private function fetchBlob( $cluster, $id, $itemID ) {
240 /**
241 * One-step cache variable to hold base blobs; operations that
242 * pull multiple revisions may often pull multiple times from
243 * the same blob. By keeping the last-used one open, we avoid
244 * redundant unserialization and decompression overhead.
245 */
246 static $externalBlobCache = [];
247
248 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
249 $cacheID = "$cacheID@{$this->dbDomain}";
250
251 if ( isset( $externalBlobCache[$cacheID] ) ) {
252 $this->logger->debug( "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
253
254 return $externalBlobCache[$cacheID];
255 }
256
257 $this->logger->debug( "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
258
259 $dbr = $this->getSlave( $cluster );
260 $ret = $dbr->selectField( $this->getTable( $dbr ),
261 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
262 if ( $ret === false ) {
263 $this->logger->info( "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
264 // Try the master
265 $dbw = $this->getMaster( $cluster );
266 $ret = $dbw->selectField( $this->getTable( $dbw ),
267 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
268 if ( $ret === false ) {
269 $this->logger->error( "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
270 }
271 }
272 if ( $itemID !== false && $ret !== false ) {
273 // Unserialise object; caller extracts item
274 $ret = unserialize( $ret );
275 }
276
277 $externalBlobCache = [ $cacheID => $ret ];
278
279 return $ret;
280 }
281
282 /**
283 * Fetch multiple blob items out of the database
284 *
285 * @param string $cluster A cluster name valid for use with LBFactory
286 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
287 * @return array A map from the blob_id's requested to their content.
288 * Unlocated ids are not represented
289 */
290 private function batchFetchBlobs( $cluster, array $ids ) {
291 $dbr = $this->getSlave( $cluster );
292 $res = $dbr->select(
293 $this->getTable( $dbr ),
294 [ 'blob_id', 'blob_text' ],
295 [ 'blob_id' => array_keys( $ids ) ],
296 __METHOD__
297 );
298
299 $ret = [];
300 if ( $res !== false ) {
301 $this->mergeBatchResult( $ret, $ids, $res );
302 }
303 if ( $ids ) {
304 $this->logger->info(
305 __METHOD__ . ": master fallback on '$cluster' for: " .
306 implode( ',', array_keys( $ids ) )
307 );
308 // Try the master
309 $dbw = $this->getMaster( $cluster );
310 $res = $dbw->select( $this->getTable( $dbr ),
311 [ 'blob_id', 'blob_text' ],
312 [ 'blob_id' => array_keys( $ids ) ],
313 __METHOD__ );
314 if ( $res === false ) {
315 $this->logger->error( __METHOD__ . ": master failed on '$cluster'" );
316 } else {
317 $this->mergeBatchResult( $ret, $ids, $res );
318 }
319 }
320 if ( $ids ) {
321 $this->logger->error(
322 __METHOD__ . ": master on '$cluster' failed locating items: " .
323 implode( ',', array_keys( $ids ) )
324 );
325 }
326
327 return $ret;
328 }
329
330 /**
331 * Helper function for self::batchFetchBlobs for merging master/replica DB results
332 * @param array &$ret Current self::batchFetchBlobs return value
333 * @param array &$ids Map from blob_id to requested itemIDs
334 * @param mixed $res DB result from Database::select
335 */
336 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
337 foreach ( $res as $row ) {
338 $id = $row->blob_id;
339 $itemIDs = $ids[$id];
340 unset( $ids[$id] ); // to track if everything is found
341 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
342 // single result stored per blob
343 $ret[$id] = $row->blob_text;
344 } else {
345 // multi result stored per blob
346 $ret[$id] = unserialize( $row->blob_text );
347 }
348 }
349 }
350
351 /**
352 * @param string $url
353 * @return array
354 */
355 protected function parseURL( $url ) {
356 $path = explode( '/', $url );
357
358 return [
359 $path[2], // cluster
360 $path[3], // id
361 $path[4] ?? false // itemID
362 ];
363 }
364 }