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