Merge "(bug 31817) Teach Tidy about the HTML5 inline tag bdi."
[lhc/web/wiklou.git] / includes / filebackend / FileBackendMultiWrite.php
1 <?php
2 /**
3 * Proxy backend that mirrors writes to several internal backends.
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 * @ingroup FileBackend
22 * @author Aaron Schulz
23 */
24
25 /**
26 * @brief Proxy backend that mirrors writes to several internal backends.
27 *
28 * This class defines a multi-write backend. Multiple backends can be
29 * registered to this proxy backend and it will act as a single backend.
30 * Use this when all access to those backends is through this proxy backend.
31 * At least one of the backends must be declared the "master" backend.
32 *
33 * Only use this class when transitioning from one storage system to another.
34 *
35 * Read operations are only done on the 'master' backend for consistency.
36 * Write operations are performed on all backends, in the order defined.
37 * If an operation fails on one backend it will be rolled back from the others.
38 *
39 * @ingroup FileBackend
40 * @since 1.19
41 */
42 class FileBackendMultiWrite extends FileBackend {
43 /** @var Array Prioritized list of FileBackendStore objects */
44 protected $backends = array(); // array of (backend index => backends)
45 protected $masterIndex = -1; // integer; index of master backend
46 protected $syncChecks = 0; // integer; bitfield
47 /** @var Array */
48 protected $noPushDirConts = array();
49 protected $noPushQuickOps = false; // boolean
50
51 /* Possible internal backend consistency checks */
52 const CHECK_SIZE = 1;
53 const CHECK_TIME = 2;
54 const CHECK_SHA1 = 4;
55
56 /**
57 * Construct a proxy backend that consists of several internal backends.
58 * Locking, journaling, and read-only checks are handled by the proxy backend.
59 *
60 * Additional $config params include:
61 * - backends : Array of backend config and multi-backend settings.
62 * Each value is the config used in the constructor of a
63 * FileBackendStore class, but with these additional settings:
64 * - class : The name of the backend class
65 * - isMultiMaster : This must be set for one backend.
66 * - template: : If given a backend name, this will use
67 * the config of that backend as a template.
68 * Values specified here take precedence.
69 * - syncChecks : Integer bitfield of internal backend sync checks to perform.
70 * Possible bits include the FileBackendMultiWrite::CHECK_* constants.
71 * There are constants for SIZE, TIME, and SHA1.
72 * The checks are done before allowing any file operations.
73 * - noPushQuickOps : (hack) Only apply doQuickOperations() to the master backend.
74 * - noPushDirConts : (hack) Only apply directory functions to the master backend.
75 *
76 * @param $config Array
77 * @throws MWException
78 */
79 public function __construct( array $config ) {
80 parent::__construct( $config );
81 $this->syncChecks = isset( $config['syncChecks'] )
82 ? $config['syncChecks']
83 : self::CHECK_SIZE;
84 $this->noPushQuickOps = isset( $config['noPushQuickOps'] )
85 ? $config['noPushQuickOps']
86 : false;
87 $this->noPushDirConts = isset( $config['noPushDirConts'] )
88 ? $config['noPushDirConts']
89 : array();
90 // Construct backends here rather than via registration
91 // to keep these backends hidden from outside the proxy.
92 $namesUsed = array();
93 foreach ( $config['backends'] as $index => $config ) {
94 if ( isset( $config['template'] ) ) {
95 // Config is just a modified version of a registered backend's.
96 // This should only be used when that config is used only by this backend.
97 $config = $config + FileBackendGroup::singleton()->config( $config['template'] );
98 }
99 $name = $config['name'];
100 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
101 throw new MWException( "Two or more backends defined with the name $name." );
102 }
103 $namesUsed[$name] = 1;
104 // Alter certain sub-backend settings for sanity
105 unset( $config['readOnly'] ); // use proxy backend setting
106 unset( $config['fileJournal'] ); // use proxy backend journal
107 $config['wikiId'] = $this->wikiId; // use the proxy backend wiki ID
108 $config['lockManager'] = 'nullLockManager'; // lock under proxy backend
109 if ( !empty( $config['isMultiMaster'] ) ) {
110 if ( $this->masterIndex >= 0 ) {
111 throw new MWException( 'More than one master backend defined.' );
112 }
113 $this->masterIndex = $index; // this is the "master"
114 $config['fileJournal'] = $this->fileJournal; // log under proxy backend
115 }
116 // Create sub-backend object
117 if ( !isset( $config['class'] ) ) {
118 throw new MWException( 'No class given for a backend config.' );
119 }
120 $class = $config['class'];
121 $this->backends[$index] = new $class( $config );
122 }
123 if ( $this->masterIndex < 0 ) { // need backends and must have a master
124 throw new MWException( 'No master backend defined.' );
125 }
126 }
127
128 /**
129 * @see FileBackend::doOperationsInternal()
130 * @return Status
131 */
132 final protected function doOperationsInternal( array $ops, array $opts ) {
133 $status = Status::newGood();
134
135 $mbe = $this->backends[$this->masterIndex]; // convenience
136
137 // Get the paths to lock from the master backend
138 $realOps = $this->substOpBatchPaths( $ops, $mbe );
139 $paths = $mbe->getPathsToLockForOpsInternal( $mbe->getOperationsInternal( $realOps ) );
140 // Get the paths under the proxy backend's name
141 $paths['sh'] = $this->unsubstPaths( $paths['sh'] );
142 $paths['ex'] = $this->unsubstPaths( $paths['ex'] );
143 // Try to lock those files for the scope of this function...
144 if ( empty( $opts['nonLocking'] ) ) {
145 // Try to lock those files for the scope of this function...
146 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
147 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
148 if ( !$status->isOK() ) {
149 return $status; // abort
150 }
151 }
152 // Clear any cache entries (after locks acquired)
153 $this->clearCache();
154 // Do a consistency check to see if the backends agree
155 $status->merge( $this->consistencyCheck( $this->fileStoragePathsForOps( $ops ) ) );
156 if ( !$status->isOK() ) {
157 return $status; // abort
158 }
159 // Actually attempt the operation batch on the master backend...
160 $masterStatus = $mbe->doOperations( $realOps, $opts );
161 $status->merge( $masterStatus );
162 // Propagate the operations to the clone backends...
163 foreach ( $this->backends as $index => $backend ) {
164 if ( $index !== $this->masterIndex ) { // not done already
165 $realOps = $this->substOpBatchPaths( $ops, $backend );
166 $status->merge( $backend->doOperations( $realOps, $opts ) );
167 }
168 }
169 // Make 'success', 'successCount', and 'failCount' fields reflect
170 // the overall operation, rather than all the batches for each backend.
171 // Do this by only using success values from the master backend's batch.
172 $status->success = $masterStatus->success;
173 $status->successCount = $masterStatus->successCount;
174 $status->failCount = $masterStatus->failCount;
175
176 return $status;
177 }
178
179 /**
180 * Check that a set of files are consistent across all internal backends
181 *
182 * @param $paths Array List of storage paths
183 * @return Status
184 */
185 public function consistencyCheck( array $paths ) {
186 $status = Status::newGood();
187 if ( $this->syncChecks == 0 || count( $this->backends ) <= 1 ) {
188 return $status; // skip checks
189 }
190
191 $mBackend = $this->backends[$this->masterIndex];
192 foreach ( array_unique( $paths ) as $path ) {
193 $params = array( 'src' => $path, 'latest' => true );
194 $mParams = $this->substOpPaths( $params, $mBackend );
195 // Stat the file on the 'master' backend
196 $mStat = $mBackend->getFileStat( $mParams );
197 if ( $this->syncChecks & self::CHECK_SHA1 ) {
198 $mSha1 = $mBackend->getFileSha1Base36( $mParams );
199 } else {
200 $mSha1 = false;
201 }
202 $mUsable = $mBackend->isPathUsableInternal( $mParams['src'] );
203 // Check of all clone backends agree with the master...
204 foreach ( $this->backends as $index => $cBackend ) {
205 if ( $index === $this->masterIndex ) {
206 continue; // master
207 }
208 $cParams = $this->substOpPaths( $params, $cBackend );
209 $cStat = $cBackend->getFileStat( $cParams );
210 if ( $mStat ) { // file is in master
211 if ( !$cStat ) { // file should exist
212 $status->fatal( 'backend-fail-synced', $path );
213 continue;
214 }
215 if ( $this->syncChecks & self::CHECK_SIZE ) {
216 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
217 $status->fatal( 'backend-fail-synced', $path );
218 continue;
219 }
220 }
221 if ( $this->syncChecks & self::CHECK_TIME ) {
222 $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] );
223 $cTs = wfTimestamp( TS_UNIX, $cStat['mtime'] );
224 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
225 $status->fatal( 'backend-fail-synced', $path );
226 continue;
227 }
228 }
229 if ( $this->syncChecks & self::CHECK_SHA1 ) {
230 if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
231 $status->fatal( 'backend-fail-synced', $path );
232 continue;
233 }
234 }
235 } else { // file is not in master
236 if ( $cStat ) { // file should not exist
237 $status->fatal( 'backend-fail-synced', $path );
238 }
239 }
240 if ( $mUsable !== $cBackend->isPathUsableInternal( $cParams['src'] ) ) {
241 $status->fatal( 'backend-fail-synced', $path );
242 }
243 }
244 }
245
246 return $status;
247 }
248
249 /**
250 * Check that a set of files are consistent across all internal backends
251 * and re-synchronize those files againt the "multi master" if needed.
252 *
253 * @param $paths Array List of storage paths
254 * @return Status
255 */
256 public function resyncFiles( array $paths ) {
257 $status = Status::newGood();
258
259 $mBackend = $this->backends[$this->masterIndex];
260 foreach ( $paths as $path ) {
261 $mPath = $this->substPaths( $path, $mBackend );
262 $mSha1 = $mBackend->getFileSha1Base36( array( 'src' => $mPath ) );
263 $mExist = $mBackend->fileExists( array( 'src' => $mPath ) );
264 // Check of all clone backends agree with the master...
265 foreach ( $this->backends as $index => $cBackend ) {
266 if ( $index === $this->masterIndex ) {
267 continue; // master
268 }
269 $cPath = $this->substPaths( $path, $cBackend );
270 $cSha1 = $cBackend->getFileSha1Base36( array( 'src' => $cPath ) );
271 if ( $mSha1 === $cSha1 ) {
272 // already synced; nothing to do
273 } elseif ( $mSha1 ) { // file is in master
274 $fsFile = $mBackend->getLocalReference( array( 'src' => $mPath ) );
275 $status->merge( $cBackend->quickStore(
276 array( 'src' => $fsFile->getPath(), 'dst' => $cPath )
277 ) );
278 } elseif ( $mExist === false ) { // file is not in master
279 $status->merge( $cBackend->quickDelete( array( 'src' => $cPath ) ) );
280 }
281 }
282 }
283
284 return $status;
285 }
286
287 /**
288 * Get a list of file storage paths to read or write for a list of operations
289 *
290 * @param $ops Array Same format as doOperations()
291 * @return Array List of storage paths to files (does not include directories)
292 */
293 protected function fileStoragePathsForOps( array $ops ) {
294 $paths = array();
295 foreach ( $ops as $op ) {
296 if ( isset( $op['src'] ) ) {
297 $paths[] = $op['src'];
298 }
299 if ( isset( $op['srcs'] ) ) {
300 $paths = array_merge( $paths, $op['srcs'] );
301 }
302 if ( isset( $op['dst'] ) ) {
303 $paths[] = $op['dst'];
304 }
305 }
306 return array_unique( $paths );
307 }
308
309 /**
310 * Substitute the backend name in storage path parameters
311 * for a set of operations with that of a given internal backend.
312 *
313 * @param $ops Array List of file operation arrays
314 * @param $backend FileBackendStore
315 * @return Array
316 */
317 protected function substOpBatchPaths( array $ops, FileBackendStore $backend ) {
318 $newOps = array(); // operations
319 foreach ( $ops as $op ) {
320 $newOp = $op; // operation
321 foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
322 if ( isset( $newOp[$par] ) ) { // string or array
323 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
324 }
325 }
326 $newOps[] = $newOp;
327 }
328 return $newOps;
329 }
330
331 /**
332 * Same as substOpBatchPaths() but for a single operation
333 *
334 * @param $ops array File operation array
335 * @param $backend FileBackendStore
336 * @return Array
337 */
338 protected function substOpPaths( array $ops, FileBackendStore $backend ) {
339 $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
340 return $newOps[0];
341 }
342
343 /**
344 * Substitute the backend of storage paths with an internal backend's name
345 *
346 * @param $paths Array|string List of paths or single string path
347 * @param $backend FileBackendStore
348 * @return Array|string
349 */
350 protected function substPaths( $paths, FileBackendStore $backend ) {
351 return preg_replace(
352 '!^mwstore://' . preg_quote( $this->name ) . '/!',
353 StringUtils::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
354 $paths // string or array
355 );
356 }
357
358 /**
359 * Substitute the backend of internal storage paths with the proxy backend's name
360 *
361 * @param $paths Array|string List of paths or single string path
362 * @return Array|string
363 */
364 protected function unsubstPaths( $paths ) {
365 return preg_replace(
366 '!^mwstore://([^/]+)!',
367 StringUtils::escapeRegexReplacement( "mwstore://{$this->name}" ),
368 $paths // string or array
369 );
370 }
371
372 /**
373 * @see FileBackend::doQuickOperationsInternal()
374 * @return Status
375 */
376 protected function doQuickOperationsInternal( array $ops ) {
377 $status = Status::newGood();
378 // Do the operations on the master backend; setting Status fields...
379 $realOps = $this->substOpBatchPaths( $ops, $this->backends[$this->masterIndex] );
380 $masterStatus = $this->backends[$this->masterIndex]->doQuickOperations( $realOps );
381 $status->merge( $masterStatus );
382 // Propagate the operations to the clone backends...
383 if ( !$this->noPushQuickOps ) {
384 foreach ( $this->backends as $index => $backend ) {
385 if ( $index !== $this->masterIndex ) { // not done already
386 $realOps = $this->substOpBatchPaths( $ops, $backend );
387 $status->merge( $backend->doQuickOperations( $realOps ) );
388 }
389 }
390 }
391 // Make 'success', 'successCount', and 'failCount' fields reflect
392 // the overall operation, rather than all the batches for each backend.
393 // Do this by only using success values from the master backend's batch.
394 $status->success = $masterStatus->success;
395 $status->successCount = $masterStatus->successCount;
396 $status->failCount = $masterStatus->failCount;
397 return $status;
398 }
399
400 /**
401 * @param $path string Storage path
402 * @return bool Path container should have dir changes pushed to all backends
403 */
404 protected function replicateContainerDirChanges( $path ) {
405 list( $b, $shortCont, $r ) = self::splitStoragePath( $path );
406 return !in_array( $shortCont, $this->noPushDirConts );
407 }
408
409 /**
410 * @see FileBackend::doPrepare()
411 * @return Status
412 */
413 protected function doPrepare( array $params ) {
414 $status = Status::newGood();
415 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
416 foreach ( $this->backends as $index => $backend ) {
417 if ( $replicate || $index == $this->masterIndex ) {
418 $realParams = $this->substOpPaths( $params, $backend );
419 $status->merge( $backend->doPrepare( $realParams ) );
420 }
421 }
422 return $status;
423 }
424
425 /**
426 * @see FileBackend::doSecure()
427 * @param $params array
428 * @return Status
429 */
430 protected function doSecure( array $params ) {
431 $status = Status::newGood();
432 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
433 foreach ( $this->backends as $index => $backend ) {
434 if ( $replicate || $index == $this->masterIndex ) {
435 $realParams = $this->substOpPaths( $params, $backend );
436 $status->merge( $backend->doSecure( $realParams ) );
437 }
438 }
439 return $status;
440 }
441
442 /**
443 * @see FileBackend::doPublish()
444 * @param $params array
445 * @return Status
446 */
447 protected function doPublish( array $params ) {
448 $status = Status::newGood();
449 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
450 foreach ( $this->backends as $index => $backend ) {
451 if ( $replicate || $index == $this->masterIndex ) {
452 $realParams = $this->substOpPaths( $params, $backend );
453 $status->merge( $backend->doPublish( $realParams ) );
454 }
455 }
456 return $status;
457 }
458
459 /**
460 * @see FileBackend::doClean()
461 * @param $params array
462 * @return Status
463 */
464 protected function doClean( array $params ) {
465 $status = Status::newGood();
466 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
467 foreach ( $this->backends as $index => $backend ) {
468 if ( $replicate || $index == $this->masterIndex ) {
469 $realParams = $this->substOpPaths( $params, $backend );
470 $status->merge( $backend->doClean( $realParams ) );
471 }
472 }
473 return $status;
474 }
475
476 /**
477 * @see FileBackend::concatenate()
478 * @param $params array
479 * @return Status
480 */
481 public function concatenate( array $params ) {
482 // We are writing to an FS file, so we don't need to do this per-backend
483 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
484 return $this->backends[$this->masterIndex]->concatenate( $realParams );
485 }
486
487 /**
488 * @see FileBackend::fileExists()
489 * @param $params array
490 */
491 public function fileExists( array $params ) {
492 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
493 return $this->backends[$this->masterIndex]->fileExists( $realParams );
494 }
495
496 /**
497 * @see FileBackend::getFileTimestamp()
498 * @param $params array
499 * @return bool|string
500 */
501 public function getFileTimestamp( array $params ) {
502 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
503 return $this->backends[$this->masterIndex]->getFileTimestamp( $realParams );
504 }
505
506 /**
507 * @see FileBackend::getFileSize()
508 * @param $params array
509 * @return bool|int
510 */
511 public function getFileSize( array $params ) {
512 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
513 return $this->backends[$this->masterIndex]->getFileSize( $realParams );
514 }
515
516 /**
517 * @see FileBackend::getFileStat()
518 * @param $params array
519 * @return Array|bool|null
520 */
521 public function getFileStat( array $params ) {
522 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
523 return $this->backends[$this->masterIndex]->getFileStat( $realParams );
524 }
525
526 /**
527 * @see FileBackend::getFileContents()
528 * @param $params array
529 * @return bool|string
530 */
531 public function getFileContents( array $params ) {
532 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
533 return $this->backends[$this->masterIndex]->getFileContents( $realParams );
534 }
535
536 /**
537 * @see FileBackend::getFileSha1Base36()
538 * @param $params array
539 * @return bool|string
540 */
541 public function getFileSha1Base36( array $params ) {
542 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
543 return $this->backends[$this->masterIndex]->getFileSha1Base36( $realParams );
544 }
545
546 /**
547 * @see FileBackend::getFileProps()
548 * @param $params array
549 * @return Array
550 */
551 public function getFileProps( array $params ) {
552 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
553 return $this->backends[$this->masterIndex]->getFileProps( $realParams );
554 }
555
556 /**
557 * @see FileBackend::streamFile()
558 * @param $params array
559 * @return \Status
560 */
561 public function streamFile( array $params ) {
562 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
563 return $this->backends[$this->masterIndex]->streamFile( $realParams );
564 }
565
566 /**
567 * @see FileBackend::getLocalReference()
568 * @param $params array
569 * @return FSFile|null
570 */
571 public function getLocalReference( array $params ) {
572 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
573 return $this->backends[$this->masterIndex]->getLocalReference( $realParams );
574 }
575
576 /**
577 * @see FileBackend::getLocalCopy()
578 * @param $params array
579 * @return null|TempFSFile
580 */
581 public function getLocalCopy( array $params ) {
582 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
583 return $this->backends[$this->masterIndex]->getLocalCopy( $realParams );
584 }
585
586 /**
587 * @see FileBackend::directoryExists()
588 * @param $params array
589 * @return bool|null
590 */
591 public function directoryExists( array $params ) {
592 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
593 return $this->backends[$this->masterIndex]->directoryExists( $realParams );
594 }
595
596 /**
597 * @see FileBackend::getSubdirectoryList()
598 * @param $params array
599 * @return Array|null|Traversable
600 */
601 public function getDirectoryList( array $params ) {
602 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
603 return $this->backends[$this->masterIndex]->getDirectoryList( $realParams );
604 }
605
606 /**
607 * @see FileBackend::getFileList()
608 * @param $params array
609 * @return Array|null|\Traversable
610 */
611 public function getFileList( array $params ) {
612 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
613 return $this->backends[$this->masterIndex]->getFileList( $realParams );
614 }
615
616 /**
617 * @see FileBackend::clearCache()
618 */
619 public function clearCache( array $paths = null ) {
620 foreach ( $this->backends as $backend ) {
621 $realPaths = is_array( $paths ) ? $this->substPaths( $paths, $backend ) : null;
622 $backend->clearCache( $realPaths );
623 }
624 }
625
626 /**
627 * @see FileBackend::getScopedLocksForOps()
628 */
629 public function getScopedLocksForOps( array $ops, Status $status ) {
630 $fileOps = $this->backends[$this->masterIndex]->getOperationsInternal( $ops );
631 // Get the paths to lock from the master backend
632 $paths = $this->backends[$this->masterIndex]->getPathsToLockForOpsInternal( $fileOps );
633 // Get the paths under the proxy backend's name
634 $paths['sh'] = $this->unsubstPaths( $paths['sh'] );
635 $paths['ex'] = $this->unsubstPaths( $paths['ex'] );
636 return array(
637 $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status ),
638 $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status )
639 );
640 }
641 }