3 * Proxy backend that mirrors writes to several internal backends.
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
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Proxy backend that mirrors writes to several internal backends.
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.
33 * Only use this class when transitioning from one storage system to another.
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.
39 * @ingroup FileBackend
42 class FileBackendMultiWrite
extends FileBackend
{
43 /** @var FileBackendStore[] Prioritized list of FileBackendStore objects */
44 protected $backends = array();
46 /** @var int Index of master backend */
47 protected $masterIndex = -1;
49 /** @var int Bitfield */
50 protected $syncChecks = 0;
52 /** @var string|bool */
53 protected $autoResync = false;
56 protected $noPushDirConts = array();
59 protected $noPushQuickOps = false;
61 /* Possible internal backend consistency checks */
67 * Construct a proxy backend that consists of several internal backends.
68 * Locking, journaling, and read-only checks are handled by the proxy backend.
70 * Additional $config params include:
71 * - backends : Array of backend config and multi-backend settings.
72 * Each value is the config used in the constructor of a
73 * FileBackendStore class, but with these additional settings:
74 * - class : The name of the backend class
75 * - isMultiMaster : This must be set for one backend.
76 * - template: : If given a backend name, this will use
77 * the config of that backend as a template.
78 * Values specified here take precedence.
79 * - syncChecks : Integer bitfield of internal backend sync checks to perform.
80 * Possible bits include the FileBackendMultiWrite::CHECK_* constants.
81 * There are constants for SIZE, TIME, and SHA1.
82 * The checks are done before allowing any file operations.
83 * - autoResync : Automatically resync the clone backends to the master backend
84 * when pre-operation sync checks fail. This should only be used
85 * if the master backend is stable and not missing any files.
86 * Use "conservative" to limit resyncing to copying newer master
87 * backend files over older (or non-existing) clone backend files.
88 * Cases that cannot be handled will result in operation abortion.
89 * - noPushQuickOps : (hack) Only apply doQuickOperations() to the master backend.
90 * - noPushDirConts : (hack) Only apply directory functions to the master backend.
92 * @param array $config
93 * @throws FileBackendError
95 public function __construct( array $config ) {
96 parent
::__construct( $config );
97 $this->syncChecks
= isset( $config['syncChecks'] )
98 ?
$config['syncChecks']
100 $this->autoResync
= isset( $config['autoResync'] )
101 ?
$config['autoResync']
103 $this->noPushQuickOps
= isset( $config['noPushQuickOps'] )
104 ?
$config['noPushQuickOps']
106 $this->noPushDirConts
= isset( $config['noPushDirConts'] )
107 ?
$config['noPushDirConts']
109 // Construct backends here rather than via registration
110 // to keep these backends hidden from outside the proxy.
111 $namesUsed = array();
112 foreach ( $config['backends'] as $index => $config ) {
113 if ( isset( $config['template'] ) ) {
114 // Config is just a modified version of a registered backend's.
115 // This should only be used when that config is used only by this backend.
116 $config = $config + FileBackendGroup
::singleton()->config( $config['template'] );
118 $name = $config['name'];
119 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
120 throw new FileBackendError( "Two or more backends defined with the name $name." );
122 $namesUsed[$name] = 1;
123 // Alter certain sub-backend settings for sanity
124 unset( $config['readOnly'] ); // use proxy backend setting
125 unset( $config['fileJournal'] ); // use proxy backend journal
126 unset( $config['lockManager'] ); // lock under proxy backend
127 $config['wikiId'] = $this->wikiId
; // use the proxy backend wiki ID
128 if ( !empty( $config['isMultiMaster'] ) ) {
129 if ( $this->masterIndex
>= 0 ) {
130 throw new FileBackendError( 'More than one master backend defined.' );
132 $this->masterIndex
= $index; // this is the "master"
133 $config['fileJournal'] = $this->fileJournal
; // log under proxy backend
135 // Create sub-backend object
136 if ( !isset( $config['class'] ) ) {
137 throw new FileBackendError( 'No class given for a backend config.' );
139 $class = $config['class'];
140 $this->backends
[$index] = new $class( $config );
142 if ( $this->masterIndex
< 0 ) { // need backends and must have a master
143 throw new FileBackendError( 'No master backend defined.' );
147 final protected function doOperationsInternal( array $ops, array $opts ) {
148 $status = Status
::newGood();
150 $mbe = $this->backends
[$this->masterIndex
]; // convenience
152 // Try to lock those files for the scope of this function...
153 if ( empty( $opts['nonLocking'] ) ) {
154 // Try to lock those files for the scope of this function...
155 $scopeLock = $this->getScopedLocksForOps( $ops, $status );
156 if ( !$status->isOK() ) {
157 return $status; // abort
160 // Clear any cache entries (after locks acquired)
162 $opts['preserveCache'] = true; // only locked files are cached
163 // Get the list of paths to read/write...
164 $relevantPaths = $this->fileStoragePathsForOps( $ops );
165 // Check if the paths are valid and accessible on all backends...
166 $status->merge( $this->accessibilityCheck( $relevantPaths ) );
167 if ( !$status->isOK() ) {
168 return $status; // abort
170 // Do a consistency check to see if the backends are consistent...
171 $syncStatus = $this->consistencyCheck( $relevantPaths );
172 if ( !$syncStatus->isOK() ) {
173 wfDebugLog( 'FileOperation', get_class( $this ) .
174 " failed sync check: " . FormatJson
::encode( $relevantPaths ) );
175 // Try to resync the clone backends to the master on the spot...
176 if ( !$this->autoResync ||
!$this->resyncFiles( $relevantPaths )->isOK() ) {
177 $status->merge( $syncStatus );
179 return $status; // abort
182 // Actually attempt the operation batch on the master backend...
183 $realOps = $this->substOpBatchPaths( $ops, $mbe );
184 $masterStatus = $mbe->doOperations( $realOps, $opts );
185 $status->merge( $masterStatus );
186 // Propagate the operations to the clone backends if there were no unexpected errors
187 // and if there were either no expected errors or if the 'force' option was used.
188 // However, if nothing succeeded at all, then don't replicate any of the operations.
189 // If $ops only had one operation, this might avoid backend sync inconsistencies.
190 if ( $masterStatus->isOK() && $masterStatus->successCount
> 0 ) {
191 foreach ( $this->backends
as $index => $backend ) {
192 if ( $index !== $this->masterIndex
) { // not done already
193 $realOps = $this->substOpBatchPaths( $ops, $backend );
194 $status->merge( $backend->doOperations( $realOps, $opts ) );
198 // Make 'success', 'successCount', and 'failCount' fields reflect
199 // the overall operation, rather than all the batches for each backend.
200 // Do this by only using success values from the master backend's batch.
201 $status->success
= $masterStatus->success
;
202 $status->successCount
= $masterStatus->successCount
;
203 $status->failCount
= $masterStatus->failCount
;
209 * Check that a set of files are consistent across all internal backends
211 * @param array $paths List of storage paths
214 public function consistencyCheck( array $paths ) {
215 $status = Status
::newGood();
216 if ( $this->syncChecks
== 0 ||
count( $this->backends
) <= 1 ) {
217 return $status; // skip checks
220 $mBackend = $this->backends
[$this->masterIndex
];
221 foreach ( $paths as $path ) {
222 $params = array( 'src' => $path, 'latest' => true );
223 $mParams = $this->substOpPaths( $params, $mBackend );
224 // Stat the file on the 'master' backend
225 $mStat = $mBackend->getFileStat( $mParams );
226 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
227 $mSha1 = $mBackend->getFileSha1Base36( $mParams );
231 // Check if all clone backends agree with the master...
232 foreach ( $this->backends
as $index => $cBackend ) {
233 if ( $index === $this->masterIndex
) {
236 $cParams = $this->substOpPaths( $params, $cBackend );
237 $cStat = $cBackend->getFileStat( $cParams );
238 if ( $mStat ) { // file is in master
239 if ( !$cStat ) { // file should exist
240 $status->fatal( 'backend-fail-synced', $path );
243 if ( $this->syncChecks
& self
::CHECK_SIZE
) {
244 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
245 $status->fatal( 'backend-fail-synced', $path );
249 if ( $this->syncChecks
& self
::CHECK_TIME
) {
250 $mTs = wfTimestamp( TS_UNIX
, $mStat['mtime'] );
251 $cTs = wfTimestamp( TS_UNIX
, $cStat['mtime'] );
252 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
253 $status->fatal( 'backend-fail-synced', $path );
257 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
258 if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
259 $status->fatal( 'backend-fail-synced', $path );
263 } else { // file is not in master
264 if ( $cStat ) { // file should not exist
265 $status->fatal( 'backend-fail-synced', $path );
275 * Check that a set of file paths are usable across all internal backends
277 * @param array $paths List of storage paths
280 public function accessibilityCheck( array $paths ) {
281 $status = Status
::newGood();
282 if ( count( $this->backends
) <= 1 ) {
283 return $status; // skip checks
286 foreach ( $paths as $path ) {
287 foreach ( $this->backends
as $backend ) {
288 $realPath = $this->substPaths( $path, $backend );
289 if ( !$backend->isPathUsableInternal( $realPath ) ) {
290 $status->fatal( 'backend-fail-usable', $path );
299 * Check that a set of files are consistent across all internal backends
300 * and re-synchronize those files against the "multi master" if needed.
302 * @param array $paths List of storage paths
305 public function resyncFiles( array $paths ) {
306 $status = Status
::newGood();
308 $mBackend = $this->backends
[$this->masterIndex
];
309 foreach ( $paths as $path ) {
310 $mPath = $this->substPaths( $path, $mBackend );
311 $mSha1 = $mBackend->getFileSha1Base36( array( 'src' => $mPath, 'latest' => true ) );
312 $mStat = $mBackend->getFileStat( array( 'src' => $mPath, 'latest' => true ) );
313 if ( $mStat === null ||
( $mSha1 !== false && !$mStat ) ) { // sanity
314 $status->fatal( 'backend-fail-internal', $this->name
);
315 wfDebugLog( 'FileOperation', __METHOD__
316 . ': File is not available on the master backend' );
317 continue; // file is not available on the master backend...
319 // Check of all clone backends agree with the master...
320 foreach ( $this->backends
as $index => $cBackend ) {
321 if ( $index === $this->masterIndex
) {
324 $cPath = $this->substPaths( $path, $cBackend );
325 $cSha1 = $cBackend->getFileSha1Base36( array( 'src' => $cPath, 'latest' => true ) );
326 $cStat = $cBackend->getFileStat( array( 'src' => $cPath, 'latest' => true ) );
327 if ( $cStat === null ||
( $cSha1 !== false && !$cStat ) ) { // sanity
328 $status->fatal( 'backend-fail-internal', $cBackend->getName() );
329 wfDebugLog( 'FileOperation', __METHOD__
.
330 ': File is not available on the clone backend' );
331 continue; // file is not available on the clone backend...
333 if ( $mSha1 === $cSha1 ) {
334 // already synced; nothing to do
335 } elseif ( $mSha1 !== false ) { // file is in master
336 if ( $this->autoResync
=== 'conservative'
337 && $cStat && $cStat['mtime'] > $mStat['mtime']
339 $status->fatal( 'backend-fail-synced', $path );
340 continue; // don't rollback data
342 $fsFile = $mBackend->getLocalReference(
343 array( 'src' => $mPath, 'latest' => true ) );
344 $status->merge( $cBackend->quickStore(
345 array( 'src' => $fsFile->getPath(), 'dst' => $cPath )
347 } elseif ( $mStat === false ) { // file is not in master
348 if ( $this->autoResync
=== 'conservative' ) {
349 $status->fatal( 'backend-fail-synced', $path );
350 continue; // don't delete data
352 $status->merge( $cBackend->quickDelete( array( 'src' => $cPath ) ) );
361 * Get a list of file storage paths to read or write for a list of operations
363 * @param array $ops Same format as doOperations()
364 * @return array List of storage paths to files (does not include directories)
366 protected function fileStoragePathsForOps( array $ops ) {
368 foreach ( $ops as $op ) {
369 if ( isset( $op['src'] ) ) {
370 // For things like copy/move/delete with "ignoreMissingSource" and there
371 // is no source file, nothing should happen and there should be no errors.
372 if ( empty( $op['ignoreMissingSource'] )
373 ||
$this->fileExists( array( 'src' => $op['src'] ) )
375 $paths[] = $op['src'];
378 if ( isset( $op['srcs'] ) ) {
379 $paths = array_merge( $paths, $op['srcs'] );
381 if ( isset( $op['dst'] ) ) {
382 $paths[] = $op['dst'];
386 return array_values( array_unique( array_filter( $paths, 'FileBackend::isStoragePath' ) ) );
390 * Substitute the backend name in storage path parameters
391 * for a set of operations with that of a given internal backend.
393 * @param array $ops List of file operation arrays
394 * @param FileBackendStore $backend
397 protected function substOpBatchPaths( array $ops, FileBackendStore
$backend ) {
398 $newOps = array(); // operations
399 foreach ( $ops as $op ) {
400 $newOp = $op; // operation
401 foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
402 if ( isset( $newOp[$par] ) ) { // string or array
403 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
413 * Same as substOpBatchPaths() but for a single operation
415 * @param array $ops File operation array
416 * @param FileBackendStore $backend
419 protected function substOpPaths( array $ops, FileBackendStore
$backend ) {
420 $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
426 * Substitute the backend of storage paths with an internal backend's name
428 * @param array|string $paths List of paths or single string path
429 * @param FileBackendStore $backend
430 * @return array|string
432 protected function substPaths( $paths, FileBackendStore
$backend ) {
434 '!^mwstore://' . preg_quote( $this->name
, '!' ) . '/!',
435 StringUtils
::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
436 $paths // string or array
441 * Substitute the backend of internal storage paths with the proxy backend's name
443 * @param array|string $paths List of paths or single string path
444 * @return array|string
446 protected function unsubstPaths( $paths ) {
448 '!^mwstore://([^/]+)!',
449 StringUtils
::escapeRegexReplacement( "mwstore://{$this->name}" ),
450 $paths // string or array
454 protected function doQuickOperationsInternal( array $ops ) {
455 $status = Status
::newGood();
456 // Do the operations on the master backend; setting Status fields...
457 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
458 $masterStatus = $this->backends
[$this->masterIndex
]->doQuickOperations( $realOps );
459 $status->merge( $masterStatus );
460 // Propagate the operations to the clone backends...
461 if ( !$this->noPushQuickOps
) {
462 foreach ( $this->backends
as $index => $backend ) {
463 if ( $index !== $this->masterIndex
) { // not done already
464 $realOps = $this->substOpBatchPaths( $ops, $backend );
465 $status->merge( $backend->doQuickOperations( $realOps ) );
469 // Make 'success', 'successCount', and 'failCount' fields reflect
470 // the overall operation, rather than all the batches for each backend.
471 // Do this by only using success values from the master backend's batch.
472 $status->success
= $masterStatus->success
;
473 $status->successCount
= $masterStatus->successCount
;
474 $status->failCount
= $masterStatus->failCount
;
480 * @param string $path Storage path
481 * @return bool Path container should have dir changes pushed to all backends
483 protected function replicateContainerDirChanges( $path ) {
484 list( , $shortCont, ) = self
::splitStoragePath( $path );
486 return !in_array( $shortCont, $this->noPushDirConts
);
489 protected function doPrepare( array $params ) {
490 $status = Status
::newGood();
491 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
492 foreach ( $this->backends
as $index => $backend ) {
493 if ( $replicate ||
$index == $this->masterIndex
) {
494 $realParams = $this->substOpPaths( $params, $backend );
495 $status->merge( $backend->doPrepare( $realParams ) );
502 protected function doSecure( array $params ) {
503 $status = Status
::newGood();
504 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
505 foreach ( $this->backends
as $index => $backend ) {
506 if ( $replicate ||
$index == $this->masterIndex
) {
507 $realParams = $this->substOpPaths( $params, $backend );
508 $status->merge( $backend->doSecure( $realParams ) );
515 protected function doPublish( array $params ) {
516 $status = Status
::newGood();
517 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
518 foreach ( $this->backends
as $index => $backend ) {
519 if ( $replicate ||
$index == $this->masterIndex
) {
520 $realParams = $this->substOpPaths( $params, $backend );
521 $status->merge( $backend->doPublish( $realParams ) );
528 protected function doClean( array $params ) {
529 $status = Status
::newGood();
530 $replicate = $this->replicateContainerDirChanges( $params['dir'] );
531 foreach ( $this->backends
as $index => $backend ) {
532 if ( $replicate ||
$index == $this->masterIndex
) {
533 $realParams = $this->substOpPaths( $params, $backend );
534 $status->merge( $backend->doClean( $realParams ) );
541 public function concatenate( array $params ) {
542 // We are writing to an FS file, so we don't need to do this per-backend
543 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
545 return $this->backends
[$this->masterIndex
]->concatenate( $realParams );
548 public function fileExists( array $params ) {
549 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
551 return $this->backends
[$this->masterIndex
]->fileExists( $realParams );
554 public function getFileTimestamp( array $params ) {
555 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
557 return $this->backends
[$this->masterIndex
]->getFileTimestamp( $realParams );
560 public function getFileSize( array $params ) {
561 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
563 return $this->backends
[$this->masterIndex
]->getFileSize( $realParams );
566 public function getFileStat( array $params ) {
567 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
569 return $this->backends
[$this->masterIndex
]->getFileStat( $realParams );
572 public function getFileXAttributes( array $params ) {
573 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
575 return $this->backends
[$this->masterIndex
]->getFileXAttributes( $realParams );
578 public function getFileContentsMulti( array $params ) {
579 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
580 $contentsM = $this->backends
[$this->masterIndex
]->getFileContentsMulti( $realParams );
582 $contents = array(); // (path => FSFile) mapping using the proxy backend's name
583 foreach ( $contentsM as $path => $data ) {
584 $contents[$this->unsubstPaths( $path )] = $data;
590 public function getFileSha1Base36( array $params ) {
591 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
593 return $this->backends
[$this->masterIndex
]->getFileSha1Base36( $realParams );
596 public function getFileProps( array $params ) {
597 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
599 return $this->backends
[$this->masterIndex
]->getFileProps( $realParams );
602 public function streamFile( array $params ) {
603 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
605 return $this->backends
[$this->masterIndex
]->streamFile( $realParams );
608 public function getLocalReferenceMulti( array $params ) {
609 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
610 $fsFilesM = $this->backends
[$this->masterIndex
]->getLocalReferenceMulti( $realParams );
612 $fsFiles = array(); // (path => FSFile) mapping using the proxy backend's name
613 foreach ( $fsFilesM as $path => $fsFile ) {
614 $fsFiles[$this->unsubstPaths( $path )] = $fsFile;
620 public function getLocalCopyMulti( array $params ) {
621 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
622 $tempFilesM = $this->backends
[$this->masterIndex
]->getLocalCopyMulti( $realParams );
624 $tempFiles = array(); // (path => TempFSFile) mapping using the proxy backend's name
625 foreach ( $tempFilesM as $path => $tempFile ) {
626 $tempFiles[$this->unsubstPaths( $path )] = $tempFile;
632 public function getFileHttpUrl( array $params ) {
633 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
635 return $this->backends
[$this->masterIndex
]->getFileHttpUrl( $realParams );
638 public function directoryExists( array $params ) {
639 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
641 return $this->backends
[$this->masterIndex
]->directoryExists( $realParams );
644 public function getDirectoryList( array $params ) {
645 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
647 return $this->backends
[$this->masterIndex
]->getDirectoryList( $realParams );
650 public function getFileList( array $params ) {
651 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
653 return $this->backends
[$this->masterIndex
]->getFileList( $realParams );
656 public function getFeatures() {
657 return $this->backends
[$this->masterIndex
]->getFeatures();
660 public function clearCache( array $paths = null ) {
661 foreach ( $this->backends
as $backend ) {
662 $realPaths = is_array( $paths ) ?
$this->substPaths( $paths, $backend ) : null;
663 $backend->clearCache( $realPaths );
667 public function preloadCache( array $paths ) {
668 $realPaths = $this->substPaths( $paths, $this->backends
[$this->masterIndex
] );
669 $this->backends
[$this->masterIndex
]->preloadCache( $realPaths );
672 public function preloadFileStat( array $params ) {
673 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
674 return $this->backends
[$this->masterIndex
]->preloadFileStat( $realParams );
677 public function getScopedLocksForOps( array $ops, Status
$status ) {
678 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
679 $fileOps = $this->backends
[$this->masterIndex
]->getOperationsInternal( $realOps );
680 // Get the paths to lock from the master backend
681 $paths = $this->backends
[$this->masterIndex
]->getPathsToLockForOpsInternal( $fileOps );
682 // Get the paths under the proxy backend's name
684 LockManager
::LOCK_UW
=> $this->unsubstPaths( $paths[LockManager
::LOCK_UW
] ),
685 LockManager
::LOCK_EX
=> $this->unsubstPaths( $paths[LockManager
::LOCK_EX
] )
688 // Actually acquire the locks
689 return $this->getScopedFileLocks( $pbPaths, 'mixed', $status );