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