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