Merge "HttpFunctions: Increase code coverage"
[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\LoadBalancer;
24 use Wikimedia\Rdbms\IDatabase;
25
26 /**
27 * DB accessable external objects.
28 *
29 * In this system, each store "location" maps to a database "cluster".
30 * The clusters must be defined in the normal LBFactory configuration.
31 *
32 * @ingroup ExternalStorage
33 */
34 class ExternalStoreDB extends ExternalStoreMedium {
35 /**
36 * The provided URL is in the form of DB://cluster/id
37 * or DB://cluster/id/itemid for concatened storage.
38 *
39 * @param string $url
40 * @return string|bool False if missing
41 * @see ExternalStoreMedium::fetchFromURL()
42 */
43 public function fetchFromURL( $url ) {
44 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
45 $ret = $this->fetchBlob( $cluster, $id, $itemID );
46
47 if ( $itemID !== false && $ret !== false ) {
48 return $ret->getItem( $itemID );
49 }
50
51 return $ret;
52 }
53
54 /**
55 * Fetch data from given external store URLs.
56 * The provided URLs are in the form of DB://cluster/id
57 * or DB://cluster/id/itemid for concatened storage.
58 *
59 * @param array $urls An array of external store URLs
60 * @return array A map from url to stored content. Failed results
61 * are not represented.
62 */
63 public function batchFetchFromURLs( array $urls ) {
64 $batched = $inverseUrlMap = [];
65 foreach ( $urls as $url ) {
66 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
67 $batched[$cluster][$id][] = $itemID;
68 // false $itemID gets cast to int, but should be ok
69 // since we do === from the $itemID in $batched
70 $inverseUrlMap[$cluster][$id][$itemID] = $url;
71 }
72 $ret = [];
73 foreach ( $batched as $cluster => $batchByCluster ) {
74 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
75 /** @var HistoryBlob $blob */
76 foreach ( $res as $id => $blob ) {
77 foreach ( $batchByCluster[$id] as $itemID ) {
78 $url = $inverseUrlMap[$cluster][$id][$itemID];
79 if ( $itemID === false ) {
80 $ret[$url] = $blob;
81 } else {
82 $ret[$url] = $blob->getItem( $itemID );
83 }
84 }
85 }
86 }
87
88 return $ret;
89 }
90
91 public function store( $location, $data ) {
92 $dbw = $this->getMaster( $location );
93 $id = $dbw->nextSequenceValue( 'blob_blob_id_seq' );
94 $dbw->insert( $this->getTable( $dbw ),
95 [ 'blob_id' => $id, 'blob_text' => $data ],
96 __METHOD__ );
97 $id = $dbw->insertId();
98 if ( !$id ) {
99 throw new MWException( __METHOD__ . ': no insert ID' );
100 }
101
102 return "DB://$location/$id";
103 }
104
105 /**
106 * Get a LoadBalancer for the specified cluster
107 *
108 * @param string $cluster Cluster name
109 * @return LoadBalancer
110 */
111 private function getLoadBalancer( $cluster ) {
112 return wfGetLBFactory()->getExternalLB( $cluster );
113 }
114
115 /**
116 * Get a replica DB connection for the specified cluster
117 *
118 * @param string $cluster Cluster name
119 * @return DBConnRef
120 */
121 public function getSlave( $cluster ) {
122 global $wgDefaultExternalStore;
123
124 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
125 $lb = $this->getLoadBalancer( $cluster );
126
127 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
128 wfDebug( "read only external store\n" );
129 $lb->allowLagged( true );
130 } else {
131 wfDebug( "writable external store\n" );
132 }
133
134 $db = $lb->getConnectionRef( DB_REPLICA, [], $wiki );
135 $db->clearFlag( DBO_TRX ); // sanity
136
137 return $db;
138 }
139
140 /**
141 * Get a master database connection for the specified cluster
142 *
143 * @param string $cluster Cluster name
144 * @return MaintainableDBConnRef
145 */
146 public function getMaster( $cluster ) {
147 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
148 $lb = $this->getLoadBalancer( $cluster );
149
150 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $wiki );
151 $db->clearFlag( DBO_TRX ); // sanity
152
153 return $db;
154 }
155
156 /**
157 * Get the 'blobs' table name for this database
158 *
159 * @param IDatabase $db
160 * @return string Table name ('blobs' by default)
161 */
162 public function getTable( $db ) {
163 $table = $db->getLBInfo( 'blobs table' );
164 if ( is_null( $table ) ) {
165 $table = 'blobs';
166 }
167
168 return $table;
169 }
170
171 /**
172 * Fetch a blob item out of the database; a cache of the last-loaded
173 * blob will be kept so that multiple loads out of a multi-item blob
174 * can avoid redundant database access and decompression.
175 * @param string $cluster
176 * @param string $id
177 * @param string $itemID
178 * @return HistoryBlob|bool Returns false if missing
179 */
180 private function fetchBlob( $cluster, $id, $itemID ) {
181 /**
182 * One-step cache variable to hold base blobs; operations that
183 * pull multiple revisions may often pull multiple times from
184 * the same blob. By keeping the last-used one open, we avoid
185 * redundant unserialization and decompression overhead.
186 */
187 static $externalBlobCache = [];
188
189 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
190 if ( isset( $externalBlobCache[$cacheID] ) ) {
191 wfDebugLog( 'ExternalStoreDB-cache',
192 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
193
194 return $externalBlobCache[$cacheID];
195 }
196
197 wfDebugLog( 'ExternalStoreDB-cache',
198 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
199
200 $dbr = $this->getSlave( $cluster );
201 $ret = $dbr->selectField( $this->getTable( $dbr ),
202 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
203 if ( $ret === false ) {
204 wfDebugLog( 'ExternalStoreDB',
205 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
206 // Try the master
207 $dbw = $this->getMaster( $cluster );
208 $ret = $dbw->selectField( $this->getTable( $dbw ),
209 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
210 if ( $ret === false ) {
211 wfDebugLog( 'ExternalStoreDB',
212 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
213 }
214 }
215 if ( $itemID !== false && $ret !== false ) {
216 // Unserialise object; caller extracts item
217 $ret = unserialize( $ret );
218 }
219
220 $externalBlobCache = [ $cacheID => $ret ];
221
222 return $ret;
223 }
224
225 /**
226 * Fetch multiple blob items out of the database
227 *
228 * @param string $cluster A cluster name valid for use with LBFactory
229 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
230 * @return array A map from the blob_id's requested to their content.
231 * Unlocated ids are not represented
232 */
233 private function batchFetchBlobs( $cluster, array $ids ) {
234 $dbr = $this->getSlave( $cluster );
235 $res = $dbr->select( $this->getTable( $dbr ),
236 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
237 $ret = [];
238 if ( $res !== false ) {
239 $this->mergeBatchResult( $ret, $ids, $res );
240 }
241 if ( $ids ) {
242 wfDebugLog( __CLASS__, __METHOD__ .
243 " master fallback on '$cluster' for: " .
244 implode( ',', array_keys( $ids ) ) );
245 // Try the master
246 $dbw = $this->getMaster( $cluster );
247 $res = $dbw->select( $this->getTable( $dbr ),
248 [ 'blob_id', 'blob_text' ],
249 [ 'blob_id' => array_keys( $ids ) ],
250 __METHOD__ );
251 if ( $res === false ) {
252 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
253 } else {
254 $this->mergeBatchResult( $ret, $ids, $res );
255 }
256 }
257 if ( $ids ) {
258 wfDebugLog( __CLASS__, __METHOD__ .
259 " master on '$cluster' failed locating items: " .
260 implode( ',', array_keys( $ids ) ) );
261 }
262
263 return $ret;
264 }
265
266 /**
267 * Helper function for self::batchFetchBlobs for merging master/replica DB results
268 * @param array &$ret Current self::batchFetchBlobs return value
269 * @param array &$ids Map from blob_id to requested itemIDs
270 * @param mixed $res DB result from Database::select
271 */
272 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
273 foreach ( $res as $row ) {
274 $id = $row->blob_id;
275 $itemIDs = $ids[$id];
276 unset( $ids[$id] ); // to track if everything is found
277 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
278 // single result stored per blob
279 $ret[$id] = $row->blob_text;
280 } else {
281 // multi result stored per blob
282 $ret[$id] = unserialize( $row->blob_text );
283 }
284 }
285 }
286
287 /**
288 * @param string $url
289 * @return array
290 */
291 protected function parseURL( $url ) {
292 $path = explode( '/', $url );
293
294 return [
295 $path[2], // cluster
296 $path[3], // id
297 isset( $path[4] ) ? $path[4] : false // itemID
298 ];
299 }
300 }