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