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