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 MediaWiki\MediaWikiServices
;
24 use Wikimedia\Rdbms\LoadBalancer
;
25 use Wikimedia\Rdbms\IDatabase
;
26 use Wikimedia\Rdbms\DBConnRef
;
27 use Wikimedia\Rdbms\MaintainableDBConnRef
;
30 * DB accessible external objects.
32 * In this system, each store "location" maps to a database "cluster".
33 * The clusters must be defined in the normal LBFactory configuration.
35 * @ingroup ExternalStorage
37 class ExternalStoreDB
extends ExternalStoreMedium
{
39 * The provided URL is in the form of DB://cluster/id
40 * or DB://cluster/id/itemid for concatened storage.
43 * @return string|bool False if missing
44 * @see ExternalStoreMedium::fetchFromURL()
46 public function fetchFromURL( $url ) {
47 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
48 $ret = $this->fetchBlob( $cluster, $id, $itemID );
50 if ( $itemID !== false && $ret !== false ) {
51 return $ret->getItem( $itemID );
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.
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.
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;
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 ) {
85 $ret[$url] = $blob->getItem( $itemID );
94 public function store( $location, $data ) {
95 $dbw = $this->getMaster( $location );
96 $dbw->insert( $this->getTable( $dbw ),
97 [ 'blob_text' => $data ],
99 $id = $dbw->insertId();
101 throw new MWException( __METHOD__
. ': no insert ID' );
104 return "DB://$location/$id";
107 public function isReadOnly( $location ) {
108 return ( $this->getLoadBalancer( $location )->getReadOnlyReason() !== false );
112 * Get a LoadBalancer for the specified cluster
114 * @param string $cluster Cluster name
115 * @return LoadBalancer
117 private function getLoadBalancer( $cluster ) {
118 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
119 return $lbFactory->getExternalLB( $cluster );
123 * Get a replica DB connection for the specified cluster
125 * @param string $cluster Cluster name
128 public function getSlave( $cluster ) {
129 global $wgDefaultExternalStore;
131 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
132 $lb = $this->getLoadBalancer( $cluster );
134 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
135 wfDebug( "read only external store\n" );
136 $lb->allowLagged( true );
138 wfDebug( "writable external store\n" );
141 $db = $lb->getConnectionRef( DB_REPLICA
, [], $wiki );
142 $db->clearFlag( DBO_TRX
); // sanity
148 * Get a master database connection for the specified cluster
150 * @param string $cluster Cluster name
151 * @return MaintainableDBConnRef
153 public function getMaster( $cluster ) {
154 $wiki = isset( $this->params
['wiki'] ) ?
$this->params
['wiki'] : false;
155 $lb = $this->getLoadBalancer( $cluster );
157 $db = $lb->getMaintenanceConnectionRef( DB_MASTER
, [], $wiki );
158 $db->clearFlag( DBO_TRX
); // sanity
164 * Get the 'blobs' table name for this database
166 * @param IDatabase $db
167 * @return string Table name ('blobs' by default)
169 public function getTable( $db ) {
170 $table = $db->getLBInfo( 'blobs table' );
171 if ( is_null( $table ) ) {
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
184 * @param string $itemID
185 * @return HistoryBlob|bool Returns false if missing
187 private function fetchBlob( $cluster, $id, $itemID ) {
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.
194 static $externalBlobCache = [];
196 $cacheID = ( $itemID === false ) ?
"$cluster/$id" : "$cluster/$id/";
197 if ( isset( $externalBlobCache[$cacheID] ) ) {
198 wfDebugLog( 'ExternalStoreDB-cache',
199 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
201 return $externalBlobCache[$cacheID];
204 wfDebugLog( 'ExternalStoreDB-cache',
205 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
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" );
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" );
222 if ( $itemID !== false && $ret !== false ) {
223 // Unserialise object; caller extracts item
224 $ret = unserialize( $ret );
227 $externalBlobCache = [ $cacheID => $ret ];
233 * Fetch multiple blob items out of the database
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
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__
);
245 if ( $res !== false ) {
246 $this->mergeBatchResult( $ret, $ids, $res );
249 wfDebugLog( __CLASS__
, __METHOD__
.
250 " master fallback on '$cluster' for: " .
251 implode( ',', array_keys( $ids ) ) );
253 $dbw = $this->getMaster( $cluster );
254 $res = $dbw->select( $this->getTable( $dbr ),
255 [ 'blob_id', 'blob_text' ],
256 [ 'blob_id' => array_keys( $ids ) ],
258 if ( $res === false ) {
259 wfDebugLog( __CLASS__
, __METHOD__
. " master failed on '$cluster'" );
261 $this->mergeBatchResult( $ret, $ids, $res );
265 wfDebugLog( __CLASS__
, __METHOD__
.
266 " master on '$cluster' failed locating items: " .
267 implode( ',', array_keys( $ids ) ) );
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
279 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
280 foreach ( $res as $row ) {
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
;
288 // multi result stored per blob
289 $ret[$id] = unserialize( $row->blob_text
);
298 protected function parseURL( $url ) {
299 $path = explode( '/', $url );
304 isset( $path[4] ) ?
$path[4] : false // itemID