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