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 array Prioritized list of FileBackendStore objects.
44 * array of (backend index => backends)
46 protected $backends = array();
48 /** @var int Index of master backend */
49 protected $masterIndex = -1;
51 /** @var int Bitfield */
52 protected $syncChecks = 0;
54 /** @var string|bool */
55 protected $autoResync = false;
57 /* Possible internal backend consistency checks */
63 * Construct a proxy backend that consists of several internal backends.
64 * Locking, journaling, and read-only checks are handled by the proxy backend.
66 * Additional $config params include:
67 * - backends : Array of backend config and multi-backend settings.
68 * Each value is the config used in the constructor of a
69 * FileBackendStore class, but with these additional settings:
70 * - class : The name of the backend class
71 * - isMultiMaster : This must be set for one backend.
72 * - template: : If given a backend name, this will use
73 * the config of that backend as a template.
74 * Values specified here take precedence.
75 * - syncChecks : Integer bitfield of internal backend sync checks to perform.
76 * Possible bits include the FileBackendMultiWrite::CHECK_* constants.
77 * There are constants for SIZE, TIME, and SHA1.
78 * The checks are done before allowing any file operations.
79 * - autoResync : Automatically resync the clone backends to the master backend
80 * when pre-operation sync checks fail. This should only be used
81 * if the master backend is stable and not missing any files.
82 * Use "conservative" to limit resyncing to copying newer master
83 * backend files over older (or non-existing) clone backend files.
84 * Cases that cannot be handled will result in operation abortion.
86 * @param array $config
87 * @throws FileBackendError
89 public function __construct( array $config ) {
90 parent
::__construct( $config );
91 $this->syncChecks
= isset( $config['syncChecks'] )
92 ?
$config['syncChecks']
94 $this->autoResync
= isset( $config['autoResync'] )
95 ?
$config['autoResync']
97 // Construct backends here rather than via registration
98 // to keep these backends hidden from outside the proxy.
100 foreach ( $config['backends'] as $index => $config ) {
101 if ( isset( $config['template'] ) ) {
102 // Config is just a modified version of a registered backend's.
103 // This should only be used when that config is used only by this backend.
104 $config = $config + FileBackendGroup
::singleton()->config( $config['template'] );
106 $name = $config['name'];
107 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
108 throw new FileBackendError( "Two or more backends defined with the name $name." );
110 $namesUsed[$name] = 1;
111 // Alter certain sub-backend settings for sanity
112 unset( $config['readOnly'] ); // use proxy backend setting
113 unset( $config['fileJournal'] ); // use proxy backend journal
114 unset( $config['lockManager'] ); // lock under proxy backend
115 $config['wikiId'] = $this->wikiId
; // use the proxy backend wiki ID
116 if ( !empty( $config['isMultiMaster'] ) ) {
117 if ( $this->masterIndex
>= 0 ) {
118 throw new FileBackendError( 'More than one master backend defined.' );
120 $this->masterIndex
= $index; // this is the "master"
121 $config['fileJournal'] = $this->fileJournal
; // log under proxy backend
123 // Create sub-backend object
124 if ( !isset( $config['class'] ) ) {
125 throw new FileBackendError( 'No class given for a backend config.' );
127 $class = $config['class'];
128 $this->backends
[$index] = new $class( $config );
130 if ( $this->masterIndex
< 0 ) { // need backends and must have a master
131 throw new FileBackendError( 'No master backend defined.' );
135 final protected function doOperationsInternal( array $ops, array $opts ) {
136 $status = Status
::newGood();
138 $mbe = $this->backends
[$this->masterIndex
]; // convenience
140 // Try to lock those files for the scope of this function...
141 if ( empty( $opts['nonLocking'] ) ) {
142 // Try to lock those files for the scope of this function...
143 $scopeLock = $this->getScopedLocksForOps( $ops, $status );
144 if ( !$status->isOK() ) {
145 return $status; // abort
148 // Clear any cache entries (after locks acquired)
150 $opts['preserveCache'] = true; // only locked files are cached
151 // Get the list of paths to read/write...
152 $relevantPaths = $this->fileStoragePathsForOps( $ops );
153 // Check if the paths are valid and accessible on all backends...
154 $status->merge( $this->accessibilityCheck( $relevantPaths ) );
155 if ( !$status->isOK() ) {
156 return $status; // abort
158 // Do a consistency check to see if the backends are consistent...
159 $syncStatus = $this->consistencyCheck( $relevantPaths );
160 if ( !$syncStatus->isOK() ) {
161 wfDebugLog( 'FileOperation', get_class( $this ) .
162 " failed sync check: " . FormatJson
::encode( $relevantPaths ) );
163 // Try to resync the clone backends to the master on the spot...
164 if ( !$this->autoResync ||
!$this->resyncFiles( $relevantPaths )->isOK() ) {
165 $status->merge( $syncStatus );
167 return $status; // abort
170 // Actually attempt the operation batch on the master backend...
171 $realOps = $this->substOpBatchPaths( $ops, $mbe );
172 $masterStatus = $mbe->doOperations( $realOps, $opts );
173 $status->merge( $masterStatus );
174 // Propagate the operations to the clone backends if there were no unexpected errors
175 // and if there were either no expected errors or if the 'force' option was used.
176 // However, if nothing succeeded at all, then don't replicate any of the operations.
177 // If $ops only had one operation, this might avoid backend sync inconsistencies.
178 if ( $masterStatus->isOK() && $masterStatus->successCount
> 0 ) {
179 foreach ( $this->backends
as $index => $backend ) {
180 if ( $index !== $this->masterIndex
) { // not done already
181 $realOps = $this->substOpBatchPaths( $ops, $backend );
182 $status->merge( $backend->doOperations( $realOps, $opts ) );
186 // Make 'success', 'successCount', and 'failCount' fields reflect
187 // the overall operation, rather than all the batches for each backend.
188 // Do this by only using success values from the master backend's batch.
189 $status->success
= $masterStatus->success
;
190 $status->successCount
= $masterStatus->successCount
;
191 $status->failCount
= $masterStatus->failCount
;
197 * Check that a set of files are consistent across all internal backends
199 * @param array $paths List of storage paths
202 public function consistencyCheck( array $paths ) {
203 $status = Status
::newGood();
204 if ( $this->syncChecks
== 0 ||
count( $this->backends
) <= 1 ) {
205 return $status; // skip checks
208 $mBackend = $this->backends
[$this->masterIndex
];
209 foreach ( $paths as $path ) {
210 $params = array( 'src' => $path, 'latest' => true );
211 $mParams = $this->substOpPaths( $params, $mBackend );
212 // Stat the file on the 'master' backend
213 $mStat = $mBackend->getFileStat( $mParams );
214 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
215 $mSha1 = $mBackend->getFileSha1Base36( $mParams );
219 // Check if all clone backends agree with the master...
220 foreach ( $this->backends
as $index => $cBackend ) {
221 if ( $index === $this->masterIndex
) {
224 $cParams = $this->substOpPaths( $params, $cBackend );
225 $cStat = $cBackend->getFileStat( $cParams );
226 if ( $mStat ) { // file is in master
227 if ( !$cStat ) { // file should exist
228 $status->fatal( 'backend-fail-synced', $path );
231 if ( $this->syncChecks
& self
::CHECK_SIZE
) {
232 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
233 $status->fatal( 'backend-fail-synced', $path );
237 if ( $this->syncChecks
& self
::CHECK_TIME
) {
238 $mTs = wfTimestamp( TS_UNIX
, $mStat['mtime'] );
239 $cTs = wfTimestamp( TS_UNIX
, $cStat['mtime'] );
240 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
241 $status->fatal( 'backend-fail-synced', $path );
245 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
246 if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
247 $status->fatal( 'backend-fail-synced', $path );
251 } else { // file is not in master
252 if ( $cStat ) { // file should not exist
253 $status->fatal( 'backend-fail-synced', $path );
263 * Check that a set of file paths are usable across all internal backends
265 * @param array $paths List of storage paths
268 public function accessibilityCheck( array $paths ) {
269 $status = Status
::newGood();
270 if ( count( $this->backends
) <= 1 ) {
271 return $status; // skip checks
274 foreach ( $paths as $path ) {
275 foreach ( $this->backends
as $backend ) {
276 $realPath = $this->substPaths( $path, $backend );
277 if ( !$backend->isPathUsableInternal( $realPath ) ) {
278 $status->fatal( 'backend-fail-usable', $path );
287 * Check that a set of files are consistent across all internal backends
288 * and re-synchronize those files against the "multi master" if needed.
290 * @param array $paths List of storage paths
293 public function resyncFiles( array $paths ) {
294 $status = Status
::newGood();
296 $mBackend = $this->backends
[$this->masterIndex
];
297 foreach ( $paths as $path ) {
298 $mPath = $this->substPaths( $path, $mBackend );
299 $mSha1 = $mBackend->getFileSha1Base36( array( 'src' => $mPath, 'latest' => true ) );
300 $mStat = $mBackend->getFileStat( array( 'src' => $mPath, 'latest' => true ) );
301 if ( $mStat === null ||
( $mSha1 !== false && !$mStat ) ) { // sanity
302 $status->fatal( 'backend-fail-internal', $this->name
);
303 wfDebugLog( 'FileOperation', __METHOD__
304 . ': File is not available on the master backend' );
305 continue; // file is not available on the master backend...
307 // Check of all clone backends agree with the master...
308 foreach ( $this->backends
as $index => $cBackend ) {
309 if ( $index === $this->masterIndex
) {
312 $cPath = $this->substPaths( $path, $cBackend );
313 $cSha1 = $cBackend->getFileSha1Base36( array( 'src' => $cPath, 'latest' => true ) );
314 $cStat = $cBackend->getFileStat( array( 'src' => $cPath, 'latest' => true ) );
315 if ( $cStat === null ||
( $cSha1 !== false && !$cStat ) ) { // sanity
316 $status->fatal( 'backend-fail-internal', $cBackend->getName() );
317 wfDebugLog( 'FileOperation', __METHOD__
.
318 ': File is not available on the clone backend' );
319 continue; // file is not available on the clone backend...
321 if ( $mSha1 === $cSha1 ) {
322 // already synced; nothing to do
323 } elseif ( $mSha1 !== false ) { // file is in master
324 if ( $this->autoResync
=== 'conservative'
325 && $cStat && $cStat['mtime'] > $mStat['mtime']
327 $status->fatal( 'backend-fail-synced', $path );
328 continue; // don't rollback data
330 $fsFile = $mBackend->getLocalReference(
331 array( 'src' => $mPath, 'latest' => true ) );
332 $status->merge( $cBackend->quickStore(
333 array( 'src' => $fsFile->getPath(), 'dst' => $cPath )
335 } elseif ( $mStat === false ) { // file is not in master
336 if ( $this->autoResync
=== 'conservative' ) {
337 $status->fatal( 'backend-fail-synced', $path );
338 continue; // don't delete data
340 $status->merge( $cBackend->quickDelete( array( 'src' => $cPath ) ) );
349 * Get a list of file storage paths to read or write for a list of operations
351 * @param array $ops Same format as doOperations()
352 * @return array List of storage paths to files (does not include directories)
354 protected function fileStoragePathsForOps( array $ops ) {
356 foreach ( $ops as $op ) {
357 if ( isset( $op['src'] ) ) {
358 // For things like copy/move/delete with "ignoreMissingSource" and there
359 // is no source file, nothing should happen and there should be no errors.
360 if ( empty( $op['ignoreMissingSource'] )
361 ||
$this->fileExists( array( 'src' => $op['src'] ) )
363 $paths[] = $op['src'];
366 if ( isset( $op['srcs'] ) ) {
367 $paths = array_merge( $paths, $op['srcs'] );
369 if ( isset( $op['dst'] ) ) {
370 $paths[] = $op['dst'];
374 return array_values( array_unique( array_filter( $paths, 'FileBackend::isStoragePath' ) ) );
378 * Substitute the backend name in storage path parameters
379 * for a set of operations with that of a given internal backend.
381 * @param array $ops List of file operation arrays
382 * @param FileBackendStore $backend
385 protected function substOpBatchPaths( array $ops, FileBackendStore
$backend ) {
386 $newOps = array(); // operations
387 foreach ( $ops as $op ) {
388 $newOp = $op; // operation
389 foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
390 if ( isset( $newOp[$par] ) ) { // string or array
391 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
401 * Same as substOpBatchPaths() but for a single operation
403 * @param array $ops File operation array
404 * @param FileBackendStore $backend
407 protected function substOpPaths( array $ops, FileBackendStore
$backend ) {
408 $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
414 * Substitute the backend of storage paths with an internal backend's name
416 * @param array|string $paths List of paths or single string path
417 * @param FileBackendStore $backend
418 * @return array|string
420 protected function substPaths( $paths, FileBackendStore
$backend ) {
422 '!^mwstore://' . preg_quote( $this->name
, '!' ) . '/!',
423 StringUtils
::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
424 $paths // string or array
429 * Substitute the backend of internal storage paths with the proxy backend's name
431 * @param array|string $paths List of paths or single string path
432 * @return array|string
434 protected function unsubstPaths( $paths ) {
436 '!^mwstore://([^/]+)!',
437 StringUtils
::escapeRegexReplacement( "mwstore://{$this->name}" ),
438 $paths // string or array
442 protected function doQuickOperationsInternal( array $ops ) {
443 $status = Status
::newGood();
444 // Do the operations on the master backend; setting Status fields...
445 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
446 $masterStatus = $this->backends
[$this->masterIndex
]->doQuickOperations( $realOps );
447 $status->merge( $masterStatus );
448 // Propagate the operations to the clone backends...
449 foreach ( $this->backends
as $index => $backend ) {
450 if ( $index !== $this->masterIndex
) { // not done already
451 $realOps = $this->substOpBatchPaths( $ops, $backend );
452 $status->merge( $backend->doQuickOperations( $realOps ) );
455 // Make 'success', 'successCount', and 'failCount' fields reflect
456 // the overall operation, rather than all the batches for each backend.
457 // Do this by only using success values from the master backend's batch.
458 $status->success
= $masterStatus->success
;
459 $status->successCount
= $masterStatus->successCount
;
460 $status->failCount
= $masterStatus->failCount
;
465 protected function doPrepare( array $params ) {
466 $status = Status
::newGood();
467 foreach ( $this->backends
as $index => $backend ) {
468 $realParams = $this->substOpPaths( $params, $backend );
469 $status->merge( $backend->doPrepare( $realParams ) );
475 protected function doSecure( array $params ) {
476 $status = Status
::newGood();
477 foreach ( $this->backends
as $index => $backend ) {
478 $realParams = $this->substOpPaths( $params, $backend );
479 $status->merge( $backend->doSecure( $realParams ) );
485 protected function doPublish( array $params ) {
486 $status = Status
::newGood();
487 foreach ( $this->backends
as $index => $backend ) {
488 $realParams = $this->substOpPaths( $params, $backend );
489 $status->merge( $backend->doPublish( $realParams ) );
495 protected function doClean( array $params ) {
496 $status = Status
::newGood();
497 foreach ( $this->backends
as $index => $backend ) {
498 $realParams = $this->substOpPaths( $params, $backend );
499 $status->merge( $backend->doClean( $realParams ) );
505 public function concatenate( array $params ) {
506 // We are writing to an FS file, so we don't need to do this per-backend
507 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
509 return $this->backends
[$this->masterIndex
]->concatenate( $realParams );
512 public function fileExists( array $params ) {
513 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
515 return $this->backends
[$this->masterIndex
]->fileExists( $realParams );
518 public function getFileTimestamp( array $params ) {
519 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
521 return $this->backends
[$this->masterIndex
]->getFileTimestamp( $realParams );
524 public function getFileSize( array $params ) {
525 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
527 return $this->backends
[$this->masterIndex
]->getFileSize( $realParams );
530 public function getFileStat( array $params ) {
531 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
533 return $this->backends
[$this->masterIndex
]->getFileStat( $realParams );
536 public function getFileXAttributes( array $params ) {
537 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
539 return $this->backends
[$this->masterIndex
]->getFileXAttributes( $realParams );
542 public function getFileContentsMulti( array $params ) {
543 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
544 $contentsM = $this->backends
[$this->masterIndex
]->getFileContentsMulti( $realParams );
546 $contents = array(); // (path => FSFile) mapping using the proxy backend's name
547 foreach ( $contentsM as $path => $data ) {
548 $contents[$this->unsubstPaths( $path )] = $data;
554 public function getFileSha1Base36( array $params ) {
555 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
557 return $this->backends
[$this->masterIndex
]->getFileSha1Base36( $realParams );
560 public function getFileProps( array $params ) {
561 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
563 return $this->backends
[$this->masterIndex
]->getFileProps( $realParams );
566 public function streamFile( array $params ) {
567 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
569 return $this->backends
[$this->masterIndex
]->streamFile( $realParams );
572 public function getLocalReferenceMulti( array $params ) {
573 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
574 $fsFilesM = $this->backends
[$this->masterIndex
]->getLocalReferenceMulti( $realParams );
576 $fsFiles = array(); // (path => FSFile) mapping using the proxy backend's name
577 foreach ( $fsFilesM as $path => $fsFile ) {
578 $fsFiles[$this->unsubstPaths( $path )] = $fsFile;
584 public function getLocalCopyMulti( array $params ) {
585 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
586 $tempFilesM = $this->backends
[$this->masterIndex
]->getLocalCopyMulti( $realParams );
588 $tempFiles = array(); // (path => TempFSFile) mapping using the proxy backend's name
589 foreach ( $tempFilesM as $path => $tempFile ) {
590 $tempFiles[$this->unsubstPaths( $path )] = $tempFile;
596 public function getFileHttpUrl( array $params ) {
597 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
599 return $this->backends
[$this->masterIndex
]->getFileHttpUrl( $realParams );
602 public function directoryExists( array $params ) {
603 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
605 return $this->backends
[$this->masterIndex
]->directoryExists( $realParams );
608 public function getDirectoryList( array $params ) {
609 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
611 return $this->backends
[$this->masterIndex
]->getDirectoryList( $realParams );
614 public function getFileList( array $params ) {
615 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
617 return $this->backends
[$this->masterIndex
]->getFileList( $realParams );
620 public function getFeatures() {
621 return $this->backends
[$this->masterIndex
]->getFeatures();
624 public function clearCache( array $paths = null ) {
625 foreach ( $this->backends
as $backend ) {
626 $realPaths = is_array( $paths ) ?
$this->substPaths( $paths, $backend ) : null;
627 $backend->clearCache( $realPaths );
631 public function preloadCache( array $paths ) {
632 $realPaths = $this->substPaths( $paths, $this->backends
[$this->masterIndex
] );
633 $this->backends
[$this->masterIndex
]->preloadCache( $realPaths );
636 public function preloadFileStat( array $params ) {
637 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
638 return $this->backends
[$this->masterIndex
]->preloadFileStat( $realParams );
641 public function getScopedLocksForOps( array $ops, Status
$status ) {
642 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
643 $fileOps = $this->backends
[$this->masterIndex
]->getOperationsInternal( $realOps );
644 // Get the paths to lock from the master backend
645 $paths = $this->backends
[$this->masterIndex
]->getPathsToLockForOpsInternal( $fileOps );
646 // Get the paths under the proxy backend's name
648 LockManager
::LOCK_UW
=> $this->unsubstPaths( $paths[LockManager
::LOCK_UW
] ),
649 LockManager
::LOCK_EX
=> $this->unsubstPaths( $paths[LockManager
::LOCK_EX
] )
652 // Actually acquire the locks
653 return array( $this->getScopedFileLocks( $pbPaths, 'mixed', $status ) );