MediaWiki 1.43.1
FileBackendMultiWrite.php
Go to the documentation of this file.
1<?php
24namespace Wikimedia\FileBackend;
25
26use InvalidArgumentException;
27use LockManager;
28use LogicException;
31use Shellbox\Command\BoxedCommand;
32use StatusValue;
33use StringUtils;
34use Wikimedia\Timestamp\ConvertibleTimestamp;
35
58 protected $backends = [];
59
61 protected $masterIndex = -1;
63 protected $readIndex = -1;
64
66 protected $syncChecks = 0;
68 protected $autoResync = false;
69
71 protected $asyncWrites = false;
72
74 private const CHECK_SIZE = 1;
76 private const CHECK_TIME = 2;
78 private const CHECK_SHA1 = 4;
79
107 public function __construct( array $config ) {
108 parent::__construct( $config );
109 $this->syncChecks = $config['syncChecks'] ?? self::CHECK_SIZE;
110 $this->autoResync = $config['autoResync'] ?? false;
111 $this->asyncWrites = isset( $config['replication'] ) && $config['replication'] === 'async';
112 // Construct backends here rather than via registration
113 // to keep these backends hidden from outside the proxy.
114 $namesUsed = [];
115 foreach ( $config['backends'] as $index => $beConfig ) {
116 $name = $beConfig['name'];
117 if ( isset( $namesUsed[$name] ) ) { // don't break FileOp predicates
118 throw new LogicException( "Two or more backends defined with the name $name." );
119 }
120 $namesUsed[$name] = 1;
121 // Alter certain sub-backend settings
122 unset( $beConfig['readOnly'] ); // use proxy backend setting
123 unset( $beConfig['lockManager'] ); // lock under proxy backend
124 $beConfig['domainId'] = $this->domainId; // use the proxy backend wiki ID
125 $beConfig['logger'] = $this->logger; // use the proxy backend logger
126 if ( !empty( $beConfig['isMultiMaster'] ) ) {
127 if ( $this->masterIndex >= 0 ) {
128 throw new LogicException( 'More than one master backend defined.' );
129 }
130 $this->masterIndex = $index; // this is the "master"
131 }
132 if ( !empty( $beConfig['readAffinity'] ) ) {
133 $this->readIndex = $index; // prefer this for reads
134 }
135 // Create sub-backend object
136 if ( !isset( $beConfig['class'] ) ) {
137 throw new InvalidArgumentException( 'No class given for a backend config.' );
138 }
139 $class = $beConfig['class'];
140 $this->backends[$index] = new $class( $beConfig );
141 }
142 if ( $this->masterIndex < 0 ) { // need backends and must have a master
143 throw new LogicException( 'No master backend defined.' );
144 }
145 if ( $this->readIndex < 0 ) {
146 $this->readIndex = $this->masterIndex; // default
147 }
148 }
149
150 final protected function doOperationsInternal( array $ops, array $opts ) {
151 $status = $this->newStatus();
152
153 $fname = __METHOD__;
154 $mbe = $this->backends[$this->masterIndex]; // convenience
155
156 // Acquire any locks as needed
157 $scopeLock = null;
158 if ( empty( $opts['nonLocking'] ) ) {
159 $scopeLock = $this->getScopedLocksForOps( $ops, $status );
160 if ( !$status->isOK() ) {
161 return $status; // abort
162 }
163 }
164 // Get the list of paths to read/write
165 $relevantPaths = $this->fileStoragePathsForOps( $ops );
166 // Clear any cache entries (after locks acquired)
167 $this->clearCache( $relevantPaths );
168 $opts['preserveCache'] = true; // only locked files are cached
169 // Check if the paths are valid and accessible on all backends
170 $status->merge( $this->accessibilityCheck( $relevantPaths ) );
171 if ( !$status->isOK() ) {
172 return $status; // abort
173 }
174 // Do a consistency check to see if the backends are consistent
175 $syncStatus = $this->consistencyCheck( $relevantPaths );
176 if ( !$syncStatus->isOK() ) {
177 $this->logger->error(
178 "$fname: failed sync check: " . FormatJson::encode( $relevantPaths )
179 );
180 // Try to resync the clone backends to the master on the spot
181 if (
182 $this->autoResync === false ||
183 !$this->resyncFiles( $relevantPaths, $this->autoResync )->isOK()
184 ) {
185 $status->merge( $syncStatus );
186
187 return $status; // abort
188 }
189 }
190 // Actually attempt the operation batch on the master backend
191 $realOps = $this->substOpBatchPaths( $ops, $mbe );
192 $masterStatus = $mbe->doOperations( $realOps, $opts );
193 $status->merge( $masterStatus );
194 // Propagate the operations to the clone backends if there were no unexpected errors
195 // and everything didn't fail due to predicted errors. If $ops only had one operation,
196 // this might avoid backend sync inconsistencies.
197 if ( $masterStatus->isOK() && $masterStatus->successCount > 0 ) {
198 foreach ( $this->backends as $index => $backend ) {
199 if ( $index === $this->masterIndex ) {
200 continue; // done already
201 }
202
203 $realOps = $this->substOpBatchPaths( $ops, $backend );
204 if ( $this->asyncWrites && !$this->hasVolatileSources( $ops ) ) {
205 // Bind $scopeLock to the callback to preserve locks
206 DeferredUpdates::addCallableUpdate(
207 function () use (
208 $backend, $realOps, $opts, $scopeLock, $relevantPaths, $fname
209 ) {
210 $this->logger->debug(
211 "$fname: '{$backend->getName()}' async replication; paths: " .
212 FormatJson::encode( $relevantPaths )
213 );
214 $backend->doOperations( $realOps, $opts );
215 }
216 );
217 } else {
218 $this->logger->debug(
219 "$fname: '{$backend->getName()}' sync replication; paths: " .
220 FormatJson::encode( $relevantPaths )
221 );
222 $status->merge( $backend->doOperations( $realOps, $opts ) );
223 }
224 }
225 }
226 // Make 'success', 'successCount', and 'failCount' fields reflect
227 // the overall operation, rather than all the batches for each backend.
228 // Do this by only using success values from the master backend's batch.
229 $status->success = $masterStatus->success;
230 $status->successCount = $masterStatus->successCount;
231 $status->failCount = $masterStatus->failCount;
232
233 return $status;
234 }
235
245 public function consistencyCheck( array $paths ) {
246 $status = $this->newStatus();
247 if ( $this->syncChecks == 0 || count( $this->backends ) <= 1 ) {
248 return $status; // skip checks
249 }
250
251 // Preload all of the stat info in as few round trips as possible
252 foreach ( $this->backends as $backend ) {
253 $realPaths = $this->substPaths( $paths, $backend );
254 $backend->preloadFileStat( [ 'srcs' => $realPaths, 'latest' => true ] );
255 }
256
257 foreach ( $paths as $path ) {
258 $params = [ 'src' => $path, 'latest' => true ];
259 // Get the state of the file on the master backend
260 $masterBackend = $this->backends[$this->masterIndex];
261 $masterParams = $this->substOpPaths( $params, $masterBackend );
262 $masterStat = $masterBackend->getFileStat( $masterParams );
263 if ( $masterStat === self::STAT_ERROR ) {
264 $status->fatal( 'backend-fail-stat', $path );
265 continue;
266 }
267 if ( $this->syncChecks & self::CHECK_SHA1 ) {
268 $masterSha1 = $masterBackend->getFileSha1Base36( $masterParams );
269 if ( ( $masterSha1 !== false ) !== (bool)$masterStat ) {
270 $status->fatal( 'backend-fail-hash', $path );
271 continue;
272 }
273 } else {
274 $masterSha1 = null; // unused
275 }
276
277 // Check if all clone backends agree with the master...
278 foreach ( $this->backends as $index => $cloneBackend ) {
279 if ( $index === $this->masterIndex ) {
280 continue; // master
281 }
282
283 // Get the state of the file on the clone backend
284 $cloneParams = $this->substOpPaths( $params, $cloneBackend );
285 $cloneStat = $cloneBackend->getFileStat( $cloneParams );
286
287 if ( $masterStat ) {
288 // File exists in the master backend
289 if ( !$cloneStat ) {
290 // File is missing from the clone backend
291 $status->fatal( 'backend-fail-synced', $path );
292 } elseif (
293 ( $this->syncChecks & self::CHECK_SIZE ) &&
294 $cloneStat['size'] !== $masterStat['size']
295 ) {
296 // File in the clone backend is different
297 $status->fatal( 'backend-fail-synced', $path );
298 } elseif (
299 ( $this->syncChecks & self::CHECK_TIME ) &&
300 abs(
301 (int)ConvertibleTimestamp::convert( TS_UNIX, $masterStat['mtime'] ) -
302 (int)ConvertibleTimestamp::convert( TS_UNIX, $cloneStat['mtime'] )
303 ) > 30
304 ) {
305 // File in the clone backend is significantly newer or older
306 $status->fatal( 'backend-fail-synced', $path );
307 } elseif (
308 ( $this->syncChecks & self::CHECK_SHA1 ) &&
309 $cloneBackend->getFileSha1Base36( $cloneParams ) !== $masterSha1
310 ) {
311 // File in the clone backend is different
312 $status->fatal( 'backend-fail-synced', $path );
313 }
314 } else {
315 // File does not exist in the master backend
316 if ( $cloneStat ) {
317 // Stray file exists in the clone backend
318 $status->fatal( 'backend-fail-synced', $path );
319 }
320 }
321 }
322 }
323
324 return $status;
325 }
326
333 public function accessibilityCheck( array $paths ) {
334 $status = $this->newStatus();
335 if ( count( $this->backends ) <= 1 ) {
336 return $status; // skip checks
337 }
338
339 foreach ( $paths as $path ) {
340 foreach ( $this->backends as $backend ) {
341 $realPath = $this->substPaths( $path, $backend );
342 if ( !$backend->isPathUsableInternal( $realPath ) ) {
343 $status->fatal( 'backend-fail-usable', $path );
344 }
345 }
346 }
347
348 return $status;
349 }
350
361 public function resyncFiles( array $paths, $resyncMode = true ) {
362 $status = $this->newStatus();
363
364 $fname = __METHOD__;
365 foreach ( $paths as $path ) {
366 $params = [ 'src' => $path, 'latest' => true ];
367 // Get the state of the file on the master backend
368 $masterBackend = $this->backends[$this->masterIndex];
369 $masterParams = $this->substOpPaths( $params, $masterBackend );
370 $masterPath = $masterParams['src'];
371 $masterStat = $masterBackend->getFileStat( $masterParams );
372 if ( $masterStat === self::STAT_ERROR ) {
373 $status->fatal( 'backend-fail-stat', $path );
374 $this->logger->error( "$fname: file '$masterPath' is not available" );
375 continue;
376 }
377 $masterSha1 = $masterBackend->getFileSha1Base36( $masterParams );
378 if ( ( $masterSha1 !== false ) !== (bool)$masterStat ) {
379 $status->fatal( 'backend-fail-hash', $path );
380 $this->logger->error( "$fname: file '$masterPath' hash does not match stat" );
381 continue;
382 }
383
384 // Check of all clone backends agree with the master...
385 foreach ( $this->backends as $index => $cloneBackend ) {
386 if ( $index === $this->masterIndex ) {
387 continue; // master
388 }
389
390 // Get the state of the file on the clone backend
391 $cloneParams = $this->substOpPaths( $params, $cloneBackend );
392 $clonePath = $cloneParams['src'];
393 $cloneStat = $cloneBackend->getFileStat( $cloneParams );
394 if ( $cloneStat === self::STAT_ERROR ) {
395 $status->fatal( 'backend-fail-stat', $path );
396 $this->logger->error( "$fname: file '$clonePath' is not available" );
397 continue;
398 }
399 $cloneSha1 = $cloneBackend->getFileSha1Base36( $cloneParams );
400 if ( ( $cloneSha1 !== false ) !== (bool)$cloneStat ) {
401 $status->fatal( 'backend-fail-hash', $path );
402 $this->logger->error( "$fname: file '$clonePath' hash does not match stat" );
403 continue;
404 }
405
406 if ( $masterSha1 === $cloneSha1 ) {
407 // File is either the same in both backends or absent from both backends
408 $this->logger->debug( "$fname: file '$clonePath' matches '$masterPath'" );
409 } elseif ( $masterSha1 !== false ) {
410 // File is either missing from or different in the clone backend
411 if (
412 $resyncMode === 'conservative' &&
413 $cloneStat &&
414 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
415 $cloneStat['mtime'] > $masterStat['mtime']
416 ) {
417 // Do not replace files with older ones; reduces the risk of data loss
418 $status->fatal( 'backend-fail-synced', $path );
419 } else {
420 // Copy the master backend file to the clone backend in overwrite mode
421 $fsFile = $masterBackend->getLocalReference( $masterParams );
422 $status->merge( $cloneBackend->quickStore( [
423 'src' => $fsFile,
424 'dst' => $clonePath
425 ] ) );
426 }
427 } elseif ( $masterStat === false ) {
428 // Stray file exists in the clone backend
429 if ( $resyncMode === 'conservative' ) {
430 // Do not delete stray files; reduces the risk of data loss
431 $status->fatal( 'backend-fail-synced', $path );
432 $this->logger->error( "$fname: not allowed to delete file '$clonePath'" );
433 } else {
434 // Delete the stay file from the clone backend
435 $status->merge( $cloneBackend->quickDelete( [ 'src' => $clonePath ] ) );
436 }
437 }
438 }
439 }
440
441 if ( !$status->isOK() ) {
442 $this->logger->error( "$fname: failed to resync: " . FormatJson::encode( $paths ) );
443 }
444
445 return $status;
446 }
447
454 protected function fileStoragePathsForOps( array $ops ) {
455 $paths = [];
456 foreach ( $ops as $op ) {
457 if ( isset( $op['src'] ) ) {
458 // For things like copy/move/delete with "ignoreMissingSource" and there
459 // is no source file, nothing should happen and there should be no errors.
460 if ( empty( $op['ignoreMissingSource'] )
461 || $this->fileExists( [ 'src' => $op['src'] ] )
462 ) {
463 $paths[] = $op['src'];
464 }
465 }
466 if ( isset( $op['srcs'] ) ) {
467 $paths = array_merge( $paths, $op['srcs'] );
468 }
469 if ( isset( $op['dst'] ) ) {
470 $paths[] = $op['dst'];
471 }
472 }
473
474 return array_values( array_unique( array_filter( $paths, [ FileBackend::class, 'isStoragePath' ] ) ) );
475 }
476
485 protected function substOpBatchPaths( array $ops, FileBackendStore $backend ) {
486 $newOps = []; // operations
487 foreach ( $ops as $op ) {
488 $newOp = $op; // operation
489 foreach ( [ 'src', 'srcs', 'dst', 'dir' ] as $par ) {
490 if ( isset( $newOp[$par] ) ) { // string or array
491 $newOp[$par] = $this->substPaths( $newOp[$par], $backend );
492 }
493 }
494 $newOps[] = $newOp;
495 }
496
497 return $newOps;
498 }
499
507 protected function substOpPaths( array $ops, FileBackendStore $backend ) {
508 $newOps = $this->substOpBatchPaths( [ $ops ], $backend );
509
510 return $newOps[0];
511 }
512
520 protected function substPaths( $paths, FileBackendStore $backend ) {
521 return preg_replace(
522 '!^mwstore://' . preg_quote( $this->name, '!' ) . '/!',
523 StringUtils::escapeRegexReplacement( "mwstore://{$backend->getName()}/" ),
524 $paths // string or array
525 );
526 }
527
535 protected function unsubstPaths( $paths, FileBackendStore $backend ) {
536 return preg_replace(
537 '!^mwstore://' . preg_quote( $backend->getName(), '!' ) . '/!',
538 StringUtils::escapeRegexReplacement( "mwstore://{$this->name}/" ),
539 $paths // string or array
540 );
541 }
542
547 protected function hasVolatileSources( array $ops ) {
548 foreach ( $ops as $op ) {
549 if ( $op['op'] === 'store' && !isset( $op['srcRef'] ) ) {
550 return true; // source file might be deleted anytime after do*Operations()
551 }
552 }
553
554 return false;
555 }
556
557 protected function doQuickOperationsInternal( array $ops, array $opts ) {
558 $status = $this->newStatus();
559 // Do the operations on the master backend; setting StatusValue fields
560 $realOps = $this->substOpBatchPaths( $ops, $this->backends[$this->masterIndex] );
561 $masterStatus = $this->backends[$this->masterIndex]->doQuickOperations( $realOps );
562 $status->merge( $masterStatus );
563 // Propagate the operations to the clone backends...
564 foreach ( $this->backends as $index => $backend ) {
565 if ( $index === $this->masterIndex ) {
566 continue; // done already
567 }
568
569 $realOps = $this->substOpBatchPaths( $ops, $backend );
570 if ( $this->asyncWrites && !$this->hasVolatileSources( $ops ) ) {
571 DeferredUpdates::addCallableUpdate(
572 static function () use ( $backend, $realOps ) {
573 $backend->doQuickOperations( $realOps );
574 }
575 );
576 } else {
577 $status->merge( $backend->doQuickOperations( $realOps ) );
578 }
579 }
580 // Make 'success', 'successCount', and 'failCount' fields reflect
581 // the overall operation, rather than all the batches for each backend.
582 // Do this by only using success values from the master backend's batch.
583 $status->success = $masterStatus->success;
584 $status->successCount = $masterStatus->successCount;
585 $status->failCount = $masterStatus->failCount;
586
587 return $status;
588 }
589
590 protected function doPrepare( array $params ) {
591 return $this->doDirectoryOp( 'prepare', $params );
592 }
593
594 protected function doSecure( array $params ) {
595 return $this->doDirectoryOp( 'secure', $params );
596 }
597
598 protected function doPublish( array $params ) {
599 return $this->doDirectoryOp( 'publish', $params );
600 }
601
602 protected function doClean( array $params ) {
603 return $this->doDirectoryOp( 'clean', $params );
604 }
605
611 protected function doDirectoryOp( $method, array $params ) {
612 $status = $this->newStatus();
613
614 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
615 $masterStatus = $this->backends[$this->masterIndex]->$method( $realParams );
616 $status->merge( $masterStatus );
617
618 foreach ( $this->backends as $index => $backend ) {
619 if ( $index === $this->masterIndex ) {
620 continue; // already done
621 }
622
623 $realParams = $this->substOpPaths( $params, $backend );
624 if ( $this->asyncWrites ) {
625 DeferredUpdates::addCallableUpdate(
626 static function () use ( $backend, $method, $realParams ) {
627 $backend->$method( $realParams );
628 }
629 );
630 } else {
631 $status->merge( $backend->$method( $realParams ) );
632 }
633 }
634
635 return $status;
636 }
637
638 public function concatenate( array $params ) {
639 $status = $this->newStatus();
640 // We are writing to an FS file, so we don't need to do this per-backend
641 $index = $this->getReadIndexFromParams( $params );
642 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
643
644 $status->merge( $this->backends[$index]->concatenate( $realParams ) );
645
646 return $status;
647 }
648
649 public function fileExists( array $params ) {
650 $index = $this->getReadIndexFromParams( $params );
651 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
652
653 return $this->backends[$index]->fileExists( $realParams );
654 }
655
656 public function getFileTimestamp( array $params ) {
657 $index = $this->getReadIndexFromParams( $params );
658 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
659
660 return $this->backends[$index]->getFileTimestamp( $realParams );
661 }
662
663 public function getFileSize( array $params ) {
664 $index = $this->getReadIndexFromParams( $params );
665 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
666
667 return $this->backends[$index]->getFileSize( $realParams );
668 }
669
670 public function getFileStat( array $params ) {
671 $index = $this->getReadIndexFromParams( $params );
672 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
673
674 return $this->backends[$index]->getFileStat( $realParams );
675 }
676
677 public function getFileXAttributes( array $params ) {
678 $index = $this->getReadIndexFromParams( $params );
679 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
680
681 return $this->backends[$index]->getFileXAttributes( $realParams );
682 }
683
684 public function getFileContentsMulti( array $params ) {
685 $index = $this->getReadIndexFromParams( $params );
686 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
687
688 $contentsM = $this->backends[$index]->getFileContentsMulti( $realParams );
689
690 $contents = []; // (path => FSFile) mapping using the proxy backend's name
691 foreach ( $contentsM as $path => $data ) {
692 $contents[$this->unsubstPaths( $path, $this->backends[$index] )] = $data;
693 }
694
695 return $contents;
696 }
697
698 public function getFileSha1Base36( array $params ) {
699 $index = $this->getReadIndexFromParams( $params );
700 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
701
702 return $this->backends[$index]->getFileSha1Base36( $realParams );
703 }
704
705 public function getFileProps( array $params ) {
706 $index = $this->getReadIndexFromParams( $params );
707 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
708
709 return $this->backends[$index]->getFileProps( $realParams );
710 }
711
712 public function streamFile( array $params ) {
713 $index = $this->getReadIndexFromParams( $params );
714 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
715
716 return $this->backends[$index]->streamFile( $realParams );
717 }
718
719 public function getLocalReferenceMulti( array $params ) {
720 $index = $this->getReadIndexFromParams( $params );
721 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
722
723 $fsFilesM = $this->backends[$index]->getLocalReferenceMulti( $realParams );
724
725 $fsFiles = []; // (path => FSFile) mapping using the proxy backend's name
726 foreach ( $fsFilesM as $path => $fsFile ) {
727 $fsFiles[$this->unsubstPaths( $path, $this->backends[$index] )] = $fsFile;
728 }
729
730 return $fsFiles;
731 }
732
733 public function getLocalCopyMulti( array $params ) {
734 $index = $this->getReadIndexFromParams( $params );
735 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
736
737 $tempFilesM = $this->backends[$index]->getLocalCopyMulti( $realParams );
738
739 $tempFiles = []; // (path => TempFSFile) mapping using the proxy backend's name
740 foreach ( $tempFilesM as $path => $tempFile ) {
741 $tempFiles[$this->unsubstPaths( $path, $this->backends[$index] )] = $tempFile;
742 }
743
744 return $tempFiles;
745 }
746
747 public function getFileHttpUrl( array $params ) {
748 $index = $this->getReadIndexFromParams( $params );
749 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
750
751 return $this->backends[$index]->getFileHttpUrl( $realParams );
752 }
753
754 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
755 array $params
756 ) {
757 $index = $this->getReadIndexFromParams( $params );
758 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
759 return $this->backends[$index]->addShellboxInputFile( $command, $boxedName, $realParams );
760 }
761
762 public function directoryExists( array $params ) {
763 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
764
765 return $this->backends[$this->masterIndex]->directoryExists( $realParams );
766 }
767
768 public function getDirectoryList( array $params ) {
769 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
770
771 return $this->backends[$this->masterIndex]->getDirectoryList( $realParams );
772 }
773
774 public function getFileList( array $params ) {
775 if ( isset( $params['forWrite'] ) && $params['forWrite'] ) {
776 return $this->getFileListForWrite( $params );
777 }
778
779 $realParams = $this->substOpPaths( $params, $this->backends[$this->masterIndex] );
780 return $this->backends[$this->masterIndex]->getFileList( $realParams );
781 }
782
783 private function getFileListForWrite( $params ) {
784 $files = [];
785 // Get the list of thumbnails from all backends to allow
786 // deleting all of them. Otherwise, old thumbnails existing on
787 // one backend only won't get updated in reupload (T331138).
788 foreach ( $this->backends as $backend ) {
789 $realParams = $this->substOpPaths( $params, $backend );
790 $iterator = $backend->getFileList( $realParams );
791 if ( $iterator !== null ) {
792 foreach ( $iterator as $file ) {
793 $files[] = $file;
794 }
795 }
796 }
797
798 return array_unique( $files );
799 }
800
801 public function getFeatures() {
802 return $this->backends[$this->masterIndex]->getFeatures();
803 }
804
805 public function clearCache( ?array $paths = null ) {
806 foreach ( $this->backends as $backend ) {
807 $realPaths = is_array( $paths ) ? $this->substPaths( $paths, $backend ) : null;
808 $backend->clearCache( $realPaths );
809 }
810 }
811
812 public function preloadCache( array $paths ) {
813 $realPaths = $this->substPaths( $paths, $this->backends[$this->readIndex] );
814 $this->backends[$this->readIndex]->preloadCache( $realPaths );
815 }
816
817 public function preloadFileStat( array $params ) {
818 $index = $this->getReadIndexFromParams( $params );
819 $realParams = $this->substOpPaths( $params, $this->backends[$index] );
820
821 return $this->backends[$index]->preloadFileStat( $realParams );
822 }
823
824 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
825 $realOps = $this->substOpBatchPaths( $ops, $this->backends[$this->masterIndex] );
826 $fileOps = $this->backends[$this->masterIndex]->getOperationsInternal( $realOps );
827 // Get the paths to lock from the master backend
828 $paths = $this->backends[$this->masterIndex]->getPathsToLockForOpsInternal( $fileOps );
829 // Get the paths under the proxy backend's name
830 $pbPaths = [
831 LockManager::LOCK_UW => $this->unsubstPaths(
832 $paths[LockManager::LOCK_UW],
833 $this->backends[$this->masterIndex]
834 ),
835 LockManager::LOCK_EX => $this->unsubstPaths(
836 $paths[LockManager::LOCK_EX],
837 $this->backends[$this->masterIndex]
838 )
839 ];
840
841 // Actually acquire the locks
842 return $this->getScopedFileLocks( $pbPaths, 'mixed', $status );
843 }
844
849 protected function getReadIndexFromParams( array $params ) {
850 return !empty( $params['latest'] ) ? $this->masterIndex : $this->readIndex;
851 }
852}
853
855class_alias( FileBackendMultiWrite::class, 'FileBackendMultiWrite' );
array $params
The job parameters.
Resource locking handling.
Defer callable updates to run later in the PHP process.
JSON formatter wrapper class.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
A collection of static methods to play with strings.
Proxy backend that mirrors writes to several internal backends.
getScopedLocksForOps(array $ops, StatusValue $status)
Get an array of scoped locks needed for a batch of file operations.
getFileXAttributes(array $params)
Get metadata about a file at a storage path in the backend.
streamFile(array $params)
Stream the content of the file at a storage path in the backend.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the content of the file at a storage path in the backend.
fileStoragePathsForOps(array $ops)
Get a list of file storage paths to read or write for a list of operations.
substPaths( $paths, FileBackendStore $backend)
Substitute the backend of storage paths with an internal backend's name.
__construct(array $config)
Construct a proxy backend that consists of several internal backends.
consistencyCheck(array $paths)
Check that a set of files are consistent across all internal backends.
directoryExists(array $params)
Check if a directory exists at a given storage path.
FileBackendStore[] $backends
Prioritized list of FileBackendStore objects.
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
getFileProps(array $params)
Get the properties of the content of the file at a storage path in the backend.
int $readIndex
Index of read affinity backend.
unsubstPaths( $paths, FileBackendStore $backend)
Substitute the backend of internal storage paths with the proxy backend's name.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
getFileHttpUrl(array $params)
Return an HTTP URL to a given file that requires no authentication to use.
substOpBatchPaths(array $ops, FileBackendStore $backend)
Substitute the backend name in storage path parameters for a set of operations with that of a given i...
concatenate(array $params)
Concatenate a list of storage files into a single file system file.
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and yields an order-preserved map ...
preloadCache(array $paths)
Preload persistent file stat cache and property cache into in-process cache.
getLocalCopyMulti(array $params)
Like getLocalCopy() except it takes an array of storage paths and yields an order preserved-map of st...
accessibilityCheck(array $paths)
Check that a set of file paths are usable across all internal backends.
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
getDirectoryList(array $params)
Get an iterator to list all directories under a storage directory.
clearCache(?array $paths=null)
Invalidate any in-process file stat and property cache.
resyncFiles(array $paths, $resyncMode=true)
Check that a set of files are consistent across all internal backends and re-synchronize those files ...
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
substOpPaths(array $ops, FileBackendStore $backend)
Same as substOpBatchPaths() but for a single operation.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
getFileContentsMulti(array $params)
Like getFileContents() except it takes an array of storage paths and returns an order preserved map o...
addShellboxInputFile(BoxedCommand $command, string $boxedName, array $params)
Add a file to a Shellbox command as an input file.
Base class for all backends using particular storage medium.
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
getName()
Get the unique backend name.
newStatus(... $args)
Yields the result of the status wrapper callback on either:
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
string $domainId
Unique domain name.