[FileBackend] Reduced code duplication with new getPathsToLockForOpsInternal() function.
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackendMultiWrite.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Aaron Schulz
6 */
7
8 /**
9 * @brief Proxy backend that mirrors writes to several internal backends.
10 *
11 * This class defines a multi-write backend. Multiple backends can be
12 * registered to this proxy backend and it will act as a single backend.
13 * Use this when all access to those backends is through this proxy backend.
14 * At least one of the backends must be declared the "master" backend.
15 *
16 * Only use this class when transitioning from one storage system to another.
17 *
18 * Read operations are only done on the 'master' backend for consistency.
19 * Write operations are performed on all backends, in the order defined.
20 * If an operation fails on one backend it will be rolled back from the others.
21 *
22 * @ingroup FileBackend
23 * @since 1.19
24 */
25 class FileBackendMultiWrite extends FileBackend {
26 /** @var Array Prioritized list of FileBackendStore objects */
27 protected $backends = array(); // array of (backend index => backends)
28 protected $masterIndex = -1; // integer; index of master backend
29 protected $syncChecks = 0; // integer bitfield
30
31 /* Possible internal backend consistency checks */
32 const CHECK_SIZE = 1;
33 const CHECK_TIME = 2;
34
35 /**
36 * Construct a proxy backend that consists of several internal backends.
37 * Additional $config params include:
38 * 'backends' : Array of backend config and multi-backend settings.
39 * Each value is the config used in the constructor of a
40 * FileBackendStore class, but with these additional settings:
41 * 'class' : The name of the backend class
42 * 'isMultiMaster' : This must be set for one backend.
43 * 'syncChecks' : Integer bitfield of internal backend sync checks to perform.
44 * Possible bits include self::CHECK_SIZE and self::CHECK_TIME.
45 * The checks are done before allowing any file operations.
46 * @param $config Array
47 */
48 public function __construct( array $config ) {
49 parent::__construct( $config );
50 $namesUsed = array();
51 // Construct backends here rather than via registration
52 // to keep these backends hidden from outside the proxy.
53 foreach ( $config['backends'] as $index => $config ) {
54 $name = $config['name'];
55 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
56 throw new MWException( "Two or more backends defined with the name $name." );
57 }
58 $namesUsed[$name] = 1;
59 if ( !isset( $config['class'] ) ) {
60 throw new MWException( 'No class given for a backend config.' );
61 }
62 $class = $config['class'];
63 $this->backends[$index] = new $class( $config );
64 if ( !empty( $config['isMultiMaster'] ) ) {
65 if ( $this->masterIndex >= 0 ) {
66 throw new MWException( 'More than one master backend defined.' );
67 }
68 $this->masterIndex = $index;
69 }
70 }
71 if ( $this->masterIndex < 0 ) { // need backends and must have a master
72 throw new MWException( 'No master backend defined.' );
73 }
74 $this->syncChecks = isset( $config['syncChecks'] )
75 ? $config['syncChecks']
76 : self::CHECK_SIZE;
77 }
78
79 /**
80 * @see FileBackend::doOperationsInternal()
81 * @return Status
82 */
83 final protected function doOperationsInternal( array $ops, array $opts ) {
84 $status = Status::newGood();
85
86 $performOps = array(); // list of FileOp objects
87 $paths = array(); // storage paths read from or written to
88 // Build up a list of FileOps. The list will have all the ops
89 // for one backend, then all the ops for the next, and so on.
90 // These batches of ops are all part of a continuous array.
91 // Also build up a list of files read/changed...
92 foreach ( $this->backends as $index => $backend ) {
93 $backendOps = $this->substOpBatchPaths( $ops, $backend );
94 // Add on the operation batch for this backend
95 $performOps = array_merge( $performOps, $backend->getOperations( $backendOps ) );
96 if ( $index == 0 ) { // first batch
97 // Get the files used for these operations. Each backend has a batch of
98 // the same operations, so we only need to get them from the first batch.
99 $paths = $backend->getPathsToLockForOpsInternal( $performOps );
100 // Get the paths under the proxy backend's name
101 $paths['sh'] = $this->unsubstPaths( $paths['sh'] );
102 $paths['ex'] = $this->unsubstPaths( $paths['ex'] );
103 }
104 }
105
106 // Try to lock those files for the scope of this function...
107 if ( empty( $opts['nonLocking'] ) ) {
108 // Try to lock those files for the scope of this function...
109 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
110 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
111 if ( !$status->isOK() ) {
112 return $status; // abort
113 }
114 }
115
116 // Clear any cache entries (after locks acquired)
117 $this->clearCache();
118
119 // Do a consistency check to see if the backends agree
120 if ( count( $this->backends ) > 1 ) {
121 $status->merge( $this->consistencyCheck( array_merge( $paths['sh'], $paths['ex'] ) ) );
122 if ( !$status->isOK() ) {
123 return $status; // abort
124 }
125 }
126
127 // Actually attempt the operation batch...
128 $subStatus = FileOp::attemptBatch( $performOps, $opts, $this->fileJournal );
129
130 $success = array();
131 $failCount = 0;
132 $successCount = 0;
133 // Make 'success', 'successCount', and 'failCount' fields reflect
134 // the overall operation, rather than all the batches for each backend.
135 // Do this by only using success values from the master backend's batch.
136 $batchStart = $this->masterIndex * count( $ops );
137 $batchEnd = $batchStart + count( $ops ) - 1;
138 for ( $i = $batchStart; $i <= $batchEnd; $i++ ) {
139 if ( !isset( $subStatus->success[$i] ) ) {
140 break; // failed out before trying this op
141 } elseif ( $subStatus->success[$i] ) {
142 ++$successCount;
143 } else {
144 ++$failCount;
145 }
146 $success[] = $subStatus->success[$i];
147 }
148 $subStatus->success = $success;
149 $subStatus->successCount = $successCount;
150 $subStatus->failCount = $failCount;
151
152 // Merge errors into status fields
153 $status->merge( $subStatus );
154 $status->success = $subStatus->success; // not done in merge()
155
156 return $status;
157 }
158
159 /**
160 * Check that a set of files are consistent across all internal backends
161 *
162 * @param $paths Array
163 * @return Status
164 */
165 public function consistencyCheck( array $paths ) {
166 $status = Status::newGood();
167 if ( $this->syncChecks == 0 ) {
168 return $status; // skip checks
169 }
170
171 $mBackend = $this->backends[$this->masterIndex];
172 foreach ( array_unique( $paths ) as $path ) {
173 $params = array( 'src' => $path, 'latest' => true );
174 // Stat the file on the 'master' backend
175 $mStat = $mBackend->getFileStat( $this->substOpPaths( $params, $mBackend ) );
176 // Check of all clone backends agree with the master...
177 foreach ( $this->backends as $index => $cBackend ) {
178 if ( $index === $this->masterIndex ) {
179 continue; // master
180 }
181 $cStat = $cBackend->getFileStat( $this->substOpPaths( $params, $cBackend ) );
182 if ( $mStat ) { // file is in master
183 if ( !$cStat ) { // file should exist
184 $status->fatal( 'backend-fail-synced', $path );
185 continue;
186 }
187 if ( $this->syncChecks & self::CHECK_SIZE ) {
188 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
189 $status->fatal( 'backend-fail-synced', $path );
190 continue;
191 }
192 }
193 if ( $this->syncChecks & self::CHECK_TIME ) {
194 $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] );
195 $cTs = wfTimestamp( TS_UNIX, $cStat['mtime'] );
196 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
197 $status->fatal( 'backend-fail-synced', $path );
198 continue;
199 }
200 }
201 } else { // file is not in master
202 if ( $cStat ) { // file should not exist
203 $status->fatal( 'backend-fail-synced', $path );
204 }
205 }
206 }
207 }
208
209 return $status;
210 }
211
212 /**
213 * Substitute the backend name in storage path parameters
214 * for a set of operations with that of a given internal backend.
215 *
216 * @param $ops Array List of file operation arrays
217 * @param $backend FileBackendStore
218 * @return Array
219 */
220 protected function substOpBatchPaths( array $ops, FileBackendStore $backend ) {
221 $newOps = array(); // operations
222 foreach ( $ops as $op ) {
223 $newOp = $op; // operation
224 foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
225 if ( isset( $newOp[$par] ) ) { // string or array
226 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
227 }
228 }
229 $newOps[] = $newOp;
230 }
231 return $newOps;
232 }
233
234 /**
235 * Same as substOpBatchPaths() but for a single operation
236 *
237 * @param $op File operation array
238 * @param $backend FileBackendStore
239 * @return Array
240 */
241 protected function substOpPaths( array $ops, FileBackendStore $backend ) {
242 $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
243 return $newOps[0];
244 }
245
246 /**
247 * Substitute the backend of storage paths with an internal backend's name
248 *
249 * @param $paths Array|string List of paths or single string path
250 * @param $backend FileBackendStore
251 * @return Array|string
252 */
253 protected function substPaths( $paths, FileBackendStore $backend ) {
254 return preg_replace(
255 '!^mwstore://' . preg_quote( $this->name ) . '/!',
256 StringUtils::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
257 $paths // string or array
258 );
259 }
260
261 /**
262 * Substitute the backend of internal storage paths with the proxy backend's name
263 *
264 * @param $paths Array|string List of paths or single string path
265 * @return Array|string
266 */
267 protected function unsubstPaths( $paths ) {
268 return preg_replace(
269 '!^mwstore://([^/]+)!',
270 StringUtils::escapeRegexReplacement( "mwstore://{$this->name}" ),
271 $paths // string or array
272 );
273 }
274
275 /**
276 * @see FileBackend::doPrepare()
277 * @return Status
278 */
279 protected function doPrepare( array $params ) {
280 $status = Status::newGood();
281 foreach ( $this->backends as $backend ) {
282 $realParams = $this->substOpPaths( $params, $backend );
283 $status->merge( $backend->doPrepare( $realParams ) );
284 }
285 return $status;
286 }
287
288 /**
289 * @see FileBackend::doSecure()
290 * @return Status
291 */
292 protected function doSecure( array $params ) {
293 $status = Status::newGood();
294 foreach ( $this->backends as $backend ) {
295 $realParams = $this->substOpPaths( $params, $backend );
296 $status->merge( $backend->doSecure( $realParams ) );
297 }
298 return $status;
299 }
300
301 /**
302 * @see FileBackend::doClean()
303 * @return Status
304 */
305 protected function doClean( array $params ) {
306 $status = Status::newGood();
307 foreach ( $this->backends as $backend ) {
308 $realParams = $this->substOpPaths( $params, $backend );
309 $status->merge( $backend->doClean( $realParams ) );
310 }
311 return $status;
312 }
313
314 /**
315 * @see FileBackend::getFileList()
316 */
317 public function concatenate( array $params ) {
318 // We are writing to an FS file, so we don't need to do this per-backend
319 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
320 return $this->backends[$this->masterIndex]->concatenate( $realParams );
321 }
322
323 /**
324 * @see FileBackend::fileExists()
325 */
326 public function fileExists( array $params ) {
327 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
328 return $this->backends[$this->masterIndex]->fileExists( $realParams );
329 }
330
331 /**
332 * @see FileBackend::getFileTimestamp()
333 */
334 public function getFileTimestamp( array $params ) {
335 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
336 return $this->backends[$this->masterIndex]->getFileTimestamp( $realParams );
337 }
338
339 /**
340 * @see FileBackend::getFileSize()
341 */
342 public function getFileSize( array $params ) {
343 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
344 return $this->backends[$this->masterIndex]->getFileSize( $realParams );
345 }
346
347 /**
348 * @see FileBackend::getFileStat()
349 */
350 public function getFileStat( array $params ) {
351 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
352 return $this->backends[$this->masterIndex]->getFileStat( $realParams );
353 }
354
355 /**
356 * @see FileBackend::getFileContents()
357 */
358 public function getFileContents( array $params ) {
359 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
360 return $this->backends[$this->masterIndex]->getFileContents( $realParams );
361 }
362
363 /**
364 * @see FileBackend::getFileSha1Base36()
365 */
366 public function getFileSha1Base36( array $params ) {
367 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
368 return $this->backends[$this->masterIndex]->getFileSha1Base36( $realParams );
369 }
370
371 /**
372 * @see FileBackend::getFileProps()
373 */
374 public function getFileProps( array $params ) {
375 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
376 return $this->backends[$this->masterIndex]->getFileProps( $realParams );
377 }
378
379 /**
380 * @see FileBackend::streamFile()
381 */
382 public function streamFile( array $params ) {
383 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
384 return $this->backends[$this->masterIndex]->streamFile( $realParams );
385 }
386
387 /**
388 * @see FileBackend::getLocalReference()
389 */
390 public function getLocalReference( array $params ) {
391 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
392 return $this->backends[$this->masterIndex]->getLocalReference( $realParams );
393 }
394
395 /**
396 * @see FileBackend::getLocalCopy()
397 */
398 public function getLocalCopy( array $params ) {
399 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
400 return $this->backends[$this->masterIndex]->getLocalCopy( $realParams );
401 }
402
403 /**
404 * @see FileBackend::getFileList()
405 */
406 public function getFileList( array $params ) {
407 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
408 return $this->backends[$this->masterIndex]->getFileList( $realParams );
409 }
410
411 /**
412 * @see FileBackend::clearCache()
413 */
414 public function clearCache( array $paths = null ) {
415 foreach ( $this->backends as $backend ) {
416 $realPaths = is_array( $paths ) ? $this->substPaths( $paths, $backend ) : null;
417 $backend->clearCache( $realPaths );
418 }
419 }
420 }