MediaWiki master
FileBackendStore.php
Go to the documentation of this file.
1<?php
24namespace Wikimedia\FileBackend;
25
26use InvalidArgumentException;
27use LockManager;
28use MapCacheLRU;
30use Shellbox\Command\BoxedCommand;
31use StatusValue;
32use Traversable;
33use Wikimedia\AtEase\AtEase;
49use Wikimedia\Timestamp\ConvertibleTimestamp;
50
65abstract class FileBackendStore extends FileBackend {
67 protected $memCache;
69 protected $srvCache;
71 protected $cheapCache;
73 protected $expensiveCache;
74
76 protected $shardViaHashLevels = [];
77
79 protected $mimeCallback;
80
82 protected $maxFileSize = 32 * 1024 * 1024 * 1024;
83
84 protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
85 protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
86 protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
87
89 protected const RES_ABSENT = false;
91 protected const RES_ERROR = null;
92
94 protected const ABSENT_NORMAL = 'FNE-N';
96 protected const ABSENT_LATEST = 'FNE-L';
97
111 public function __construct( array $config ) {
112 parent::__construct( $config );
113 $this->mimeCallback = $config['mimeCallback'] ?? null;
114 $this->srvCache = new EmptyBagOStuff(); // disabled by default
115 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
116 $this->cheapCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
117 $this->expensiveCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
118 }
119
127 final public function maxFileSizeInternal() {
128 return min( $this->maxFileSize, PHP_INT_MAX );
129 }
130
141 abstract public function isPathUsableInternal( $storagePath );
142
161 final public function createInternal( array $params ) {
163 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
164
165 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
166 $status = $this->newStatus( 'backend-fail-maxsize',
167 $params['dst'], $this->maxFileSizeInternal() );
168 } else {
169 $status = $this->doCreateInternal( $params );
170 $this->clearCache( [ $params['dst'] ] );
171 if ( $params['dstExists'] ?? true ) {
172 $this->deleteFileCache( $params['dst'] ); // persistent cache
173 }
174 }
175
176 return $status;
177 }
178
184 abstract protected function doCreateInternal( array $params );
185
204 final public function storeInternal( array $params ) {
206 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
207
208 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
209 $status = $this->newStatus( 'backend-fail-maxsize',
210 $params['dst'], $this->maxFileSizeInternal() );
211 } else {
212 $status = $this->doStoreInternal( $params );
213 $this->clearCache( [ $params['dst'] ] );
214 if ( $params['dstExists'] ?? true ) {
215 $this->deleteFileCache( $params['dst'] ); // persistent cache
216 }
217 }
218
219 return $status;
220 }
221
227 abstract protected function doStoreInternal( array $params );
228
248 final public function copyInternal( array $params ) {
250 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
251
252 $status = $this->doCopyInternal( $params );
253 $this->clearCache( [ $params['dst'] ] );
254 if ( $params['dstExists'] ?? true ) {
255 $this->deleteFileCache( $params['dst'] ); // persistent cache
256 }
257
258 return $status;
259 }
260
266 abstract protected function doCopyInternal( array $params );
267
282 final public function deleteInternal( array $params ) {
284 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
285
286 $status = $this->doDeleteInternal( $params );
287 $this->clearCache( [ $params['src'] ] );
288 $this->deleteFileCache( $params['src'] ); // persistent cache
289 return $status;
290 }
291
297 abstract protected function doDeleteInternal( array $params );
298
318 final public function moveInternal( array $params ) {
320 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
321
322 $status = $this->doMoveInternal( $params );
323 $this->clearCache( [ $params['src'], $params['dst'] ] );
324 $this->deleteFileCache( $params['src'] ); // persistent cache
325 if ( $params['dstExists'] ?? true ) {
326 $this->deleteFileCache( $params['dst'] ); // persistent cache
327 }
328
329 return $status;
330 }
331
337 abstract protected function doMoveInternal( array $params );
338
353 final public function describeInternal( array $params ) {
355 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
356
357 if ( count( $params['headers'] ) ) {
358 $status = $this->doDescribeInternal( $params );
359 $this->clearCache( [ $params['src'] ] );
360 $this->deleteFileCache( $params['src'] ); // persistent cache
361 } else {
362 $status = $this->newStatus(); // nothing to do
363 }
364
365 return $status;
366 }
367
374 protected function doDescribeInternal( array $params ) {
375 return $this->newStatus();
376 }
377
385 final public function nullInternal( array $params ) {
386 return $this->newStatus();
387 }
388
389 final public function concatenate( array $params ) {
391 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
392 $status = $this->newStatus();
393
394 // Try to lock the source files for the scope of this function
396 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
397 if ( $status->isOK() ) {
398 // Actually do the file concatenation...
399 $start_time = microtime( true );
400 $status->merge( $this->doConcatenate( $params ) );
401 $sec = microtime( true ) - $start_time;
402 if ( !$status->isOK() ) {
403 $this->logger->error( static::class . "-{$this->name}" .
404 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
405 }
406 }
407
408 return $status;
409 }
410
417 protected function doConcatenate( array $params ) {
418 $status = $this->newStatus();
419 $tmpPath = $params['dst'];
420 unset( $params['latest'] );
421
422 // Check that the specified temp file is valid...
423 AtEase::suppressWarnings();
424 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
425 AtEase::restoreWarnings();
426 if ( !$ok ) { // not present or not empty
427 $status->fatal( 'backend-fail-opentemp', $tmpPath );
428
429 return $status;
430 }
431
432 // Get local FS versions of the chunks needed for the concatenation...
433 $fsFiles = $this->getLocalReferenceMulti( $params );
434 foreach ( $fsFiles as $path => &$fsFile ) {
435 if ( !$fsFile ) { // chunk failed to download?
436 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
437 if ( !$fsFile ) { // retry failed?
438 $status->fatal(
439 $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
440 $path
441 );
442
443 return $status;
444 }
445 }
446 }
447 unset( $fsFile ); // unset reference so we can reuse $fsFile
448
449 // Get a handle for the destination temp file
450 $tmpHandle = fopen( $tmpPath, 'ab' );
451 if ( $tmpHandle === false ) {
452 $status->fatal( 'backend-fail-opentemp', $tmpPath );
453
454 return $status;
455 }
456
457 // Build up the temp file using the source chunks (in order)...
458 foreach ( $fsFiles as $virtualSource => $fsFile ) {
459 // Get a handle to the local FS version
460 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
461 if ( $sourceHandle === false ) {
462 fclose( $tmpHandle );
463 $status->fatal( 'backend-fail-read', $virtualSource );
464
465 return $status;
466 }
467 // Append chunk to file (pass chunk size to avoid magic quotes)
468 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
469 fclose( $sourceHandle );
470 fclose( $tmpHandle );
471 $status->fatal( 'backend-fail-writetemp', $tmpPath );
472
473 return $status;
474 }
475 fclose( $sourceHandle );
476 }
477 if ( !fclose( $tmpHandle ) ) {
478 $status->fatal( 'backend-fail-closetemp', $tmpPath );
479
480 return $status;
481 }
482
483 clearstatcache(); // temp file changed
484
485 return $status;
486 }
487
491 final protected function doPrepare( array $params ) {
493 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
494 $status = $this->newStatus();
495
496 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
497 if ( $dir === null ) {
498 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
499
500 return $status; // invalid storage path
501 }
502
503 if ( $shard !== null ) { // confined to a single container/shard
504 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
505 } else { // directory is on several shards
506 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
507 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
508 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
509 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
510 }
511 }
512
513 return $status;
514 }
515
524 protected function doPrepareInternal( $container, $dir, array $params ) {
525 return $this->newStatus();
526 }
527
528 final protected function doSecure( array $params ) {
530 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
531 $status = $this->newStatus();
532
533 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
534 if ( $dir === null ) {
535 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
536
537 return $status; // invalid storage path
538 }
539
540 if ( $shard !== null ) { // confined to a single container/shard
541 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
542 } else { // directory is on several shards
543 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
544 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
545 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
546 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
547 }
548 }
549
550 return $status;
551 }
552
561 protected function doSecureInternal( $container, $dir, array $params ) {
562 return $this->newStatus();
563 }
564
565 final protected function doPublish( array $params ) {
567 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
568 $status = $this->newStatus();
569
570 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
571 if ( $dir === null ) {
572 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
573
574 return $status; // invalid storage path
575 }
576
577 if ( $shard !== null ) { // confined to a single container/shard
578 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
579 } else { // directory is on several shards
580 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
581 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
582 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
583 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
584 }
585 }
586
587 return $status;
588 }
589
598 protected function doPublishInternal( $container, $dir, array $params ) {
599 return $this->newStatus();
600 }
601
602 final protected function doClean( array $params ) {
604 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
605 $status = $this->newStatus();
606
607 // Recursive: first delete all empty subdirs recursively
608 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
609 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
610 if ( $subDirsRel !== null ) { // no errors
611 foreach ( $subDirsRel as $subDirRel ) {
612 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
613 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
614 }
615 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
616 }
617 }
618
619 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
620 if ( $dir === null ) {
621 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
622
623 return $status; // invalid storage path
624 }
625
626 // Attempt to lock this directory...
627 $filesLockEx = [ $params['dir'] ];
629 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
630 if ( !$status->isOK() ) {
631 return $status; // abort
632 }
633
634 if ( $shard !== null ) { // confined to a single container/shard
635 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
636 $this->deleteContainerCache( $fullCont ); // purge cache
637 } else { // directory is on several shards
638 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
639 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
640 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
641 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
642 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
643 }
644 }
645
646 return $status;
647 }
648
657 protected function doCleanInternal( $container, $dir, array $params ) {
658 return $this->newStatus();
659 }
660
661 final public function fileExists( array $params ) {
663 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
664
665 $stat = $this->getFileStat( $params );
666 if ( is_array( $stat ) ) {
667 return true;
668 }
669
670 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
671 }
672
673 final public function getFileTimestamp( array $params ) {
675 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
676
677 $stat = $this->getFileStat( $params );
678 if ( is_array( $stat ) ) {
679 return $stat['mtime'];
680 }
681
682 return self::TIMESTAMP_FAIL; // all failure cases
683 }
684
685 final public function getFileSize( array $params ) {
687 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
688
689 $stat = $this->getFileStat( $params );
690 if ( is_array( $stat ) ) {
691 return $stat['size'];
692 }
693
694 return self::SIZE_FAIL; // all failure cases
695 }
696
697 final public function getFileStat( array $params ) {
699 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
700
702 if ( $path === null ) {
703 return self::STAT_ERROR; // invalid storage path
704 }
705
706 // Whether to bypass cache except for process cache entries loaded directly from
707 // high consistency backend queries (caller handles any cache flushing and locking)
708 $latest = !empty( $params['latest'] );
709 // Whether to ignore cache entries missing the SHA-1 field for existing files
710 $requireSHA1 = !empty( $params['requireSHA1'] );
711
712 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
713 // Load the persistent stat cache into process cache if needed
714 if ( !$latest ) {
715 if (
716 // File stat is not in process cache
717 $stat === null ||
718 // Key/value store backends might opportunistically set file stat process
719 // cache entries from object listings that do not include the SHA-1. In that
720 // case, loading the persistent stat cache will likely yield the SHA-1.
721 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
722 ) {
723 $this->primeFileCache( [ $path ] );
724 // Get any newly process-cached entry
725 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
726 }
727 }
728
729 if ( is_array( $stat ) ) {
730 if (
731 ( !$latest || !empty( $stat['latest'] ) ) &&
732 ( !$requireSHA1 || isset( $stat['sha1'] ) )
733 ) {
734 return $stat;
735 }
736 } elseif ( $stat === self::ABSENT_LATEST ) {
737 return self::STAT_ABSENT;
738 } elseif ( $stat === self::ABSENT_NORMAL ) {
739 if ( !$latest ) {
740 return self::STAT_ABSENT;
741 }
742 }
743
744 // Load the file stat from the backend and update caches
745 $stat = $this->doGetFileStat( $params );
746 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
747
748 if ( is_array( $stat ) ) {
749 return $stat;
750 }
751
752 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
753 }
754
762 final protected function ingestFreshFileStats( array $stats, $latest ) {
763 $success = true;
764
765 foreach ( $stats as $path => $stat ) {
766 if ( is_array( $stat ) ) {
767 // Strongly consistent backends might automatically set this flag
768 $stat['latest'] ??= $latest;
769
770 $this->cheapCache->setField( $path, 'stat', $stat );
771 if ( isset( $stat['sha1'] ) ) {
772 // Some backends store the SHA-1 hash as metadata
773 $this->cheapCache->setField(
774 $path,
775 'sha1',
776 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
777 );
778 }
779 if ( isset( $stat['xattr'] ) ) {
780 // Some backends store custom headers/metadata
781 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
782 $this->cheapCache->setField(
783 $path,
784 'xattr',
785 [ 'map' => $stat['xattr'], 'latest' => $latest ]
786 );
787 }
788 // Update persistent cache (@TODO: set all entries in one batch)
789 $this->setFileCache( $path, $stat );
790 } elseif ( $stat === self::RES_ABSENT ) {
791 $this->cheapCache->setField(
792 $path,
793 'stat',
794 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
795 );
796 $this->cheapCache->setField(
797 $path,
798 'xattr',
799 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
800 );
801 $this->cheapCache->setField(
802 $path,
803 'sha1',
804 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
805 );
806 $this->logger->debug(
807 __METHOD__ . ': File {path} does not exist',
808 [ 'path' => $path ]
809 );
810 } else {
811 $success = false;
812 $this->logger->error(
813 __METHOD__ . ': Could not stat file {path}',
814 [ 'path' => $path ]
815 );
816 }
817 }
818
819 return $success;
820 }
821
827 abstract protected function doGetFileStat( array $params );
828
829 public function getFileContentsMulti( array $params ) {
831 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
832
833 $params = $this->setConcurrencyFlags( $params );
834 $contents = $this->doGetFileContentsMulti( $params );
835 foreach ( $contents as $path => $content ) {
836 if ( !is_string( $content ) ) {
837 $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
838 }
839 }
840
841 return $contents;
842 }
843
850 protected function doGetFileContentsMulti( array $params ) {
851 $contents = [];
852 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
853 if ( $fsFile instanceof FSFile ) {
854 AtEase::suppressWarnings();
855 $content = file_get_contents( $fsFile->getPath() );
856 AtEase::restoreWarnings();
857 $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
858 } else {
859 // self::RES_ERROR or self::RES_ABSENT
860 $contents[$path] = $fsFile;
861 }
862 }
863
864 return $contents;
865 }
866
867 final public function getFileXAttributes( array $params ) {
869 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
870
872 if ( $path === null ) {
873 return self::XATTRS_FAIL; // invalid storage path
874 }
875 $latest = !empty( $params['latest'] ); // use latest data?
876 if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
877 $stat = $this->cheapCache->getField( $path, 'xattr' );
878 // If we want the latest data, check that this cached
879 // value was in fact fetched with the latest available data.
880 if ( !$latest || $stat['latest'] ) {
881 return $stat['map'];
882 }
883 }
884 $fields = $this->doGetFileXAttributes( $params );
885 if ( is_array( $fields ) ) {
886 $fields = self::normalizeXAttributes( $fields );
887 $this->cheapCache->setField(
888 $path,
889 'xattr',
890 [ 'map' => $fields, 'latest' => $latest ]
891 );
892 } elseif ( $fields === self::RES_ABSENT ) {
893 $this->cheapCache->setField(
894 $path,
895 'xattr',
896 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
897 );
898 } else {
899 $fields = self::XATTRS_FAIL; // used for all failure cases
900 }
901
902 return $fields;
903 }
904
911 protected function doGetFileXAttributes( array $params ) {
912 return [ 'headers' => [], 'metadata' => [] ]; // not supported
913 }
914
915 final public function getFileSha1Base36( array $params ) {
917 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
918
920 if ( $path === null ) {
921 return self::SHA1_FAIL; // invalid storage path
922 }
923 $latest = !empty( $params['latest'] ); // use latest data?
924 if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
925 $stat = $this->cheapCache->getField( $path, 'sha1' );
926 // If we want the latest data, check that this cached
927 // value was in fact fetched with the latest available data.
928 if ( !$latest || $stat['latest'] ) {
929 return $stat['hash'];
930 }
931 }
932 $sha1 = $this->doGetFileSha1Base36( $params );
933 if ( is_string( $sha1 ) ) {
934 $this->cheapCache->setField(
935 $path,
936 'sha1',
937 [ 'hash' => $sha1, 'latest' => $latest ]
938 );
939 } elseif ( $sha1 === self::RES_ABSENT ) {
940 $this->cheapCache->setField(
941 $path,
942 'sha1',
943 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
944 );
945 } else {
946 $sha1 = self::SHA1_FAIL; // used for all failure cases
947 }
948
949 return $sha1;
950 }
951
958 protected function doGetFileSha1Base36( array $params ) {
959 $fsFile = $this->getLocalReference( $params );
960 if ( $fsFile instanceof FSFile ) {
961 $sha1 = $fsFile->getSha1Base36();
962
963 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
964 }
965
966 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
967 }
968
969 final public function getFileProps( array $params ) {
971 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
972
973 $fsFile = $this->getLocalReference( $params );
974
975 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
976 }
977
978 final public function getLocalReferenceMulti( array $params ) {
980 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
981
982 $params = $this->setConcurrencyFlags( $params );
983
984 $fsFiles = []; // (path => FSFile)
985 $latest = !empty( $params['latest'] ); // use latest data?
986 // Reuse any files already in process cache...
987 foreach ( $params['srcs'] as $src ) {
989 if ( $path === null ) {
990 $fsFiles[$src] = self::RES_ERROR; // invalid storage path
991 } elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
992 $val = $this->expensiveCache->getField( $path, 'localRef' );
993 // If we want the latest data, check that this cached
994 // value was in fact fetched with the latest available data.
995 if ( !$latest || $val['latest'] ) {
996 $fsFiles[$src] = $val['object'];
997 }
998 }
999 }
1000 // Fetch local references of any remaining files...
1001 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
1002 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
1003 if ( $fsFile instanceof FSFile ) {
1004 $fsFiles[$path] = $fsFile;
1005 $this->expensiveCache->setField(
1006 $path,
1007 'localRef',
1008 [ 'object' => $fsFile, 'latest' => $latest ]
1009 );
1010 } else {
1011 // self::RES_ERROR or self::RES_ABSENT
1012 $fsFiles[$path] = $fsFile;
1013 }
1014 }
1015
1016 return $fsFiles;
1017 }
1018
1025 protected function doGetLocalReferenceMulti( array $params ) {
1026 return $this->doGetLocalCopyMulti( $params );
1027 }
1028
1029 final public function getLocalCopyMulti( array $params ) {
1031 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1032
1033 $params = $this->setConcurrencyFlags( $params );
1034
1035 return $this->doGetLocalCopyMulti( $params );
1036 }
1037
1043 abstract protected function doGetLocalCopyMulti( array $params );
1044
1051 public function getFileHttpUrl( array $params ) {
1052 return self::TEMPURL_ERROR; // not supported
1053 }
1054
1055 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1056 array $params
1057 ) {
1058 $ref = $this->getLocalReference( [ 'src' => $params['src'] ] );
1059 if ( $ref === false ) {
1060 return $this->newStatus( 'backend-fail-notexists', $params['src'] );
1061 } elseif ( $ref === null ) {
1062 return $this->newStatus( 'backend-fail-read', $params['src'] );
1063 } else {
1064 $file = $command->newInputFileFromFile( $ref->getPath() )
1065 ->userData( __CLASS__, $ref );
1066 $command->inputFile( $boxedName, $file );
1067 return $this->newStatus();
1068 }
1069 }
1070
1071 final public function streamFile( array $params ) {
1073 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1074 $status = $this->newStatus();
1075
1076 // Always set some fields for subclass convenience
1077 $params['options'] ??= [];
1078 $params['headers'] ??= [];
1079
1080 // Don't stream it out as text/html if there was a PHP error
1081 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
1082 print "Headers already sent, terminating.\n";
1083 $status->fatal( 'backend-fail-stream', $params['src'] );
1084 return $status;
1085 }
1086
1087 $status->merge( $this->doStreamFile( $params ) );
1088
1089 return $status;
1090 }
1091
1098 protected function doStreamFile( array $params ) {
1099 $status = $this->newStatus();
1100
1101 $flags = 0;
1102 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1103 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1104
1105 $fsFile = $this->getLocalReference( $params );
1106 if ( $fsFile ) {
1107 $streamer = new HTTPFileStreamer(
1108 $fsFile->getPath(),
1109 $this->getStreamerOptions()
1110 );
1111 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1112 } else {
1113 $res = false;
1114 HTTPFileStreamer::send404Message( $params['src'], $flags );
1115 }
1116
1117 if ( !$res ) {
1118 $status->fatal( 'backend-fail-stream', $params['src'] );
1119 }
1120
1121 return $status;
1122 }
1123
1124 final public function directoryExists( array $params ) {
1125 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1126 if ( $dir === null ) {
1127 return self::EXISTENCE_ERROR; // invalid storage path
1128 }
1129 if ( $shard !== null ) { // confined to a single container/shard
1130 return $this->doDirectoryExists( $fullCont, $dir, $params );
1131 } else { // directory is on several shards
1132 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1133 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1134 $res = false; // response
1135 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1136 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1137 if ( $exists === true ) {
1138 $res = true;
1139 break; // found one!
1140 } elseif ( $exists === self::RES_ERROR ) {
1141 $res = self::EXISTENCE_ERROR;
1142 }
1143 }
1144
1145 return $res;
1146 }
1147 }
1148
1157 abstract protected function doDirectoryExists( $container, $dir, array $params );
1158
1159 final public function getDirectoryList( array $params ) {
1160 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1161 if ( $dir === null ) {
1162 return self::EXISTENCE_ERROR; // invalid storage path
1163 }
1164 if ( $shard !== null ) {
1165 // File listing is confined to a single container/shard
1166 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1167 } else {
1168 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1169 // File listing spans multiple containers/shards
1170 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1171
1172 return new FileBackendStoreShardDirIterator( $this,
1173 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1174 }
1175 }
1176
1187 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1188
1189 final public function getFileList( array $params ) {
1190 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1191 if ( $dir === null ) {
1192 return self::LIST_ERROR; // invalid storage path
1193 }
1194 if ( $shard !== null ) {
1195 // File listing is confined to a single container/shard
1196 return $this->getFileListInternal( $fullCont, $dir, $params );
1197 } else {
1198 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1199 // File listing spans multiple containers/shards
1200 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1201
1202 return new FileBackendStoreShardFileIterator( $this,
1203 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1204 }
1205 }
1206
1217 abstract public function getFileListInternal( $container, $dir, array $params );
1218
1230 final public function getOperationsInternal( array $ops ) {
1231 $supportedOps = [
1232 'store' => StoreFileOp::class,
1233 'copy' => CopyFileOp::class,
1234 'move' => MoveFileOp::class,
1235 'delete' => DeleteFileOp::class,
1236 'create' => CreateFileOp::class,
1237 'describe' => DescribeFileOp::class,
1238 'null' => NullFileOp::class
1239 ];
1240
1241 $performOps = []; // array of FileOp objects
1242 // Build up ordered array of FileOps...
1243 foreach ( $ops as $operation ) {
1244 $opName = $operation['op'];
1245 if ( isset( $supportedOps[$opName] ) ) {
1246 $class = $supportedOps[$opName];
1247 // Get params for this operation
1248 $params = $operation;
1249 // Append the FileOp class
1250 $performOps[] = new $class( $this, $params, $this->logger );
1251 } else {
1252 throw new FileBackendError( "Operation '$opName' is not supported." );
1253 }
1254 }
1255
1256 return $performOps;
1257 }
1258
1269 final public function getPathsToLockForOpsInternal( array $performOps ) {
1270 // Build up a list of files to lock...
1271 $paths = [ 'sh' => [], 'ex' => [] ];
1272 foreach ( $performOps as $fileOp ) {
1273 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1274 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1275 }
1276 // Optimization: if doing an EX lock anyway, don't also set an SH one
1277 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1278 // Get a shared lock on the parent directory of each path changed
1279 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1280
1281 return [
1282 LockManager::LOCK_UW => $paths['sh'],
1283 LockManager::LOCK_EX => $paths['ex']
1284 ];
1285 }
1286
1287 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1288 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1289
1290 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1291 }
1292
1293 final protected function doOperationsInternal( array $ops, array $opts ) {
1295 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1296 $status = $this->newStatus();
1297
1298 // Fix up custom header name/value pairs
1299 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1300 // Build up a list of FileOps and involved paths
1301 $fileOps = $this->getOperationsInternal( $ops );
1302 $pathsUsed = [];
1303 foreach ( $fileOps as $fileOp ) {
1304 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1305 }
1306
1307 // Acquire any locks as needed for the scope of this function
1308 if ( empty( $opts['nonLocking'] ) ) {
1309 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1311 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1312 if ( !$status->isOK() ) {
1313 return $status; // abort
1314 }
1315 }
1316
1317 // Clear any file cache entries (after locks acquired)
1318 if ( empty( $opts['preserveCache'] ) ) {
1319 $this->clearCache( $pathsUsed );
1320 }
1321
1322 // Enlarge the cache to fit the stat entries of these files
1323 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1324
1325 // Load from the persistent container caches
1326 $this->primeContainerCache( $pathsUsed );
1327 // Get the latest stat info for all the files (having locked them)
1328 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1329
1330 if ( $ok ) {
1331 // Actually attempt the operation batch...
1332 $opts = $this->setConcurrencyFlags( $opts );
1333 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1334 } else {
1335 // If we could not even stat some files, then bail out
1336 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1337 foreach ( $ops as $i => $op ) { // mark each op as failed
1338 $subStatus->success[$i] = false;
1339 ++$subStatus->failCount;
1340 }
1341 $this->logger->error( static::class . "-{$this->name} " .
1342 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1343 }
1344
1345 // Merge errors into StatusValue fields
1346 $status->merge( $subStatus );
1347 $status->success = $subStatus->success; // not done in merge()
1348
1349 // Shrink the stat cache back to normal size
1350 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1351
1352 return $status;
1353 }
1354
1355 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1357 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1358 $status = $this->newStatus();
1359
1360 // Fix up custom header name/value pairs
1361 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1362 // Build up a list of FileOps and involved paths
1363 $fileOps = $this->getOperationsInternal( $ops );
1364 $pathsUsed = [];
1365 foreach ( $fileOps as $fileOp ) {
1366 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1367 }
1368
1369 // Clear any file cache entries for involved paths
1370 $this->clearCache( $pathsUsed );
1371
1372 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1373 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1374 $maxConcurrency = $this->concurrency; // throttle
1376 $statuses = []; // array of (index => StatusValue)
1378 $batch = [];
1379 foreach ( $fileOps as $index => $fileOp ) {
1380 $subStatus = $async
1381 ? $fileOp->attemptAsyncQuick()
1382 : $fileOp->attemptQuick();
1383 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1384 if ( count( $batch ) >= $maxConcurrency ) {
1385 // Execute this batch. Don't queue any more ops since they contain
1386 // open filehandles which are a limited resource (T230245).
1387 $statuses += $this->executeOpHandlesInternal( $batch );
1388 $batch = [];
1389 }
1390 $batch[$index] = $subStatus->value; // keep index
1391 } else { // error or completed
1392 $statuses[$index] = $subStatus; // keep index
1393 }
1394 }
1395 if ( count( $batch ) ) {
1396 $statuses += $this->executeOpHandlesInternal( $batch );
1397 }
1398 // Marshall and merge all the responses...
1399 foreach ( $statuses as $index => $subStatus ) {
1400 $status->merge( $subStatus );
1401 if ( $subStatus->isOK() ) {
1402 $status->success[$index] = true;
1403 ++$status->successCount;
1404 } else {
1405 $status->success[$index] = false;
1406 ++$status->failCount;
1407 }
1408 }
1409
1410 $this->clearCache( $pathsUsed );
1411
1412 return $status;
1413 }
1414
1424 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1426 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1427
1428 foreach ( $fileOpHandles as $fileOpHandle ) {
1429 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1430 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1431 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1432 throw new InvalidArgumentException( "Expected handle for this file backend." );
1433 }
1434 }
1435
1436 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1437 foreach ( $fileOpHandles as $fileOpHandle ) {
1438 $fileOpHandle->closeResources();
1439 }
1440
1441 return $statuses;
1442 }
1443
1453 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1454 if ( count( $fileOpHandles ) ) {
1455 throw new FileBackendError( "Backend does not support asynchronous operations." );
1456 }
1457
1458 return [];
1459 }
1460
1472 protected function sanitizeOpHeaders( array $op ) {
1473 static $longs = [ 'content-disposition' ];
1474
1475 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1476 $newHeaders = [];
1477 foreach ( $op['headers'] as $name => $value ) {
1478 $name = strtolower( $name );
1479 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1480 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1481 $this->logger->error( "Header '{header}' is too long.", [
1482 'filebackend' => $this->name,
1483 'header' => "$name: $value",
1484 ] );
1485 } else {
1486 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1487 }
1488 }
1489 $op['headers'] = $newHeaders;
1490 }
1491
1492 return $op;
1493 }
1494
1495 final public function preloadCache( array $paths ) {
1496 $fullConts = []; // full container names
1497 foreach ( $paths as $path ) {
1498 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1499 $fullConts[] = $fullCont;
1500 }
1501 // Load from the persistent file and container caches
1502 $this->primeContainerCache( $fullConts );
1503 $this->primeFileCache( $paths );
1504 }
1505
1506 final public function clearCache( ?array $paths = null ) {
1507 if ( is_array( $paths ) ) {
1508 $paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
1509 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1510 }
1511 if ( $paths === null ) {
1512 $this->cheapCache->clear();
1513 $this->expensiveCache->clear();
1514 } else {
1515 foreach ( $paths as $path ) {
1516 $this->cheapCache->clear( $path );
1517 $this->expensiveCache->clear( $path );
1518 }
1519 }
1520 $this->doClearCache( $paths );
1521 }
1522
1531 protected function doClearCache( ?array $paths = null ) {
1532 }
1533
1534 final public function preloadFileStat( array $params ) {
1536 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1537
1538 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1539 $stats = $this->doGetFileStatMulti( $params );
1540 if ( $stats === null ) {
1541 return true; // not supported
1542 }
1543
1544 // Whether this queried the backend in high consistency mode
1545 $latest = !empty( $params['latest'] );
1546
1547 return $this->ingestFreshFileStats( $stats, $latest );
1548 }
1549
1563 protected function doGetFileStatMulti( array $params ) {
1564 return null; // not supported
1565 }
1566
1574 abstract protected function directoriesAreVirtual();
1575
1586 final protected static function isValidShortContainerName( $container ) {
1587 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1588 // might be used by subclasses. Reserve the dot character.
1589 // The only way dots end up in containers (e.g. resolveStoragePath)
1590 // is due to the wikiId container prefix or the above suffixes.
1591 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1592 }
1593
1603 final protected static function isValidContainerName( $container ) {
1604 // This accounts for NTFS, Swift, and Ceph restrictions
1605 // and disallows directory separators or traversal characters.
1606 // Note that matching strings URL encode to the same string;
1607 // in Swift/Ceph, the length restriction is *after* URL encoding.
1608 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1609 }
1610
1624 final protected function resolveStoragePath( $storagePath ) {
1625 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1626 if ( $backend === $this->name ) { // must be for this backend
1627 $relPath = self::normalizeContainerPath( $relPath );
1628 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1629 // Get shard for the normalized path if this container is sharded
1630 $cShard = $this->getContainerShard( $shortCont, $relPath );
1631 // Validate and sanitize the relative path (backend-specific)
1632 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1633 if ( $relPath !== null ) {
1634 // Prepend any domain ID prefix to the container name
1635 $container = $this->fullContainerName( $shortCont );
1636 if ( self::isValidContainerName( $container ) ) {
1637 // Validate and sanitize the container name (backend-specific)
1638 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1639 if ( $container !== null ) {
1640 return [ $container, $relPath, $cShard ];
1641 }
1642 }
1643 }
1644 }
1645 }
1646
1647 return [ null, null, null ];
1648 }
1649
1665 final protected function resolveStoragePathReal( $storagePath ) {
1666 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1667 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1668 return [ $container, $relPath ];
1669 }
1670
1671 return [ null, null ];
1672 }
1673
1682 final protected function getContainerShard( $container, $relPath ) {
1683 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1684 if ( $levels == 1 || $levels == 2 ) {
1685 // Hash characters are either base 16 or 36
1686 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1687 // Get a regex that represents the shard portion of paths.
1688 // The concatenation of the captures gives us the shard.
1689 if ( $levels === 1 ) { // 16 or 36 shards per container
1690 $hashDirRegex = '(' . $char . ')';
1691 } else { // 256 or 1296 shards per container
1692 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1693 $hashDirRegex = $char . '/(' . $char . '{2})';
1694 } else { // short hash dir format (e.g. "a/b/c")
1695 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1696 }
1697 }
1698 // Allow certain directories to be above the hash dirs so as
1699 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1700 // They must be 2+ chars to avoid any hash directory ambiguity.
1701 $m = [];
1702 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1703 return '.' . implode( '', array_slice( $m, 1 ) );
1704 }
1705
1706 return null; // failed to match
1707 }
1708
1709 return ''; // no sharding
1710 }
1711
1720 final public function isSingleShardPathInternal( $storagePath ) {
1721 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1722
1723 return ( $shard !== null );
1724 }
1725
1734 final protected function getContainerHashLevels( $container ) {
1735 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1736 $config = $this->shardViaHashLevels[$container];
1737 $hashLevels = (int)$config['levels'];
1738 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1739 $hashBase = (int)$config['base'];
1740 if ( $hashBase == 16 || $hashBase == 36 ) {
1741 return [ $hashLevels, $hashBase, $config['repeat'] ];
1742 }
1743 }
1744 }
1745
1746 return [ 0, 0, false ]; // no sharding
1747 }
1748
1755 final protected function getContainerSuffixes( $container ) {
1756 $shards = [];
1757 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1758 if ( $digits > 0 ) {
1759 $numShards = $base ** $digits;
1760 for ( $index = 0; $index < $numShards; $index++ ) {
1761 $shards[] = '.' . \Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1762 }
1763 }
1764
1765 return $shards;
1766 }
1767
1774 final protected function fullContainerName( $container ) {
1775 if ( $this->domainId != '' ) {
1776 return "{$this->domainId}-$container";
1777 } else {
1778 return $container;
1779 }
1780 }
1781
1791 protected function resolveContainerName( $container ) {
1792 return $container;
1793 }
1794
1806 protected function resolveContainerPath( $container, $relStoragePath ) {
1807 return $relStoragePath;
1808 }
1809
1816 private function containerCacheKey( $container ) {
1817 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1818 }
1819
1826 final protected function setContainerCache( $container, array $val ) {
1827 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1828 $this->logger->warning( "Unable to set stat cache for container {container}.",
1829 [ 'filebackend' => $this->name, 'container' => $container ]
1830 );
1831 }
1832 }
1833
1840 final protected function deleteContainerCache( $container ) {
1841 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1842 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1843 [ 'filebackend' => $this->name, 'container' => $container ]
1844 );
1845 }
1846 }
1847
1855 final protected function primeContainerCache( array $items ) {
1857 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1858
1859 $paths = []; // list of storage paths
1860 $contNames = []; // (cache key => resolved container name)
1861 // Get all the paths/containers from the items...
1862 foreach ( $items as $item ) {
1863 if ( self::isStoragePath( $item ) ) {
1864 $paths[] = $item;
1865 } elseif ( is_string( $item ) ) { // full container name
1866 $contNames[$this->containerCacheKey( $item )] = $item;
1867 }
1868 }
1869 // Get all the corresponding cache keys for paths...
1870 foreach ( $paths as $path ) {
1871 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1872 if ( $fullCont !== null ) { // valid path for this backend
1873 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1874 }
1875 }
1876
1877 $contInfo = []; // (resolved container name => cache value)
1878 // Get all cache entries for these container cache keys...
1879 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1880 foreach ( $values as $cacheKey => $val ) {
1881 $contInfo[$contNames[$cacheKey]] = $val;
1882 }
1883
1884 // Populate the container process cache for the backend...
1885 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1886 }
1887
1896 protected function doPrimeContainerCache( array $containerInfo ) {
1897 }
1898
1905 private function fileCacheKey( $path ) {
1906 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1907 }
1908
1917 final protected function setFileCache( $path, array $val ) {
1919 if ( $path === null ) {
1920 return; // invalid storage path
1921 }
1922 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1923 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1924 $key = $this->fileCacheKey( $path );
1925 // Set the cache unless it is currently salted.
1926 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1927 $this->logger->warning( "Unable to set stat cache for file {path}.",
1928 [ 'filebackend' => $this->name, 'path' => $path ]
1929 );
1930 }
1931 }
1932
1941 final protected function deleteFileCache( $path ) {
1943 if ( $path === null ) {
1944 return; // invalid storage path
1945 }
1946 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1947 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1948 [ 'filebackend' => $this->name, 'path' => $path ]
1949 );
1950 }
1951 }
1952
1960 final protected function primeFileCache( array $items ) {
1962 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1963
1964 $paths = []; // list of storage paths
1965 $pathNames = []; // (cache key => storage path)
1966 // Get all the paths/containers from the items...
1967 foreach ( $items as $item ) {
1968 if ( self::isStoragePath( $item ) ) {
1970 if ( $path !== null ) {
1971 $paths[] = $path;
1972 }
1973 }
1974 }
1975 // Get all the corresponding cache keys for paths...
1976 foreach ( $paths as $path ) {
1977 [ , $rel, ] = $this->resolveStoragePath( $path );
1978 if ( $rel !== null ) { // valid path for this backend
1979 $pathNames[$this->fileCacheKey( $path )] = $path;
1980 }
1981 }
1982 // Get all cache entries for these file cache keys.
1983 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1984 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1985 // Load all of the results into process cache...
1986 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1987 $path = $pathNames[$cacheKey];
1988 // This flag only applies to stat info loaded directly
1989 // from a high consistency backend query to the process cache
1990 unset( $stat['latest'] );
1991
1992 $this->cheapCache->setField( $path, 'stat', $stat );
1993 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1994 // Some backends store SHA-1 as metadata
1995 $this->cheapCache->setField(
1996 $path,
1997 'sha1',
1998 [ 'hash' => $stat['sha1'], 'latest' => false ]
1999 );
2000 }
2001 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
2002 // Some backends store custom headers/metadata
2003 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
2004 $this->cheapCache->setField(
2005 $path,
2006 'xattr',
2007 [ 'map' => $stat['xattr'], 'latest' => false ]
2008 );
2009 }
2010 }
2011 }
2012
2020 final protected static function normalizeXAttributes( array $xattr ) {
2021 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
2022
2023 foreach ( $xattr['headers'] as $name => $value ) {
2024 $newXAttr['headers'][strtolower( $name )] = $value;
2025 }
2026
2027 foreach ( $xattr['metadata'] as $name => $value ) {
2028 $newXAttr['metadata'][strtolower( $name )] = $value;
2029 }
2030
2031 return $newXAttr;
2032 }
2033
2040 final protected function setConcurrencyFlags( array $opts ) {
2041 $opts['concurrency'] = 1; // off
2042 if ( $this->parallelize === 'implicit' ) {
2043 if ( $opts['parallelize'] ?? true ) {
2044 $opts['concurrency'] = $this->concurrency;
2045 }
2046 } elseif ( $this->parallelize === 'explicit' ) {
2047 if ( !empty( $opts['parallelize'] ) ) {
2048 $opts['concurrency'] = $this->concurrency;
2049 }
2050 }
2051
2052 return $opts;
2053 }
2054
2064 protected function getContentType( $storagePath, $content, $fsPath ) {
2065 if ( $this->mimeCallback ) {
2066 return call_user_func_array( $this->mimeCallback, func_get_args() );
2067 }
2068
2069 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2070 return $mime ?: 'unknown/unknown';
2071 }
2072}
2073
2075class_alias( FileBackendStore::class, 'FileBackendStore' );
array $params
The job parameters.
Resource locking handling.
Store key-value entries in a size-limited in-memory LRU cache.
JSON formatter wrapper class.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Class representing a non-directory file on the file system.
Definition FSFile.php:34
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.
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.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
doDirectoryExists( $container, $dir, array $params)
doOperationsInternal(array $ops, array $opts)
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_...
getContainerShard( $container, $relPath)
Get the container name shard suffix for a given path.
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.
concatenate(array $params)
Concatenate a list of storage files into a single file system file.
describeInternal(array $params)
Alter metadata for a file at the storage path.
MapCacheLRU $cheapCache
Map of paths to small (RAM/disk) cache items.
static normalizeXAttributes(array $xattr)
Normalize file headers/metadata to the FileBackend::getFileXAttributes() format.
MapCacheLRU $expensiveCache
Map of paths to large (RAM/disk) cache items.
directoryExists(array $params)
Check if a directory exists at a given storage path.
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)
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.
doSecureInternal( $container, $dir, 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.
setContainerCache( $container, array $val)
Set the cached info for a container.
maxFileSizeInternal()
Get the maximum allowable file size given backend medium restrictions and basic performance constrain...
doClearCache(?array $paths=null)
Clears any additional stat caches for storage paths.
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.
fullContainerName( $container)
Get the full container name, including the domain ID prefix.
getDirectoryListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
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.
getFileListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
streamFile(array $params)
Stream the content of the file at a storage path in the backend.
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.
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.
doPrepareInternal( $container, $dir, array $params)
copyInternal(array $params)
Copy a file from one storage path to another in the backend.
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.
doPublishInternal( $container, $dir, array $params)
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
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.
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.
doCleanInternal( $container, $dir, array $params)
getOperationsInternal(array $ops)
Return a list of FileOp objects from a list of operations.
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
getFileSha1Base36(array $params)
Get a SHA-1 hash of the content of the file at a storage path in the backend.
addShellboxInputFile(BoxedCommand $command, string $boxedName, array $params)
Add a file to a Shellbox command as an input file.
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.
newStatus(... $args)
Yields the result of the status wrapper callback on either:
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 ...
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.
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.
Copy a file from one storage path to another in the backend.
Create a file in the backend with the given content.
Delete a file at the given storage path from the backend.
Change metadata for a file at the given storage path in the backend.
FileBackend helper class for representing operations.
Definition FileOp.php:47
Move a file from one storage path to another in the backend.
Placeholder operation that has no params and does nothing.
Store a file into the backend from a file on the file system.
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:89
No-op implementation that stores nothing.
Multi-datacenter aware caching interface.