MediaWiki master
FileBackendStore.php
Go to the documentation of this file.
1<?php
9
10namespace Wikimedia\FileBackend;
11
12use InvalidArgumentException;
13use Shellbox\Command\BoxedCommand;
14use StatusValue;
15use Traversable;
16use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardDirIterator;
17use Wikimedia\FileBackend\FileIteration\FileBackendStoreShardFileIterator;
18use Wikimedia\FileBackend\FileOpHandle\FileBackendStoreOpHandle;
19use Wikimedia\FileBackend\FileOps\CopyFileOp;
20use Wikimedia\FileBackend\FileOps\CreateFileOp;
21use Wikimedia\FileBackend\FileOps\DeleteFileOp;
22use Wikimedia\FileBackend\FileOps\DescribeFileOp;
23use Wikimedia\FileBackend\FileOps\FileOp;
24use Wikimedia\FileBackend\FileOps\MoveFileOp;
25use Wikimedia\FileBackend\FileOps\NullFileOp;
26use Wikimedia\FileBackend\FileOps\StoreFileOp;
27use Wikimedia\FileBackend\FSFile\FSFile;
28use Wikimedia\Http\HttpHeader;
29use Wikimedia\LockManager\LockManager;
30use Wikimedia\ObjectCache\BagOStuff;
31use Wikimedia\ObjectCache\EmptyBagOStuff;
32use Wikimedia\ObjectCache\MapCacheLRU;
33use Wikimedia\ObjectCache\WANObjectCache;
34
49abstract class FileBackendStore extends FileBackend {
62
66 protected $memCache;
67
69 protected $shardViaHashLevels = [];
70
72 protected $mimeCallback;
73
75 protected $maxFileSize = 32 * 1024 * 1024 * 1024;
76
77 protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
78 protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
79 protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
80
82 protected const RES_ABSENT = false;
84 protected const RES_ERROR = null;
85
87 protected const ABSENT_NORMAL = 'FNE-N';
89 protected const ABSENT_LATEST = 'FNE-L';
90
104 public function __construct( array $config ) {
105 parent::__construct( $config );
106 $this->mimeCallback = $config['mimeCallback'] ?? null;
107 $this->srvCache = $config['srvCache'] ?? new EmptyBagOStuff();
108 $this->wanCache = $config['wanCache'] ?? WANObjectCache::newEmpty();
109 $this->wanStatCache = WANObjectCache::newEmpty(); // disabled by default
110 $this->memCache =& $this->wanStatCache; // compatibility alias
111 $this->procFileStatCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
112 $this->cheapCache =& $this->procFileStatCache; // compatability alias
113 $this->procFileDataCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
114 $this->expensiveCache =& $this->procFileDataCache; // compatability alias
115 }
116
124 final public function maxFileSizeInternal() {
125 return min( $this->maxFileSize, PHP_INT_MAX );
126 }
127
139 abstract public function isPathUsableInternal( $storagePath );
140
159 final public function createInternal( array $params ) {
160 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
161 $status = $this->newStatus( 'backend-fail-maxsize',
162 $params['dst'], $this->maxFileSizeInternal() );
163 } else {
164 $status = $this->doCreateInternal( $params );
165 $this->clearCache( [ $params['dst'] ] );
166 if ( $params['dstExists'] ?? true ) {
167 $this->deleteFileCache( $params['dst'] ); // persistent cache
168 }
169 }
170
171 return $status;
172 }
173
179 abstract protected function doCreateInternal( array $params );
180
199 final public function storeInternal( array $params ) {
200 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
201 $status = $this->newStatus( 'backend-fail-maxsize',
202 $params['dst'], $this->maxFileSizeInternal() );
203 } else {
204 $status = $this->doStoreInternal( $params );
205 $this->clearCache( [ $params['dst'] ] );
206 if ( $params['dstExists'] ?? true ) {
207 $this->deleteFileCache( $params['dst'] ); // persistent cache
208 }
209 }
210
211 return $status;
212 }
213
219 abstract protected function doStoreInternal( array $params );
220
240 final public function copyInternal( array $params ) {
241 $status = $this->doCopyInternal( $params );
242 $this->clearCache( [ $params['dst'] ] );
243 if ( $params['dstExists'] ?? true ) {
244 $this->deleteFileCache( $params['dst'] ); // persistent cache
245 }
246
247 return $status;
248 }
249
255 abstract protected function doCopyInternal( array $params );
256
271 final public function deleteInternal( array $params ) {
272 $status = $this->doDeleteInternal( $params );
273 $this->clearCache( [ $params['src'] ] );
274 $this->deleteFileCache( $params['src'] ); // persistent cache
275 return $status;
276 }
277
283 abstract protected function doDeleteInternal( array $params );
284
304 final public function moveInternal( array $params ) {
305 $status = $this->doMoveInternal( $params );
306 $this->clearCache( [ $params['src'], $params['dst'] ] );
307 $this->deleteFileCache( $params['src'] ); // persistent cache
308 if ( $params['dstExists'] ?? true ) {
309 $this->deleteFileCache( $params['dst'] ); // persistent cache
310 }
311
312 return $status;
313 }
314
320 abstract protected function doMoveInternal( array $params );
321
336 final public function describeInternal( array $params ) {
337 if ( count( $params['headers'] ) ) {
338 $status = $this->doDescribeInternal( $params );
339 $this->clearCache( [ $params['src'] ] );
340 $this->deleteFileCache( $params['src'] ); // persistent cache
341 } else {
342 $status = $this->newStatus(); // nothing to do
343 }
344
345 return $status;
346 }
347
354 protected function doDescribeInternal( array $params ) {
355 return $this->newStatus();
356 }
357
365 final public function nullInternal( array $params ) {
366 return $this->newStatus();
367 }
368
370 final public function concatenate( array $params ) {
371 $status = $this->newStatus();
372 // Try to lock the source files for the scope of this function
374 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
375 if ( $status->isOK() ) {
376 // Actually do the file concatenation...
377 $hrStart = hrtime( true );
378 $status->merge( $this->doConcatenate( $params ) );
379 $sec = ( hrtime( true ) - $hrStart ) / 1e9;
380 if ( !$status->isOK() ) {
381 $this->logger->error( static::class . "-{$this->name}" .
382 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
383 }
384 }
385
386 return $status;
387 }
388
395 protected function doConcatenate( array $params ) {
396 $status = $this->newStatus();
397 $tmpPath = $params['dst'];
398 unset( $params['latest'] );
399
400 // Check that the specified temp file is valid...
401 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
402 $ok = ( @is_file( $tmpPath ) && @filesize( $tmpPath ) == 0 );
403 if ( !$ok ) { // not present or not empty
404 $status->fatal( 'backend-fail-opentemp', $tmpPath );
405
406 return $status;
407 }
408
409 // Get local FS versions of the chunks needed for the concatenation...
410 $fsFiles = $this->getLocalReferenceMulti( $params );
411 foreach ( $fsFiles as $path => &$fsFile ) {
412 if ( !$fsFile ) { // chunk failed to download?
413 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
414 if ( !$fsFile ) { // retry failed?
415 $status->fatal(
416 $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
417 $path
418 );
419
420 return $status;
421 }
422 }
423 }
424 unset( $fsFile ); // unset reference so we can reuse $fsFile
425
426 // Get a handle for the destination temp file
427 $tmpHandle = fopen( $tmpPath, 'ab' );
428 if ( $tmpHandle === false ) {
429 $status->fatal( 'backend-fail-opentemp', $tmpPath );
430
431 return $status;
432 }
433
434 // Build up the temp file using the source chunks (in order)...
435 foreach ( $fsFiles as $virtualSource => $fsFile ) {
436 // Get a handle to the local FS version
437 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
438 if ( $sourceHandle === false ) {
439 fclose( $tmpHandle );
440 $status->fatal( 'backend-fail-read', $virtualSource );
441
442 return $status;
443 }
444 // Append chunk to file (pass chunk size to avoid magic quotes)
445 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
446 fclose( $sourceHandle );
447 fclose( $tmpHandle );
448 $status->fatal( 'backend-fail-writetemp', $tmpPath );
449
450 return $status;
451 }
452 fclose( $sourceHandle );
453 }
454 if ( !fclose( $tmpHandle ) ) {
455 $status->fatal( 'backend-fail-closetemp', $tmpPath );
456
457 return $status;
458 }
459
460 clearstatcache(); // temp file changed
461
462 return $status;
463 }
464
468 final protected function doPrepare( array $params ) {
469 $status = $this->newStatus();
470
471 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
472 if ( $dir === null ) {
473 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
474
475 return $status; // invalid storage path
476 }
477
478 if ( $shard !== null ) { // confined to a single container/shard
479 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
480 } else { // directory is on several shards
481 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
482 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
483 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
484 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
485 }
486 }
487
488 return $status;
489 }
490
499 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
500 return $this->newStatus();
501 }
502
504 final protected function doSecure( array $params ) {
505 $status = $this->newStatus();
506
507 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
508 if ( $dir === null ) {
509 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
510
511 return $status; // invalid storage path
512 }
513
514 if ( $shard !== null ) { // confined to a single container/shard
515 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
516 } else { // directory is on several shards
517 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
518 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
519 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
520 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
521 }
522 }
523
524 return $status;
525 }
526
535 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
536 return $this->newStatus();
537 }
538
540 final protected function doPublish( array $params ) {
541 $status = $this->newStatus();
542
543 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
544 if ( $dir === null ) {
545 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
546
547 return $status; // invalid storage path
548 }
549
550 if ( $shard !== null ) { // confined to a single container/shard
551 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
552 } else { // directory is on several shards
553 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
554 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
555 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
556 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
557 }
558 }
559
560 return $status;
561 }
562
571 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
572 return $this->newStatus();
573 }
574
576 final protected function doClean( array $params ) {
577 $status = $this->newStatus();
578
579 // Recursive: first delete all empty subdirs recursively
580 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
581 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
582 if ( $subDirsRel !== null ) { // no errors
583 foreach ( $subDirsRel as $subDirRel ) {
584 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
585 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
586 }
587 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
588 }
589 }
590
591 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
592 if ( $dir === null ) {
593 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
594
595 return $status; // invalid storage path
596 }
597
598 // Attempt to lock this directory...
599 $filesLockEx = [ $params['dir'] ];
601 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
602 if ( !$status->isOK() ) {
603 return $status; // abort
604 }
605
606 if ( $shard !== null ) { // confined to a single container/shard
607 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
608 $this->deleteContainerCache( $fullCont ); // purge cache
609 } else { // directory is on several shards
610 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
611 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
612 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
613 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
614 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
615 }
616 }
617
618 return $status;
619 }
620
629 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
630 return $this->newStatus();
631 }
632
634 final public function fileExists( array $params ) {
635 $stat = $this->getFileStat( $params );
636 if ( is_array( $stat ) ) {
637 return true;
638 }
639
640 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
641 }
642
644 final public function getFileTimestamp( array $params ) {
645 $stat = $this->getFileStat( $params );
646 if ( is_array( $stat ) ) {
647 return $stat['mtime'];
648 }
649
650 return self::TIMESTAMP_FAIL; // all failure cases
651 }
652
654 final public function getFileSize( array $params ) {
655 $stat = $this->getFileStat( $params );
656 if ( is_array( $stat ) ) {
657 return $stat['size'];
658 }
659
660 return self::SIZE_FAIL; // all failure cases
661 }
662
664 final public function getFileStat( array $params ) {
665 $path = self::normalizeStoragePath( $params['src'] );
666 if ( $path === null ) {
667 return self::STAT_ERROR; // invalid storage path
668 }
669
670 // Whether to bypass cache except for process cache entries loaded directly from
671 // high consistency backend queries (caller handles any cache flushing and locking)
672 $latest = !empty( $params['latest'] );
673 // Whether to ignore cache entries missing the SHA-1 field for existing files
674 $requireSHA1 = !empty( $params['requireSHA1'] );
675
676 $stat = $this->procFileStatCache->getField( $path, 'stat', self::CACHE_TTL );
677 // Load the persistent stat cache into process cache if needed
678 if ( !$latest ) {
679 if (
680 // File stat is not in process cache
681 $stat === null ||
682 // Key/value store backends might opportunistically set file stat process
683 // cache entries from object listings that do not include the SHA-1. In that
684 // case, loading the persistent stat cache will likely yield the SHA-1.
685 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
686 ) {
687 $this->primeFileCache( [ $path ] );
688 // Get any newly process-cached entry
689 $stat = $this->procFileStatCache->getField( $path, 'stat', self::CACHE_TTL );
690 }
691 }
692
693 if ( is_array( $stat ) ) {
694 if (
695 ( !$latest || !empty( $stat['latest'] ) ) &&
696 ( !$requireSHA1 || isset( $stat['sha1'] ) )
697 ) {
698 return $stat;
699 }
700 } elseif ( $stat === self::ABSENT_LATEST ) {
701 return self::STAT_ABSENT;
702 } elseif ( $stat === self::ABSENT_NORMAL ) {
703 if ( !$latest ) {
704 return self::STAT_ABSENT;
705 }
706 }
707
708 // Load the file stat from the backend and update caches
709 $stat = $this->doGetFileStat( $params );
710 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
711
712 if ( is_array( $stat ) ) {
713 return $stat;
714 }
715
716 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
717 }
718
726 final protected function ingestFreshFileStats( array $stats, $latest ) {
727 $success = true;
728
729 foreach ( $stats as $path => $stat ) {
730 if ( is_array( $stat ) ) {
731 // Strongly consistent backends might automatically set this flag
732 $stat['latest'] ??= $latest;
733
734 $this->procFileStatCache->setField( $path, 'stat', $stat );
735 if ( isset( $stat['sha1'] ) ) {
736 // Some backends store the SHA-1 hash as metadata
737 $this->procFileStatCache->setField(
738 $path,
739 'sha1',
740 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
741 );
742 }
743 if ( isset( $stat['xattr'] ) ) {
744 // Some backends store custom headers/metadata
745 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
746 $this->procFileStatCache->setField(
747 $path,
748 'xattr',
749 [ 'map' => $stat['xattr'], 'latest' => $latest ]
750 );
751 }
752 // Update persistent cache (@TODO: set all entries in one batch)
753 $this->setFileCache( $path, $stat );
754 } elseif ( $stat === self::RES_ABSENT ) {
755 $this->procFileStatCache->setField(
756 $path,
757 'stat',
758 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
759 );
760 $this->procFileStatCache->setField(
761 $path,
762 'xattr',
763 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
764 );
765 $this->procFileStatCache->setField(
766 $path,
767 'sha1',
768 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
769 );
770 $this->logger->debug(
771 __METHOD__ . ': File {path} does not exist',
772 [ 'path' => $path ]
773 );
774 } else {
775 $success = false;
776 $this->logger->error(
777 __METHOD__ . ': Could not stat file {path}',
778 [ 'path' => $path ]
779 );
780 }
781 }
782
783 return $success;
784 }
785
791 abstract protected function doGetFileStat( array $params );
792
794 public function getFileContentsMulti( array $params ) {
795 $params = $this->setConcurrencyFlags( $params );
796 $contents = $this->doGetFileContentsMulti( $params );
797 foreach ( $contents as $path => $content ) {
798 if ( !is_string( $content ) ) {
799 $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
800 }
801 }
802
803 return $contents;
804 }
805
812 protected function doGetFileContentsMulti( array $params ) {
813 $contents = [];
814 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
815 if ( $fsFile instanceof FSFile ) {
816 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
817 $content = @file_get_contents( $fsFile->getPath() );
818 $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
819 } else {
820 // self::RES_ERROR or self::RES_ABSENT
821 $contents[$path] = $fsFile;
822 }
823 }
824
825 return $contents;
826 }
827
829 final public function getFileXAttributes( array $params ) {
830 $path = self::normalizeStoragePath( $params['src'] );
831 if ( $path === null ) {
832 return self::XATTRS_FAIL; // invalid storage path
833 }
834 $latest = !empty( $params['latest'] ); // use latest data?
835 if ( $this->procFileStatCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
836 $stat = $this->procFileStatCache->getField( $path, 'xattr' );
837 // If we want the latest data, check that this cached
838 // value was in fact fetched with the latest available data.
839 if ( !$latest || $stat['latest'] ) {
840 return $stat['map'];
841 }
842 }
843 $fields = $this->doGetFileXAttributes( $params );
844 if ( is_array( $fields ) ) {
845 $fields = self::normalizeXAttributes( $fields );
846 $this->procFileStatCache->setField(
847 $path,
848 'xattr',
849 [ 'map' => $fields, 'latest' => $latest ]
850 );
851 } elseif ( $fields === self::RES_ABSENT ) {
852 $this->procFileStatCache->setField(
853 $path,
854 'xattr',
855 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
856 );
857 } else {
858 $fields = self::XATTRS_FAIL; // used for all failure cases
859 }
860
861 return $fields;
862 }
863
870 protected function doGetFileXAttributes( array $params ) {
871 return [ 'headers' => [], 'metadata' => [] ]; // not supported
872 }
873
875 final public function getFileSha1Base36( array $params ) {
876 $path = self::normalizeStoragePath( $params['src'] );
877 if ( $path === null ) {
878 return self::SHA1_FAIL; // invalid storage path
879 }
880 $latest = !empty( $params['latest'] ); // use latest data?
881 if ( $this->procFileStatCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
882 $stat = $this->procFileStatCache->getField( $path, 'sha1' );
883 // If we want the latest data, check that this cached
884 // value was in fact fetched with the latest available data.
885 if ( !$latest || $stat['latest'] ) {
886 return $stat['hash'];
887 }
888 }
889 $sha1 = $this->doGetFileSha1Base36( $params );
890 if ( is_string( $sha1 ) ) {
891 $this->procFileStatCache->setField(
892 $path,
893 'sha1',
894 [ 'hash' => $sha1, 'latest' => $latest ]
895 );
896 } elseif ( $sha1 === self::RES_ABSENT ) {
897 $this->procFileStatCache->setField(
898 $path,
899 'sha1',
900 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
901 );
902 } else {
903 $sha1 = self::SHA1_FAIL; // used for all failure cases
904 }
905
906 return $sha1;
907 }
908
915 protected function doGetFileSha1Base36( array $params ) {
916 $fsFile = $this->getLocalReference( $params );
917 if ( $fsFile instanceof FSFile ) {
918 $sha1 = $fsFile->getSha1Base36();
919
920 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
921 }
922
923 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
924 }
925
927 final public function getFileProps( array $params ) {
928 $fsFile = $this->getLocalReference( $params );
929
930 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
931 }
932
934 final public function getLocalReferenceMulti( array $params ) {
935 $params = $this->setConcurrencyFlags( $params );
936
937 $fsFiles = []; // (path => FSFile)
938 $latest = !empty( $params['latest'] ); // use latest data?
939 // Reuse any files already in process cache...
940 foreach ( $params['srcs'] as $src ) {
942 if ( $path === null ) {
943 $fsFiles[$src] = self::RES_ERROR; // invalid storage path
944 } elseif ( $this->procFileDataCache->hasField( $path, 'localRef' ) ) {
945 $val = $this->procFileDataCache->getField( $path, 'localRef' );
946 // If we want the latest data, check that this cached
947 // value was in fact fetched with the latest available data.
948 if ( !$latest || $val['latest'] ) {
949 $fsFiles[$src] = $val['object'];
950 }
951 }
952 }
953 // Fetch local references of any remaining files...
954 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
955 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
956 $fsFiles[$path] = $fsFile;
957 if ( $fsFile instanceof FSFile ) {
958 $this->procFileDataCache->setField(
959 $path,
960 'localRef',
961 [ 'object' => $fsFile, 'latest' => $latest ]
962 );
963 }
964 }
965
966 return $fsFiles;
967 }
968
975 protected function doGetLocalReferenceMulti( array $params ) {
976 return $this->doGetLocalCopyMulti( $params );
977 }
978
980 final public function getLocalCopyMulti( array $params ) {
981 $params = $this->setConcurrencyFlags( $params );
982
983 return $this->doGetLocalCopyMulti( $params );
984 }
985
991 abstract protected function doGetLocalCopyMulti( array $params );
992
999 public function getFileHttpUrl( array $params ) {
1000 return self::TEMPURL_ERROR; // not supported
1001 }
1002
1004 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1005 array $params
1006 ) {
1007 $ref = $this->getLocalReference( [ 'src' => $params['src'] ] );
1008 if ( $ref === false ) {
1009 return $this->newStatus( 'backend-fail-notexists', $params['src'] );
1010 } elseif ( $ref === null ) {
1011 return $this->newStatus( 'backend-fail-read', $params['src'] );
1012 } else {
1013 $file = $command->newInputFileFromFile( $ref->getPath() )
1014 ->userData( __CLASS__, $ref );
1015 $command->inputFile( $boxedName, $file );
1016 return $this->newStatus();
1017 }
1018 }
1019
1021 final public function streamFile( array $params ) {
1022 $status = $this->newStatus();
1023
1024 // Always set some fields for subclass convenience
1025 $params['options'] ??= [];
1026 $params['headers'] ??= [];
1027
1028 // Don't stream it out as text/html if there was a PHP error
1029 if ( ( empty( $params['headless'] ) || $params['headers'] ) && HttpHeader::headersSent() ) {
1030 print "Headers already sent, terminating.\n";
1031 $status->fatal( 'backend-fail-stream', $params['src'] );
1032 return $status;
1033 }
1034
1035 $status->merge( $this->doStreamFile( $params ) );
1036
1037 return $status;
1038 }
1039
1046 protected function doStreamFile( array $params ) {
1047 $status = $this->newStatus();
1048
1049 $flags = 0;
1050 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1051 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1052
1053 $fsFile = $this->getLocalReference( $params );
1054 if ( $fsFile ) {
1055 $streamer = new HTTPFileStreamer(
1056 $fsFile->getPath(),
1057 $this->getStreamerOptions()
1058 );
1059 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1060 } else {
1061 $res = false;
1062 HTTPFileStreamer::send404Message( $params['src'], $flags );
1063 }
1064
1065 if ( !$res ) {
1066 $status->fatal( 'backend-fail-stream', $params['src'] );
1067 }
1068
1069 return $status;
1070 }
1071
1073 final public function directoryExists( array $params ) {
1074 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1075 if ( $dir === null ) {
1076 return self::EXISTENCE_ERROR; // invalid storage path
1077 }
1078 if ( $shard !== null ) { // confined to a single container/shard
1079 return $this->doDirectoryExists( $fullCont, $dir, $params );
1080 } else { // directory is on several shards
1081 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1082 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1083 $res = false; // response
1084 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1085 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1086 if ( $exists === true ) {
1087 $res = true;
1088 break; // found one!
1089 } elseif ( $exists === self::RES_ERROR ) {
1090 $res = self::EXISTENCE_ERROR;
1091 }
1092 }
1093
1094 return $res;
1095 }
1096 }
1097
1106 abstract protected function doDirectoryExists( $fullCont, $dirRel, array $params );
1107
1109 final public function getDirectoryList( array $params ) {
1110 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1111 if ( $dir === null ) {
1112 return self::EXISTENCE_ERROR; // invalid storage path
1113 }
1114 if ( $shard !== null ) {
1115 // File listing is confined to a single container/shard
1116 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1117 } else {
1118 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1119 // File listing spans multiple containers/shards
1120 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1121
1122 return new FileBackendStoreShardDirIterator( $this,
1123 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1124 }
1125 }
1126
1137 abstract public function getDirectoryListInternal( $fullCont, $dirRel, array $params );
1138
1140 final public function getFileList( array $params ) {
1141 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1142 if ( $dir === null ) {
1143 return self::LIST_ERROR; // invalid storage path
1144 }
1145 if ( $shard !== null ) {
1146 // File listing is confined to a single container/shard
1147 return $this->getFileListInternal( $fullCont, $dir, $params );
1148 } else {
1149 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1150 // File listing spans multiple containers/shards
1151 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1152
1153 return new FileBackendStoreShardFileIterator( $this,
1154 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1155 }
1156 }
1157
1168 abstract public function getFileListInternal( $fullCont, $dirRel, array $params );
1169
1181 final public function getOperationsInternal( array $ops ) {
1182 $supportedOps = [
1183 'store' => StoreFileOp::class,
1184 'copy' => CopyFileOp::class,
1185 'move' => MoveFileOp::class,
1186 'delete' => DeleteFileOp::class,
1187 'create' => CreateFileOp::class,
1188 'describe' => DescribeFileOp::class,
1189 'null' => NullFileOp::class
1190 ];
1191
1192 $performOps = []; // array of FileOp objects
1193 // Build up ordered array of FileOps...
1194 foreach ( $ops as $operation ) {
1195 $opName = $operation['op'];
1196 if ( isset( $supportedOps[$opName] ) ) {
1197 $class = $supportedOps[$opName];
1198 // Get params for this operation
1199 $params = $operation;
1200 // Append the FileOp class
1201 $performOps[] = new $class( $this, $params, $this->logger );
1202 } else {
1203 throw new FileBackendError( "Operation '$opName' is not supported." );
1204 }
1205 }
1206
1207 return $performOps;
1208 }
1209
1220 final public function getPathsToLockForOpsInternal( array $performOps ) {
1221 // Build up a list of files to lock...
1222 $paths = [ 'sh' => [], 'ex' => [] ];
1223 foreach ( $performOps as $fileOp ) {
1224 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1225 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1226 }
1227 // Optimization: if doing an EX lock anyway, don't also set an SH one
1228 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1229 // Get a shared lock on the parent directory of each path changed
1230 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1231
1232 return [
1233 LockManager::LOCK_UW => $paths['sh'],
1234 LockManager::LOCK_EX => $paths['ex']
1235 ];
1236 }
1237
1239 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1240 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1241
1242 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1243 }
1244
1246 final protected function doOperationsInternal( array $ops, array $opts ) {
1247 $status = $this->newStatus();
1248
1249 // Fix up custom header name/value pairs
1250 $ops = array_map( $this->sanitizeOpHeaders( ... ), $ops );
1251 // Build up a list of FileOps and involved paths
1252 $fileOps = $this->getOperationsInternal( $ops );
1253 $pathsUsed = [];
1254 foreach ( $fileOps as $fileOp ) {
1255 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1256 }
1257
1258 // Acquire any locks as needed for the scope of this function
1259 if ( empty( $opts['nonLocking'] ) ) {
1260 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1262 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1263 if ( !$status->isOK() ) {
1264 return $status; // abort
1265 }
1266 }
1267
1268 // Clear any file cache entries (after locks acquired)
1269 if ( empty( $opts['preserveCache'] ) ) {
1270 $this->clearCache( $pathsUsed );
1271 }
1272
1273 // Enlarge the cache to fit the stat entries of these files
1274 $this->procFileStatCache->setMaxSize(
1275 max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE )
1276 );
1277
1278 // Load from the persistent container caches
1279 $this->primeContainerCache( $pathsUsed );
1280 // Get the latest stat info for all the files (having locked them)
1281 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1282
1283 if ( $ok ) {
1284 // Actually attempt the operation batch...
1285 $opts = $this->setConcurrencyFlags( $opts );
1286 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1287 } else {
1288 // If we could not even stat some files, then bail out
1289 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1290 foreach ( $ops as $i => $op ) { // mark each op as failed
1291 $subStatus->success[$i] = false;
1292 ++$subStatus->failCount;
1293 }
1294 $this->logger->error( static::class . "-{$this->name} stat failure",
1295 [ 'aborted_operations' => $ops ]
1296 );
1297 }
1298
1299 // Merge errors into StatusValue fields
1300 $status->merge( $subStatus );
1301 $status->success = $subStatus->success; // not done in merge()
1302
1303 // Shrink the stat cache back to normal size
1304 $this->procFileStatCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1305
1306 return $status;
1307 }
1308
1310 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1311 $status = $this->newStatus();
1312
1313 // Fix up custom header name/value pairs
1314 $ops = array_map( $this->sanitizeOpHeaders( ... ), $ops );
1315 // Build up a list of FileOps and involved paths
1316 $fileOps = $this->getOperationsInternal( $ops );
1317 $pathsUsed = [];
1318 foreach ( $fileOps as $fileOp ) {
1319 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1320 }
1321
1322 // Clear any file cache entries for involved paths
1323 $this->clearCache( $pathsUsed );
1324
1325 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1326 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1327 $maxConcurrency = $this->concurrency; // throttle
1329 $statuses = []; // array of (index => StatusValue)
1331 $batch = [];
1332 foreach ( $fileOps as $index => $fileOp ) {
1333 $subStatus = $async
1334 ? $fileOp->attemptAsyncQuick()
1335 : $fileOp->attemptQuick();
1336 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1337 if ( count( $batch ) >= $maxConcurrency ) {
1338 // Execute this batch. Don't queue any more ops since they contain
1339 // open filehandles which are a limited resource (T230245).
1340 $statuses += $this->executeOpHandlesInternal( $batch );
1341 $batch = [];
1342 }
1343 $batch[$index] = $subStatus->value; // keep index
1344 } else { // error or completed
1345 $statuses[$index] = $subStatus; // keep index
1346 }
1347 }
1348 if ( count( $batch ) ) {
1349 $statuses += $this->executeOpHandlesInternal( $batch );
1350 }
1351 // Marshall and merge all the responses...
1352 foreach ( $statuses as $index => $subStatus ) {
1353 $status->merge( $subStatus );
1354 if ( $subStatus->isOK() ) {
1355 $status->success[$index] = true;
1356 ++$status->successCount;
1357 } else {
1358 $status->success[$index] = false;
1359 ++$status->failCount;
1360 }
1361 }
1362
1363 $this->clearCache( $pathsUsed );
1364
1365 return $status;
1366 }
1367
1377 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1378 foreach ( $fileOpHandles as $fileOpHandle ) {
1379 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1380 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1381 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1382 throw new InvalidArgumentException( "Expected handle for this file backend." );
1383 }
1384 }
1385
1386 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1387 foreach ( $fileOpHandles as $fileOpHandle ) {
1388 $fileOpHandle->closeResources();
1389 }
1390
1391 return $statuses;
1392 }
1393
1403 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1404 if ( count( $fileOpHandles ) ) {
1405 throw new FileBackendError( "Backend does not support asynchronous operations." );
1406 }
1407
1408 return [];
1409 }
1410
1422 protected function sanitizeOpHeaders( array $op ) {
1423 static $longs = [ 'content-disposition' ];
1424
1425 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1426 $newHeaders = [];
1427 foreach ( $op['headers'] as $name => $value ) {
1428 $name = strtolower( $name );
1429 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1430 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1431 $this->logger->error( "Header '{header}' is too long.", [
1432 'filebackend' => $this->name,
1433 'header' => "$name: $value",
1434 ] );
1435 } else {
1436 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1437 }
1438 }
1439 $op['headers'] = $newHeaders;
1440 }
1441
1442 return $op;
1443 }
1444
1445 final public function preloadCache( array $paths ) {
1446 $fullConts = []; // full container names
1447 foreach ( $paths as $path ) {
1448 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1449 $fullConts[] = $fullCont;
1450 }
1451 // Load from the persistent file and container caches
1452 $this->primeContainerCache( $fullConts );
1453 $this->primeFileCache( $paths );
1454 }
1455
1456 final public function clearCache( ?array $paths = null ) {
1457 if ( is_array( $paths ) ) {
1458 $paths = array_map( FileBackend::normalizeStoragePath( ... ), $paths );
1459 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1460 }
1461 if ( $paths === null ) {
1462 $this->procFileStatCache->clear();
1463 $this->procFileDataCache->clear();
1464 } else {
1465 foreach ( $paths as $path ) {
1466 $this->procFileStatCache->clear( $path );
1467 $this->procFileDataCache->clear( $path );
1468 }
1469 }
1470 $this->doClearCache( $paths );
1471 }
1472
1481 protected function doClearCache( ?array $paths = null ) {
1482 }
1483
1485 final public function preloadFileStat( array $params ) {
1486 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1487 $stats = $this->doGetFileStatMulti( $params );
1488 if ( $stats === null ) {
1489 return true; // not supported
1490 }
1491
1492 // Whether this queried the backend in high consistency mode
1493 $latest = !empty( $params['latest'] );
1494
1495 return $this->ingestFreshFileStats( $stats, $latest );
1496 }
1497
1511 protected function doGetFileStatMulti( array $params ) {
1512 return null; // not supported
1513 }
1514
1523 abstract protected function directoriesAreVirtual();
1524
1535 final protected static function isValidShortContainerName( $container ) {
1536 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1537 // might be used by subclasses. Reserve the dot character.
1538 // The only way dots end up in containers (e.g. resolveStoragePath)
1539 // is due to the wikiId container prefix or the above suffixes.
1540 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1541 }
1542
1552 final protected static function isValidContainerName( $container ) {
1553 // This accounts for NTFS, Swift, and Ceph restrictions
1554 // and disallows directory separators or traversal characters.
1555 // Note that matching strings URL encode to the same string;
1556 // in Swift/Ceph, the length restriction is *after* URL encoding.
1557 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1558 }
1559
1573 final protected function resolveStoragePath( $storagePath ) {
1574 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1575 if ( $backend === $this->name && $relPath !== null ) { // must be for this backend
1576 $relPath = self::normalizeContainerPath( $relPath );
1577 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1578 // Get shard for the normalized path if this container is sharded
1579 $cShard = $this->getContainerShard( $shortCont, $relPath );
1580 // Validate and sanitize the relative path (backend-specific)
1581 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1582 if ( $relPath !== null ) {
1583 // Prepend any domain ID prefix to the container name
1584 $container = $this->fullContainerName( $shortCont );
1585 if ( self::isValidContainerName( $container ) ) {
1586 // Validate and sanitize the container name (backend-specific)
1587 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1588 if ( $container !== null ) {
1589 return [ $container, $relPath, $cShard ];
1590 }
1591 }
1592 }
1593 }
1594 }
1595
1596 return [ null, null, null ];
1597 }
1598
1614 final protected function resolveStoragePathReal( $storagePath ) {
1615 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1616 if ( $cShard !== null && !str_ends_with( $relPath, '/' ) ) {
1617 return [ $container, $relPath ];
1618 }
1619
1620 return [ null, null ];
1621 }
1622
1631 final protected function getContainerShard( $container, $relPath ) {
1632 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1633 if ( $levels == 1 || $levels == 2 ) {
1634 // Hash characters are either base 16 or 36
1635 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1636 // Get a regex that represents the shard portion of paths.
1637 // The concatenation of the captures gives us the shard.
1638 if ( $levels === 1 ) { // 16 or 36 shards per container
1639 $hashDirRegex = '(' . $char . ')';
1640 } else { // 256 or 1296 shards per container
1641 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1642 $hashDirRegex = $char . '/(' . $char . '{2})';
1643 } else { // short hash dir format (e.g. "a/b/c")
1644 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1645 }
1646 }
1647 // Allow certain directories to be above the hash dirs so as
1648 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1649 // They must be 2+ chars to avoid any hash directory ambiguity.
1650 $m = [];
1651 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1652 return '.' . implode( '', array_slice( $m, 1 ) );
1653 }
1654
1655 return null; // failed to match
1656 }
1657
1658 return ''; // no sharding
1659 }
1660
1669 final public function isSingleShardPathInternal( $storagePath ) {
1670 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1671
1672 return ( $shard !== null );
1673 }
1674
1683 final protected function getContainerHashLevels( $container ) {
1684 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1685 $config = $this->shardViaHashLevels[$container];
1686 $hashLevels = (int)$config['levels'];
1687 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1688 $hashBase = (int)$config['base'];
1689 if ( $hashBase == 16 || $hashBase == 36 ) {
1690 return [ $hashLevels, $hashBase, $config['repeat'] ];
1691 }
1692 }
1693 }
1694
1695 return [ 0, 0, false ]; // no sharding
1696 }
1697
1704 final protected function getContainerSuffixes( $container ) {
1705 $shards = [];
1706 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1707 if ( $digits > 0 ) {
1708 $numShards = $base ** $digits;
1709 for ( $index = 0; $index < $numShards; $index++ ) {
1710 $shards[] = '.' . \Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1711 }
1712 }
1713
1714 return $shards;
1715 }
1716
1723 final protected function fullContainerName( $container ) {
1724 if ( $this->domainId != '' ) {
1725 return "{$this->domainId}-$container";
1726 } else {
1727 return $container;
1728 }
1729 }
1730
1740 protected function resolveContainerName( $container ) {
1741 return $container;
1742 }
1743
1755 protected function resolveContainerPath( $container, $relStoragePath ) {
1756 return $relStoragePath;
1757 }
1758
1765 private function containerCacheKey( $container ) {
1766 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1767 }
1768
1775 final protected function setContainerCache( $container, array $val ) {
1776 if ( !$this->wanStatCache->set(
1777 $this->containerCacheKey( $container ),
1778 $val,
1779 14 * 86400
1780 ) ) {
1781 $this->logger->warning( "Unable to set stat cache for container {container}.",
1782 [ 'filebackend' => $this->name, 'container' => $container ]
1783 );
1784 }
1785 }
1786
1793 final protected function deleteContainerCache( $container ) {
1794 if ( !$this->wanStatCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1795 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1796 [ 'filebackend' => $this->name, 'container' => $container ]
1797 );
1798 }
1799 }
1800
1806 final protected function primeContainerCache( array $items ) {
1807 $paths = []; // list of storage paths
1808 $contNames = []; // (cache key => resolved container name)
1809 // Get all the paths/containers from the items...
1810 foreach ( $items as $item ) {
1811 if ( self::isStoragePath( $item ) ) {
1812 $paths[] = $item;
1813 } elseif ( is_string( $item ) ) { // full container name
1814 $contNames[$this->containerCacheKey( $item )] = $item;
1815 }
1816 }
1817 // Get all the corresponding cache keys for paths...
1818 foreach ( $paths as $path ) {
1819 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1820 if ( $fullCont !== null ) { // valid path for this backend
1821 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1822 }
1823 }
1824
1825 $contInfo = []; // (resolved container name => cache value)
1826 // Get all cache entries for these container cache keys...
1827 $values = $this->wanStatCache->getMulti( array_keys( $contNames ) );
1828 foreach ( $values as $cacheKey => $val ) {
1829 $contInfo[$contNames[$cacheKey]] = $val;
1830 }
1831
1832 // Populate the container process cache for the backend...
1833 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1834 }
1835
1844 protected function doPrimeContainerCache( array $containerInfo ) {
1845 }
1846
1853 private function fileCacheKey( $path ) {
1854 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1855 }
1856
1865 final protected function setFileCache( $path, array $val ) {
1867 if ( $path === null ) {
1868 return; // invalid storage path
1869 }
1870 // Set the cache unless it is currently salted.
1871 if ( !$this->wanStatCache->set( $this->fileCacheKey( $path ), $val, 7 * 86400 ) ) {
1872 $this->logger->warning( "Unable to set stat cache for file {path}.",
1873 [ 'filebackend' => $this->name, 'path' => $path ]
1874 );
1875 }
1876 }
1877
1886 final protected function deleteFileCache( $path ) {
1888 if ( $path === null ) {
1889 return; // invalid storage path
1890 }
1891 if ( !$this->wanStatCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1892 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1893 [ 'filebackend' => $this->name, 'path' => $path ]
1894 );
1895 }
1896 }
1897
1905 final protected function primeFileCache( array $items ) {
1906 $paths = []; // list of storage paths
1907 $pathNames = []; // (cache key => storage path)
1908 // Get all the paths/containers from the items...
1909 foreach ( $items as $item ) {
1910 if ( self::isStoragePath( $item ) ) {
1912 if ( $path !== null ) {
1913 $paths[] = $path;
1914 }
1915 }
1916 }
1917 // Get all the corresponding cache keys for paths...
1918 foreach ( $paths as $path ) {
1919 [ , $rel, ] = $this->resolveStoragePath( $path );
1920 if ( $rel !== null ) { // valid path for this backend
1921 $pathNames[$this->fileCacheKey( $path )] = $path;
1922 }
1923 }
1924 // Get all cache entries for these file cache keys.
1925 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1926 $values = $this->wanStatCache->getMulti( array_keys( $pathNames ) );
1927 // Load all of the results into process cache...
1928 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1929 $path = $pathNames[$cacheKey];
1930 // This flag only applies to stat info loaded directly
1931 // from a high consistency backend query to the process cache
1932 unset( $stat['latest'] );
1933
1934 $this->procFileStatCache->setField( $path, 'stat', $stat );
1935 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1936 // Some backends store SHA-1 as metadata
1937 $this->procFileStatCache->setField(
1938 $path,
1939 'sha1',
1940 [ 'hash' => $stat['sha1'], 'latest' => false ]
1941 );
1942 }
1943 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1944 // Some backends store custom headers/metadata
1945 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1946 $this->procFileStatCache->setField(
1947 $path,
1948 'xattr',
1949 [ 'map' => $stat['xattr'], 'latest' => false ]
1950 );
1951 }
1952 }
1953 }
1954
1962 final protected static function normalizeXAttributes( array $xattr ) {
1963 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1964
1965 foreach ( $xattr['headers'] as $name => $value ) {
1966 $newXAttr['headers'][strtolower( $name )] = $value;
1967 }
1968
1969 foreach ( $xattr['metadata'] as $name => $value ) {
1970 $newXAttr['metadata'][strtolower( $name )] = $value;
1971 }
1972
1973 return $newXAttr;
1974 }
1975
1982 final protected function setConcurrencyFlags( array $opts ) {
1983 $opts['concurrency'] = 1; // off
1984 if ( $this->parallelize === 'implicit' ) {
1985 if ( $opts['parallelize'] ?? true ) {
1986 $opts['concurrency'] = $this->concurrency;
1987 }
1988 } elseif ( $this->parallelize === 'explicit' ) {
1989 if ( !empty( $opts['parallelize'] ) ) {
1990 $opts['concurrency'] = $this->concurrency;
1991 }
1992 }
1993
1994 return $opts;
1995 }
1996
2006 protected function getContentType( $storagePath, $content, $fsPath ) {
2007 if ( $this->mimeCallback ) {
2008 return ( $this->mimeCallback )( $storagePath, $content, $fsPath );
2009 }
2010
2011 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2012 return $mime ?: 'unknown/unknown';
2013 }
2014}
2015
2017class_alias( FileBackendStore::class, 'FileBackendStore' );
File backend exception for checked exceptions (e.g.
Base class for all backends using particular storage medium.
getContainerHashLevels( $container)
Get the sharding config for a container.
createInternal(array $params)
Create a file in the backend with the given contents.
static isValidContainerName( $container)
Check if a full container name is valid.
doCleanInternal( $fullCont, $dirRel, array $params)
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
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...
getFileXAttributes(array $params)
Get metadata about a file at a storage path in the backend.If the file does not exist,...
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.If the directory is of the form "m...
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
doOperationsInternal(array $ops, array $opts)
FileBackend\doOperations() StatusValue
ingestFreshFileStats(array $stats, $latest)
Ingest file stat entries that just came from querying the backend (not cache).
moveInternal(array $params)
Move a file from one storage path to another in the backend.
getContainerSuffixes( $container)
Get a list of full container shard suffixes for a container.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
getPathsToLockForOpsInternal(array $performOps)
Get a list of storage paths to lock for a list of operations Returns an array with LockManager\LOCK_U...
getContainerShard( $container, $relPath)
Get the container name shard suffix for a given path.
doSecureInternal( $fullCont, $dirRel, array $params)
doSecure(array $params)
FileBackend\secure() StatusValue
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
primeFileCache(array $items)
Do a batch lookup from cache for file stats for all paths used in a list of storage paths or FileOp o...
setConcurrencyFlags(array $opts)
Set the 'concurrency' option from a list of operation options.
getScopedLocksForOps(array $ops, StatusValue $status)
Get an array of scoped locks needed for a batch of file operations.Normally, FileBackend\doOperations...
concatenate(array $params)
Concatenate a list of storage files into a single file system file.The target path should refer to a ...
describeInternal(array $params)
Alter metadata for a file at the storage path.
static normalizeXAttributes(array $xattr)
Normalize file headers/metadata to the FileBackend\getFileXAttributes() format.
directoryExists(array $params)
Check if a directory exists at a given storage path.For backends using key/value stores,...
getFileContentsMulti(array $params)
Like getFileContents() except it takes an array of storage paths and returns an order preserved map o...
doQuickOperationsInternal(array $ops, array $opts)
FileBackend\doQuickOperations() StatusValue 1.20
setFileCache( $path, array $val)
Set the cached stat info for a file path.
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
static isValidShortContainerName( $container)
Check if a short container name is valid.
isSingleShardPathInternal( $storagePath)
Check if a storage path maps to a single shard.
doDirectoryExists( $fullCont, $dirRel, array $params)
storeInternal(array $params)
Store a file into the backend from a file on disk.
deleteInternal(array $params)
Delete a file at the storage path.
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
getFileProps(array $params)
Get the properties of the content of the file at a storage path in the backend.This gives the result ...
setContainerCache( $container, array $val)
Set the cached info for a container.
WANObjectCache $wanStatCache
Cache used for persistent file/container stat entries.
maxFileSizeInternal()
Get the maximum allowable file size given backend medium restrictions and basic performance constrain...
doPrepareInternal( $fullCont, $dirRel, array $params)
getDirectoryListInternal( $fullCont, $dirRel, array $params)
Do not call this function from places outside FileBackend.
doClearCache(?array $paths=null)
Clears any additional stat caches for storage paths.
WANObjectCache $wanCache
Persistent cache accessible to all relevant datacenters.
int $maxFileSize
Size in bytes, defaults to 32 GiB.
doPrepare(array $params)
FileBackend\prepare() StatusValue Good status without value for success, fatal otherwise.
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.If the file does not exist,...
fullContainerName( $container)
Get the full container name, including the domain ID prefix.
fileExists(array $params)
Check if a file exists at a storage path in the backend.This returns false if only a directory exists...
callable null $mimeCallback
Method to get the MIME type of files.
deleteContainerCache( $container)
Delete the cached info for a container.
array< string, array > $shardViaHashLevels
Map of container names to sharding config.
streamFile(array $params)
Stream the content of the file at a storage path in the backend.If the file does not exists,...
clearCache(?array $paths=null)
Invalidate any in-process file stat and property cache.
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.FileBackend\TIMESTAMP_FAILstring|false ...
deleteFileCache( $path)
Delete the cached stat info for a file path.
resolveContainerName( $container)
Resolve a container name, checking if it's allowed by the backend.
doClean(array $params)
FileBackend\clean() StatusValue
copyInternal(array $params)
Copy a file from one storage path to another in the backend.
MapCacheLRU $procFileStatCache
LRU map of file paths to small (RAM/disk) cache items.
resolveStoragePath( $storagePath)
Splits a storage path into an internal container name, an internal relative file name,...
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and yields an order-preserved map ...
getDirectoryList(array $params)
Get an iterator to list all directories under a storage directory.If the directory is of the form "mw...
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.This should be used wh...
sanitizeOpHeaders(array $op)
Normalize and filter HTTP headers from a file operation.
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.FileBackend\SIZE_FAILint|false File s...
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.
nullInternal(array $params)
No-op file operation that does nothing.
MapCacheLRU $procFileDataCache
LRU map of file paths to large (RAM/disk) cache items.
doPublish(array $params)
FileBackend\publish() StatusValue
getFileListInternal( $fullCont, $dirRel, array $params)
Do not call this function from places outside FileBackend.
getOperationsInternal(array $ops)
Return a list of FileOp objects from a list of operations.
directoriesAreVirtual()
Whether this a key/value store where directories are merely virtual.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
BagOStuff $srvCache
Persistent local server/host cache (e.g.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the content of the file at a storage path in the backend.FileBackend\SHA1_FAILstr...
doPublishInternal( $fullCont, $dirRel, array $params)
addShellboxInputFile(BoxedCommand $command, string $boxedName, array $params)
Add a file to a Shellbox command as an input file.StatusValue 1.43
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
static normalizeContainerPath( $path)
Validate and normalize a relative storage path.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
getLocalReference(array $params)
Returns a file system file, identical in content to the file at a storage path.
getTopDirectoryList(array $params)
Same as FileBackend\getDirectoryList() except only lists directories that are immediately under the g...
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
static normalizeStoragePath( $storagePath)
Normalize a storage path by cleaning up directory separators.
newStatus( $message=null,... $params)
Yields the result of the status wrapper callback on either:
int $concurrency
How many operations can be done in parallel.
static attempt(array $performOps, array $opts)
Attempt to perform a series of file operations.
FileBackendStore helper class for performing asynchronous file operations.
Functions related to the output of file content.
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:73
No-op implementation that stores nothing.
Store key-value entries in a size-limited in-memory LRU cache.
Multi-datacenter aware caching interface.