10e5a1e6c06378ddf03819cafe60d0d65f804f5c
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, starting with the master.
37 * This makes a best-effort to have transactional semantics, but since requests
38 * may sometimes fail, the use of "autoResync" or background scripts to fix
39 * inconsistencies is important.
41 * @ingroup FileBackend
44 class FileBackendMultiWrite
extends FileBackend
{
45 /** @var FileBackendStore[] Prioritized list of FileBackendStore objects */
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 /** @noinspection PhpUnusedLocalVariableInspection */
144 $scopeLock = $this->getScopedLocksForOps( $ops, $status );
145 if ( !$status->isOK() ) {
146 return $status; // abort
149 // Clear any cache entries (after locks acquired)
151 $opts['preserveCache'] = true; // only locked files are cached
152 // Get the list of paths to read/write...
153 $relevantPaths = $this->fileStoragePathsForOps( $ops );
154 // Check if the paths are valid and accessible on all backends...
155 $status->merge( $this->accessibilityCheck( $relevantPaths ) );
156 if ( !$status->isOK() ) {
157 return $status; // abort
159 // Do a consistency check to see if the backends are consistent...
160 $syncStatus = $this->consistencyCheck( $relevantPaths );
161 if ( !$syncStatus->isOK() ) {
162 wfDebugLog( 'FileOperation', get_class( $this ) .
163 " failed sync check: " . FormatJson
::encode( $relevantPaths ) );
164 // Try to resync the clone backends to the master on the spot...
165 if ( !$this->autoResync ||
!$this->resyncFiles( $relevantPaths )->isOK() ) {
166 $status->merge( $syncStatus );
168 return $status; // abort
171 // Actually attempt the operation batch on the master backend...
172 $realOps = $this->substOpBatchPaths( $ops, $mbe );
173 $masterStatus = $mbe->doOperations( $realOps, $opts );
174 $status->merge( $masterStatus );
175 // Propagate the operations to the clone backends if there were no unexpected errors
176 // and if there were either no expected errors or if the 'force' option was used.
177 // However, if nothing succeeded at all, then don't replicate any of the operations.
178 // If $ops only had one operation, this might avoid backend sync inconsistencies.
179 if ( $masterStatus->isOK() && $masterStatus->successCount
> 0 ) {
180 foreach ( $this->backends
as $index => $backend ) {
181 if ( $index !== $this->masterIndex
) { // not done already
182 $realOps = $this->substOpBatchPaths( $ops, $backend );
183 $status->merge( $backend->doOperations( $realOps, $opts ) );
187 // Make 'success', 'successCount', and 'failCount' fields reflect
188 // the overall operation, rather than all the batches for each backend.
189 // Do this by only using success values from the master backend's batch.
190 $status->success
= $masterStatus->success
;
191 $status->successCount
= $masterStatus->successCount
;
192 $status->failCount
= $masterStatus->failCount
;
198 * Check that a set of files are consistent across all internal backends
200 * @param array $paths List of storage paths
203 public function consistencyCheck( array $paths ) {
204 $status = Status
::newGood();
205 if ( $this->syncChecks
== 0 ||
count( $this->backends
) <= 1 ) {
206 return $status; // skip checks
209 $mBackend = $this->backends
[$this->masterIndex
];
210 foreach ( $paths as $path ) {
211 $params = array( 'src' => $path, 'latest' => true );
212 $mParams = $this->substOpPaths( $params, $mBackend );
213 // Stat the file on the 'master' backend
214 $mStat = $mBackend->getFileStat( $mParams );
215 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
216 $mSha1 = $mBackend->getFileSha1Base36( $mParams );
220 // Check if all clone backends agree with the master...
221 foreach ( $this->backends
as $index => $cBackend ) {
222 if ( $index === $this->masterIndex
) {
225 $cParams = $this->substOpPaths( $params, $cBackend );
226 $cStat = $cBackend->getFileStat( $cParams );
227 if ( $mStat ) { // file is in master
228 if ( !$cStat ) { // file should exist
229 $status->fatal( 'backend-fail-synced', $path );
232 if ( $this->syncChecks
& self
::CHECK_SIZE
) {
233 if ( $cStat['size'] != $mStat['size'] ) { // wrong size
234 $status->fatal( 'backend-fail-synced', $path );
238 if ( $this->syncChecks
& self
::CHECK_TIME
) {
239 $mTs = wfTimestamp( TS_UNIX
, $mStat['mtime'] );
240 $cTs = wfTimestamp( TS_UNIX
, $cStat['mtime'] );
241 if ( abs( $mTs - $cTs ) > 30 ) { // outdated file somewhere
242 $status->fatal( 'backend-fail-synced', $path );
246 if ( $this->syncChecks
& self
::CHECK_SHA1
) {
247 if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
248 $status->fatal( 'backend-fail-synced', $path );
252 } else { // file is not in master
253 if ( $cStat ) { // file should not exist
254 $status->fatal( 'backend-fail-synced', $path );
264 * Check that a set of file paths are usable across all internal backends
266 * @param array $paths List of storage paths
269 public function accessibilityCheck( array $paths ) {
270 $status = Status
::newGood();
271 if ( count( $this->backends
) <= 1 ) {
272 return $status; // skip checks
275 foreach ( $paths as $path ) {
276 foreach ( $this->backends
as $backend ) {
277 $realPath = $this->substPaths( $path, $backend );
278 if ( !$backend->isPathUsableInternal( $realPath ) ) {
279 $status->fatal( 'backend-fail-usable', $path );
288 * Check that a set of files are consistent across all internal backends
289 * and re-synchronize those files against the "multi master" if needed.
291 * @param array $paths List of storage paths
294 public function resyncFiles( array $paths ) {
295 $status = Status
::newGood();
297 $mBackend = $this->backends
[$this->masterIndex
];
298 foreach ( $paths as $path ) {
299 $mPath = $this->substPaths( $path, $mBackend );
300 $mSha1 = $mBackend->getFileSha1Base36( array( 'src' => $mPath, 'latest' => true ) );
301 $mStat = $mBackend->getFileStat( array( 'src' => $mPath, 'latest' => true ) );
302 if ( $mStat === null ||
( $mSha1 !== false && !$mStat ) ) { // sanity
303 $status->fatal( 'backend-fail-internal', $this->name
);
304 wfDebugLog( 'FileOperation', __METHOD__
305 . ': File is not available on the master backend' );
306 continue; // file is not available on the master backend...
308 // Check of all clone backends agree with the master...
309 foreach ( $this->backends
as $index => $cBackend ) {
310 if ( $index === $this->masterIndex
) {
313 $cPath = $this->substPaths( $path, $cBackend );
314 $cSha1 = $cBackend->getFileSha1Base36( array( 'src' => $cPath, 'latest' => true ) );
315 $cStat = $cBackend->getFileStat( array( 'src' => $cPath, 'latest' => true ) );
316 if ( $cStat === null ||
( $cSha1 !== false && !$cStat ) ) { // sanity
317 $status->fatal( 'backend-fail-internal', $cBackend->getName() );
318 wfDebugLog( 'FileOperation', __METHOD__
.
319 ': File is not available on the clone backend' );
320 continue; // file is not available on the clone backend...
322 if ( $mSha1 === $cSha1 ) {
323 // already synced; nothing to do
324 } elseif ( $mSha1 !== false ) { // file is in master
325 if ( $this->autoResync
=== 'conservative'
326 && $cStat && $cStat['mtime'] > $mStat['mtime']
328 $status->fatal( 'backend-fail-synced', $path );
329 continue; // don't rollback data
331 $fsFile = $mBackend->getLocalReference(
332 array( 'src' => $mPath, 'latest' => true ) );
333 $status->merge( $cBackend->quickStore(
334 array( 'src' => $fsFile->getPath(), 'dst' => $cPath )
336 } elseif ( $mStat === false ) { // file is not in master
337 if ( $this->autoResync
=== 'conservative' ) {
338 $status->fatal( 'backend-fail-synced', $path );
339 continue; // don't delete data
341 $status->merge( $cBackend->quickDelete( array( 'src' => $cPath ) ) );
350 * Get a list of file storage paths to read or write for a list of operations
352 * @param array $ops Same format as doOperations()
353 * @return array List of storage paths to files (does not include directories)
355 protected function fileStoragePathsForOps( array $ops ) {
357 foreach ( $ops as $op ) {
358 if ( isset( $op['src'] ) ) {
359 // For things like copy/move/delete with "ignoreMissingSource" and there
360 // is no source file, nothing should happen and there should be no errors.
361 if ( empty( $op['ignoreMissingSource'] )
362 ||
$this->fileExists( array( 'src' => $op['src'] ) )
364 $paths[] = $op['src'];
367 if ( isset( $op['srcs'] ) ) {
368 $paths = array_merge( $paths, $op['srcs'] );
370 if ( isset( $op['dst'] ) ) {
371 $paths[] = $op['dst'];
375 return array_values( array_unique( array_filter( $paths, 'FileBackend::isStoragePath' ) ) );
379 * Substitute the backend name in storage path parameters
380 * for a set of operations with that of a given internal backend.
382 * @param array $ops List of file operation arrays
383 * @param FileBackendStore $backend
386 protected function substOpBatchPaths( array $ops, FileBackendStore
$backend ) {
387 $newOps = array(); // operations
388 foreach ( $ops as $op ) {
389 $newOp = $op; // operation
390 foreach ( array( 'src', 'srcs', 'dst', 'dir' ) as $par ) {
391 if ( isset( $newOp[$par] ) ) { // string or array
392 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
402 * Same as substOpBatchPaths() but for a single operation
404 * @param array $ops File operation array
405 * @param FileBackendStore $backend
408 protected function substOpPaths( array $ops, FileBackendStore
$backend ) {
409 $newOps = $this->substOpBatchPaths( array( $ops ), $backend );
415 * Substitute the backend of storage paths with an internal backend's name
417 * @param array|string $paths List of paths or single string path
418 * @param FileBackendStore $backend
419 * @return array|string
421 protected function substPaths( $paths, FileBackendStore
$backend ) {
423 '!^mwstore://' . preg_quote( $this->name
, '!' ) . '/!',
424 StringUtils
::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
425 $paths // string or array
430 * Substitute the backend of internal storage paths with the proxy backend's name
432 * @param array|string $paths List of paths or single string path
433 * @return array|string
435 protected function unsubstPaths( $paths ) {
437 '!^mwstore://([^/]+)!',
438 StringUtils
::escapeRegexReplacement( "mwstore://{$this->name}" ),
439 $paths // string or array
443 protected function doQuickOperationsInternal( array $ops ) {
444 $status = Status
::newGood();
445 // Do the operations on the master backend; setting Status fields...
446 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
447 $masterStatus = $this->backends
[$this->masterIndex
]->doQuickOperations( $realOps );
448 $status->merge( $masterStatus );
449 // Propagate the operations to the clone backends...
450 foreach ( $this->backends
as $index => $backend ) {
451 if ( $index !== $this->masterIndex
) { // not done already
452 $realOps = $this->substOpBatchPaths( $ops, $backend );
453 $status->merge( $backend->doQuickOperations( $realOps ) );
456 // Make 'success', 'successCount', and 'failCount' fields reflect
457 // the overall operation, rather than all the batches for each backend.
458 // Do this by only using success values from the master backend's batch.
459 $status->success
= $masterStatus->success
;
460 $status->successCount
= $masterStatus->successCount
;
461 $status->failCount
= $masterStatus->failCount
;
466 protected function doPrepare( array $params ) {
467 $status = Status
::newGood();
468 foreach ( $this->backends
as $index => $backend ) {
469 $realParams = $this->substOpPaths( $params, $backend );
470 $status->merge( $backend->doPrepare( $realParams ) );
476 protected function doSecure( array $params ) {
477 $status = Status
::newGood();
478 foreach ( $this->backends
as $index => $backend ) {
479 $realParams = $this->substOpPaths( $params, $backend );
480 $status->merge( $backend->doSecure( $realParams ) );
486 protected function doPublish( array $params ) {
487 $status = Status
::newGood();
488 foreach ( $this->backends
as $index => $backend ) {
489 $realParams = $this->substOpPaths( $params, $backend );
490 $status->merge( $backend->doPublish( $realParams ) );
496 protected function doClean( array $params ) {
497 $status = Status
::newGood();
498 foreach ( $this->backends
as $index => $backend ) {
499 $realParams = $this->substOpPaths( $params, $backend );
500 $status->merge( $backend->doClean( $realParams ) );
506 public function concatenate( array $params ) {
507 // We are writing to an FS file, so we don't need to do this per-backend
508 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
510 return $this->backends
[$this->masterIndex
]->concatenate( $realParams );
513 public function fileExists( array $params ) {
514 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
516 return $this->backends
[$this->masterIndex
]->fileExists( $realParams );
519 public function getFileTimestamp( array $params ) {
520 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
522 return $this->backends
[$this->masterIndex
]->getFileTimestamp( $realParams );
525 public function getFileSize( array $params ) {
526 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
528 return $this->backends
[$this->masterIndex
]->getFileSize( $realParams );
531 public function getFileStat( array $params ) {
532 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
534 return $this->backends
[$this->masterIndex
]->getFileStat( $realParams );
537 public function getFileXAttributes( array $params ) {
538 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
540 return $this->backends
[$this->masterIndex
]->getFileXAttributes( $realParams );
543 public function getFileContentsMulti( array $params ) {
544 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
545 $contentsM = $this->backends
[$this->masterIndex
]->getFileContentsMulti( $realParams );
547 $contents = array(); // (path => FSFile) mapping using the proxy backend's name
548 foreach ( $contentsM as $path => $data ) {
549 $contents[$this->unsubstPaths( $path )] = $data;
555 public function getFileSha1Base36( array $params ) {
556 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
558 return $this->backends
[$this->masterIndex
]->getFileSha1Base36( $realParams );
561 public function getFileProps( array $params ) {
562 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
564 return $this->backends
[$this->masterIndex
]->getFileProps( $realParams );
567 public function streamFile( array $params ) {
568 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
570 return $this->backends
[$this->masterIndex
]->streamFile( $realParams );
573 public function getLocalReferenceMulti( array $params ) {
574 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
575 $fsFilesM = $this->backends
[$this->masterIndex
]->getLocalReferenceMulti( $realParams );
577 $fsFiles = array(); // (path => FSFile) mapping using the proxy backend's name
578 foreach ( $fsFilesM as $path => $fsFile ) {
579 $fsFiles[$this->unsubstPaths( $path )] = $fsFile;
585 public function getLocalCopyMulti( array $params ) {
586 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
587 $tempFilesM = $this->backends
[$this->masterIndex
]->getLocalCopyMulti( $realParams );
589 $tempFiles = array(); // (path => TempFSFile) mapping using the proxy backend's name
590 foreach ( $tempFilesM as $path => $tempFile ) {
591 $tempFiles[$this->unsubstPaths( $path )] = $tempFile;
597 public function getFileHttpUrl( array $params ) {
598 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
600 return $this->backends
[$this->masterIndex
]->getFileHttpUrl( $realParams );
603 public function directoryExists( array $params ) {
604 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
606 return $this->backends
[$this->masterIndex
]->directoryExists( $realParams );
609 public function getDirectoryList( array $params ) {
610 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
612 return $this->backends
[$this->masterIndex
]->getDirectoryList( $realParams );
615 public function getFileList( array $params ) {
616 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
618 return $this->backends
[$this->masterIndex
]->getFileList( $realParams );
621 public function getFeatures() {
622 return $this->backends
[$this->masterIndex
]->getFeatures();
625 public function clearCache( array $paths = null ) {
626 foreach ( $this->backends
as $backend ) {
627 $realPaths = is_array( $paths ) ?
$this->substPaths( $paths, $backend ) : null;
628 $backend->clearCache( $realPaths );
632 public function preloadCache( array $paths ) {
633 $realPaths = $this->substPaths( $paths, $this->backends
[$this->masterIndex
] );
634 $this->backends
[$this->masterIndex
]->preloadCache( $realPaths );
637 public function preloadFileStat( array $params ) {
638 $realParams = $this->substOpPaths( $params, $this->backends
[$this->masterIndex
] );
639 return $this->backends
[$this->masterIndex
]->preloadFileStat( $realParams );
642 public function getScopedLocksForOps( array $ops, Status
$status ) {
643 $realOps = $this->substOpBatchPaths( $ops, $this->backends
[$this->masterIndex
] );
644 $fileOps = $this->backends
[$this->masterIndex
]->getOperationsInternal( $realOps );
645 // Get the paths to lock from the master backend
646 $paths = $this->backends
[$this->masterIndex
]->getPathsToLockForOpsInternal( $fileOps );
647 // Get the paths under the proxy backend's name
649 LockManager
::LOCK_UW
=> $this->unsubstPaths( $paths[LockManager
::LOCK_UW
] ),
650 LockManager
::LOCK_EX
=> $this->unsubstPaths( $paths[LockManager
::LOCK_EX
] )
653 // Actually acquire the locks
654 return $this->getScopedFileLocks( $pbPaths, 'mixed', $status );