75f7ccdfabe2c62507d4ae75388643dd19d55415
[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 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
112 /**
113 * Get a LoadBalancer for the specified cluster
114 *
115 * @param string $cluster Cluster name
116 * @return ILoadBalancer
117 */
118 private function getLoadBalancer( $cluster ) {
119 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
120 return $lbFactory->getExternalLB( $cluster );
121 }
122
123 /**
124 * Get a replica DB connection for the specified cluster
125 *
126 * @param string $cluster Cluster name
127 * @return DBConnRef
128 */
129 public function getSlave( $cluster ) {
130 global $wgDefaultExternalStore;
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
148 /**
149 * Get a master database connection for the specified cluster
150 *
151 * @param string $cluster Cluster name
152 * @return MaintainableDBConnRef
153 */
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
164 /**
165 * @param array $server Master DB server configuration array for LoadBalancer
166 * @return string|bool Database domain ID or false
167 */
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
191 /**
192 * Get the 'blobs' table name for this database
193 *
194 * @param IDatabase $db
195 * @return string Table name ('blobs' by default)
196 */
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
206 /**
207 * Fetch a blob item out of the database; a cache of the last-loaded
208 * blob will be kept so that multiple loads out of a multi-item blob
209 * can avoid redundant database access and decompression.
210 * @param string $cluster
211 * @param string $id
212 * @param string $itemID
213 * @return HistoryBlob|bool Returns false if missing
214 */
215 private function fetchBlob( $cluster, $id, $itemID ) {
216 /**
217 * One-step cache variable to hold base blobs; operations that
218 * pull multiple revisions may often pull multiple times from
219 * the same blob. By keeping the last-used one open, we avoid
220 * redundant unserialization and decompression overhead.
221 */
222 static $externalBlobCache = [];
223
224 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
225
226 $wiki = $this->params['wiki'] ?? false;
227 $cacheID = ( $wiki === false ) ? $cacheID : "$cacheID@$wiki";
228
229 if ( isset( $externalBlobCache[$cacheID] ) ) {
230 wfDebugLog( 'ExternalStoreDB-cache',
231 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
232
233 return $externalBlobCache[$cacheID];
234 }
235
236 wfDebugLog( 'ExternalStoreDB-cache',
237 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
238
239 $dbr = $this->getSlave( $cluster );
240 $ret = $dbr->selectField( $this->getTable( $dbr ),
241 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
242 if ( $ret === false ) {
243 wfDebugLog( 'ExternalStoreDB',
244 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
245 // Try the master
246 $dbw = $this->getMaster( $cluster );
247 $ret = $dbw->selectField( $this->getTable( $dbw ),
248 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
249 if ( $ret === false ) {
250 wfDebugLog( 'ExternalStoreDB',
251 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
252 }
253 }
254 if ( $itemID !== false && $ret !== false ) {
255 // Unserialise object; caller extracts item
256 $ret = unserialize( $ret );
257 }
258
259 $externalBlobCache = [ $cacheID => $ret ];
260
261 return $ret;
262 }
263
264 /**
265 * Fetch multiple blob items out of the database
266 *
267 * @param string $cluster A cluster name valid for use with LBFactory
268 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
269 * @return array A map from the blob_id's requested to their content.
270 * Unlocated ids are not represented
271 */
272 private function batchFetchBlobs( $cluster, array $ids ) {
273 $dbr = $this->getSlave( $cluster );
274 $res = $dbr->select( $this->getTable( $dbr ),
275 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
276 $ret = [];
277 if ( $res !== false ) {
278 $this->mergeBatchResult( $ret, $ids, $res );
279 }
280 if ( $ids ) {
281 wfDebugLog( __CLASS__, __METHOD__ .
282 " master fallback on '$cluster' for: " .
283 implode( ',', array_keys( $ids ) ) );
284 // Try the master
285 $dbw = $this->getMaster( $cluster );
286 $res = $dbw->select( $this->getTable( $dbr ),
287 [ 'blob_id', 'blob_text' ],
288 [ 'blob_id' => array_keys( $ids ) ],
289 __METHOD__ );
290 if ( $res === false ) {
291 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
292 } else {
293 $this->mergeBatchResult( $ret, $ids, $res );
294 }
295 }
296 if ( $ids ) {
297 wfDebugLog( __CLASS__, __METHOD__ .
298 " master on '$cluster' failed locating items: " .
299 implode( ',', array_keys( $ids ) ) );
300 }
301
302 return $ret;
303 }
304
305 /**
306 * Helper function for self::batchFetchBlobs for merging master/replica DB results
307 * @param array &$ret Current self::batchFetchBlobs return value
308 * @param array &$ids Map from blob_id to requested itemIDs
309 * @param mixed $res DB result from Database::select
310 */
311 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
312 foreach ( $res as $row ) {
313 $id = $row->blob_id;
314 $itemIDs = $ids[$id];
315 unset( $ids[$id] ); // to track if everything is found
316 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
317 // single result stored per blob
318 $ret[$id] = $row->blob_text;
319 } else {
320 // multi result stored per blob
321 $ret[$id] = unserialize( $row->blob_text );
322 }
323 }
324 }
325
326 /**
327 * @param string $url
328 * @return array
329 */
330 protected function parseURL( $url ) {
331 $path = explode( '/', $url );
332
333 return [
334 $path[2], // cluster
335 $path[3], // id
336 $path[4] ?? false // itemID
337 ];
338 }
339 }