3 * External storage in SQL database.
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.
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.
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
23 use Wikimedia\Rdbms\LoadBalancer
;
24 use Wikimedia\Rdbms\IDatabase
;
25 use Wikimedia\Rdbms\DBConnRef
;
26 use Wikimedia\Rdbms\MaintainableDBConnRef
;
29 * DB accessable external objects.
31 * In this system, each store "location" maps to a database "cluster".
32 * The clusters must be defined in the normal LBFactory configuration.
34 * @ingroup ExternalStorage
36 class ExternalStoreDB
extends ExternalStoreMedium
{
38 * The provided URL is in the form of DB://cluster/id
39 * or DB://cluster/id/itemid for concatened storage.
42 * @return string|bool False if missing
43 * @see ExternalStoreMedium::fetchFromURL()
45 public function fetchFromURL( $url ) {
46 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
47 $ret = $this->fetchBlob( $cluster, $id, $itemID );
49 if ( $itemID !== false && $ret !== false ) {
50 return $ret->getItem( $itemID );
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.
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.
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;
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 ) {
84 $ret[$url] = $blob->getItem( $itemID );
93 public function store( $location, $data ) {
94 $dbw = $this->getMaster( $location );
95 $dbw->insert( $this->getTable( $dbw ),
96 [ 'blob_text' => $data ],
98 $id = $dbw->insertId();
100 throw new MWException( __METHOD__
. ': no insert ID' );
103 return "DB://$location/$id";
107 * Get a LoadBalancer for the specified cluster
109 * @param string $cluster Cluster name
110 * @return LoadBalancer
112 private function getLoadBalancer( $cluster ) {
113 return wfGetLBFactory()->getExternalLB( $cluster );
117 * Get a replica DB connection for the specified cluster
119 * @param string $cluster Cluster name
122 public function getSlave( $cluster ) {
123 global $wgDefaultExternalStore;
125 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
126 $lb = $this->getLoadBalancer( $cluster );
128 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
129 wfDebug( "read only external store\n" );
130 $lb->allowLagged( true );
132 wfDebug( "writable external store\n" );
135 $db = $lb->getConnectionRef( DB_REPLICA
, [], $wiki );
136 $db->clearFlag( DBO_TRX
); // sanity
142 * Get a master database connection for the specified cluster
144 * @param string $cluster Cluster name
145 * @return MaintainableDBConnRef
147 public function getMaster( $cluster ) {
148 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
149 $lb = $this->getLoadBalancer( $cluster );
151 $db = $lb->getMaintenanceConnectionRef( DB_MASTER
, [], $wiki );
152 $db->clearFlag( DBO_TRX
); // sanity
158 * Get the 'blobs' table name for this database
160 * @param IDatabase $db
161 * @return string Table name ('blobs' by default)
163 public function getTable( $db ) {
164 $table = $db->getLBInfo( 'blobs table' );
165 if ( is_null( $table ) ) {
173 * Fetch a blob item out of the database; a cache of the last-loaded
174 * blob will be kept so that multiple loads out of a multi-item blob
175 * can avoid redundant database access and decompression.
176 * @param string $cluster
178 * @param string $itemID
179 * @return HistoryBlob|bool Returns false if missing
181 private function fetchBlob( $cluster, $id, $itemID ) {
183 * One-step cache variable to hold base blobs; operations that
184 * pull multiple revisions may often pull multiple times from
185 * the same blob. By keeping the last-used one open, we avoid
186 * redundant unserialization and decompression overhead.
188 static $externalBlobCache = [];
190 $cacheID = ( $itemID === false ) ?
"$cluster/$id" : "$cluster/$id/";
191 if ( isset( $externalBlobCache[$cacheID] ) ) {
192 wfDebugLog( 'ExternalStoreDB-cache',
193 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
195 return $externalBlobCache[$cacheID];
198 wfDebugLog( 'ExternalStoreDB-cache',
199 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
201 $dbr = $this->getSlave( $cluster );
202 $ret = $dbr->selectField( $this->getTable( $dbr ),
203 'blob_text', [ 'blob_id' => $id ], __METHOD__
);
204 if ( $ret === false ) {
205 wfDebugLog( 'ExternalStoreDB',
206 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
208 $dbw = $this->getMaster( $cluster );
209 $ret = $dbw->selectField( $this->getTable( $dbw ),
210 'blob_text', [ 'blob_id' => $id ], __METHOD__
);
211 if ( $ret === false ) {
212 wfDebugLog( 'ExternalStoreDB',
213 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
216 if ( $itemID !== false && $ret !== false ) {
217 // Unserialise object; caller extracts item
218 $ret = unserialize( $ret );
221 $externalBlobCache = [ $cacheID => $ret ];
227 * Fetch multiple blob items out of the database
229 * @param string $cluster A cluster name valid for use with LBFactory
230 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
231 * @return array A map from the blob_id's requested to their content.
232 * Unlocated ids are not represented
234 private function batchFetchBlobs( $cluster, array $ids ) {
235 $dbr = $this->getSlave( $cluster );
236 $res = $dbr->select( $this->getTable( $dbr ),
237 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__
);
239 if ( $res !== false ) {
240 $this->mergeBatchResult( $ret, $ids, $res );
243 wfDebugLog( __CLASS__
, __METHOD__
.
244 " master fallback on '$cluster' for: " .
245 implode( ',', array_keys( $ids ) ) );
247 $dbw = $this->getMaster( $cluster );
248 $res = $dbw->select( $this->getTable( $dbr ),
249 [ 'blob_id', 'blob_text' ],
250 [ 'blob_id' => array_keys( $ids ) ],
252 if ( $res === false ) {
253 wfDebugLog( __CLASS__
, __METHOD__
. " master failed on '$cluster'" );
255 $this->mergeBatchResult( $ret, $ids, $res );
259 wfDebugLog( __CLASS__
, __METHOD__
.
260 " master on '$cluster' failed locating items: " .
261 implode( ',', array_keys( $ids ) ) );
268 * Helper function for self::batchFetchBlobs for merging master/replica DB results
269 * @param array &$ret Current self::batchFetchBlobs return value
270 * @param array &$ids Map from blob_id to requested itemIDs
271 * @param mixed $res DB result from Database::select
273 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
274 foreach ( $res as $row ) {
276 $itemIDs = $ids[$id];
277 unset( $ids[$id] ); // to track if everything is found
278 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
279 // single result stored per blob
280 $ret[$id] = $row->blob_text
;
282 // multi result stored per blob
283 $ret[$id] = unserialize( $row->blob_text
);
292 protected function parseURL( $url ) {
293 $path = explode( '/', $url );
298 isset( $path[4] ) ?
$path[4] : false // itemID