rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / externalstore / ExternalStoreDB.php
blob6bb1618ff6869bc158e9c5ac9348e660edfe2fa0
1 <?php
2 /**
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
20 * @file
23 use Wikimedia\Rdbms\LoadBalancer;
24 use Wikimedia\Rdbms\IDatabase;
25 use Wikimedia\Rdbms\DBConnRef;
26 use Wikimedia\Rdbms\MaintainableDBConnRef;
28 /**
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 {
37 /**
38 * The provided URL is in the form of DB://cluster/id
39 * or DB://cluster/id/itemid for concatened storage.
41 * @param string $url
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 );
53 return $ret;
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.
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;
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 );
90 return $ret;
93 public function store( $location, $data ) {
94 $dbw = $this->getMaster( $location );
95 $id = $dbw->nextSequenceValue( 'blob_blob_id_seq' );
96 $dbw->insert( $this->getTable( $dbw ),
97 [ 'blob_id' => $id, 'blob_text' => $data ],
98 __METHOD__ );
99 $id = $dbw->insertId();
100 if ( !$id ) {
101 throw new MWException( __METHOD__ . ': no insert ID' );
104 return "DB://$location/$id";
108 * Get a LoadBalancer for the specified cluster
110 * @param string $cluster Cluster name
111 * @return LoadBalancer
113 private function getLoadBalancer( $cluster ) {
114 return wfGetLBFactory()->getExternalLB( $cluster );
118 * Get a replica DB connection for the specified cluster
120 * @param string $cluster Cluster name
121 * @return DBConnRef
123 public function getSlave( $cluster ) {
124 global $wgDefaultExternalStore;
126 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
127 $lb = $this->getLoadBalancer( $cluster );
129 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
130 wfDebug( "read only external store\n" );
131 $lb->allowLagged( true );
132 } else {
133 wfDebug( "writable external store\n" );
136 $db = $lb->getConnectionRef( DB_REPLICA, [], $wiki );
137 $db->clearFlag( DBO_TRX ); // sanity
139 return $db;
143 * Get a master database connection for the specified cluster
145 * @param string $cluster Cluster name
146 * @return MaintainableDBConnRef
148 public function getMaster( $cluster ) {
149 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
150 $lb = $this->getLoadBalancer( $cluster );
152 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $wiki );
153 $db->clearFlag( DBO_TRX ); // sanity
155 return $db;
159 * Get the 'blobs' table name for this database
161 * @param IDatabase $db
162 * @return string Table name ('blobs' by default)
164 public function getTable( $db ) {
165 $table = $db->getLBInfo( 'blobs table' );
166 if ( is_null( $table ) ) {
167 $table = 'blobs';
170 return $table;
174 * Fetch a blob item out of the database; a cache of the last-loaded
175 * blob will be kept so that multiple loads out of a multi-item blob
176 * can avoid redundant database access and decompression.
177 * @param string $cluster
178 * @param string $id
179 * @param string $itemID
180 * @return HistoryBlob|bool Returns false if missing
182 private function fetchBlob( $cluster, $id, $itemID ) {
184 * One-step cache variable to hold base blobs; operations that
185 * pull multiple revisions may often pull multiple times from
186 * the same blob. By keeping the last-used one open, we avoid
187 * redundant unserialization and decompression overhead.
189 static $externalBlobCache = [];
191 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
192 if ( isset( $externalBlobCache[$cacheID] ) ) {
193 wfDebugLog( 'ExternalStoreDB-cache',
194 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
196 return $externalBlobCache[$cacheID];
199 wfDebugLog( 'ExternalStoreDB-cache',
200 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
202 $dbr = $this->getSlave( $cluster );
203 $ret = $dbr->selectField( $this->getTable( $dbr ),
204 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
205 if ( $ret === false ) {
206 wfDebugLog( 'ExternalStoreDB',
207 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
208 // Try the master
209 $dbw = $this->getMaster( $cluster );
210 $ret = $dbw->selectField( $this->getTable( $dbw ),
211 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
212 if ( $ret === false ) {
213 wfDebugLog( 'ExternalStoreDB',
214 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
217 if ( $itemID !== false && $ret !== false ) {
218 // Unserialise object; caller extracts item
219 $ret = unserialize( $ret );
222 $externalBlobCache = [ $cacheID => $ret ];
224 return $ret;
228 * Fetch multiple blob items out of the database
230 * @param string $cluster A cluster name valid for use with LBFactory
231 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
232 * @return array A map from the blob_id's requested to their content.
233 * Unlocated ids are not represented
235 private function batchFetchBlobs( $cluster, array $ids ) {
236 $dbr = $this->getSlave( $cluster );
237 $res = $dbr->select( $this->getTable( $dbr ),
238 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
239 $ret = [];
240 if ( $res !== false ) {
241 $this->mergeBatchResult( $ret, $ids, $res );
243 if ( $ids ) {
244 wfDebugLog( __CLASS__, __METHOD__ .
245 " master fallback on '$cluster' for: " .
246 implode( ',', array_keys( $ids ) ) );
247 // Try the master
248 $dbw = $this->getMaster( $cluster );
249 $res = $dbw->select( $this->getTable( $dbr ),
250 [ 'blob_id', 'blob_text' ],
251 [ 'blob_id' => array_keys( $ids ) ],
252 __METHOD__ );
253 if ( $res === false ) {
254 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
255 } else {
256 $this->mergeBatchResult( $ret, $ids, $res );
259 if ( $ids ) {
260 wfDebugLog( __CLASS__, __METHOD__ .
261 " master on '$cluster' failed locating items: " .
262 implode( ',', array_keys( $ids ) ) );
265 return $ret;
269 * Helper function for self::batchFetchBlobs for merging master/replica DB results
270 * @param array &$ret Current self::batchFetchBlobs return value
271 * @param array &$ids Map from blob_id to requested itemIDs
272 * @param mixed $res DB result from Database::select
274 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
275 foreach ( $res as $row ) {
276 $id = $row->blob_id;
277 $itemIDs = $ids[$id];
278 unset( $ids[$id] ); // to track if everything is found
279 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
280 // single result stored per blob
281 $ret[$id] = $row->blob_text;
282 } else {
283 // multi result stored per blob
284 $ret[$id] = unserialize( $row->blob_text );
290 * @param string $url
291 * @return array
293 protected function parseURL( $url ) {
294 $path = explode( '/', $url );
296 return [
297 $path[2], // cluster
298 $path[3], // id
299 isset( $path[4] ) ? $path[4] : false // itemID