MediaWiki master
FileBackendStore.php
Go to the documentation of this file.
1<?php
24namespace Wikimedia\FileBackend;
25
26use InvalidArgumentException;
27use LockManager;
28use MapCacheLRU;
30use StatusValue;
31use Traversable;
32use Wikimedia\AtEase\AtEase;
48use Wikimedia\Timestamp\ConvertibleTimestamp;
49
64abstract class FileBackendStore extends FileBackend {
66 protected $memCache;
68 protected $srvCache;
70 protected $cheapCache;
72 protected $expensiveCache;
73
75 protected $shardViaHashLevels = [];
76
78 protected $mimeCallback;
79
81 protected $maxFileSize = 32 * 1024 * 1024 * 1024;
82
83 protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
84 protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
85 protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
86
88 protected const RES_ABSENT = false;
90 protected const RES_ERROR = null;
91
93 protected const ABSENT_NORMAL = 'FNE-N';
95 protected const ABSENT_LATEST = 'FNE-L';
96
110 public function __construct( array $config ) {
111 parent::__construct( $config );
112 $this->mimeCallback = $config['mimeCallback'] ?? null;
113 $this->srvCache = new EmptyBagOStuff(); // disabled by default
114 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
115 $this->cheapCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
116 $this->expensiveCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
117 }
118
126 final public function maxFileSizeInternal() {
127 return min( $this->maxFileSize, PHP_INT_MAX );
128 }
129
140 abstract public function isPathUsableInternal( $storagePath );
141
160 final public function createInternal( array $params ) {
162 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
163
164 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
165 $status = $this->newStatus( 'backend-fail-maxsize',
166 $params['dst'], $this->maxFileSizeInternal() );
167 } else {
168 $status = $this->doCreateInternal( $params );
169 $this->clearCache( [ $params['dst'] ] );
170 if ( $params['dstExists'] ?? true ) {
171 $this->deleteFileCache( $params['dst'] ); // persistent cache
172 }
173 }
174
175 return $status;
176 }
177
183 abstract protected function doCreateInternal( array $params );
184
203 final public function storeInternal( array $params ) {
205 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
206
207 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
208 $status = $this->newStatus( 'backend-fail-maxsize',
209 $params['dst'], $this->maxFileSizeInternal() );
210 } else {
211 $status = $this->doStoreInternal( $params );
212 $this->clearCache( [ $params['dst'] ] );
213 if ( $params['dstExists'] ?? true ) {
214 $this->deleteFileCache( $params['dst'] ); // persistent cache
215 }
216 }
217
218 return $status;
219 }
220
226 abstract protected function doStoreInternal( array $params );
227
247 final public function copyInternal( array $params ) {
249 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
250
251 $status = $this->doCopyInternal( $params );
252 $this->clearCache( [ $params['dst'] ] );
253 if ( $params['dstExists'] ?? true ) {
254 $this->deleteFileCache( $params['dst'] ); // persistent cache
255 }
256
257 return $status;
258 }
259
265 abstract protected function doCopyInternal( array $params );
266
281 final public function deleteInternal( array $params ) {
283 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
284
285 $status = $this->doDeleteInternal( $params );
286 $this->clearCache( [ $params['src'] ] );
287 $this->deleteFileCache( $params['src'] ); // persistent cache
288 return $status;
289 }
290
296 abstract protected function doDeleteInternal( array $params );
297
317 final public function moveInternal( array $params ) {
319 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
320
321 $status = $this->doMoveInternal( $params );
322 $this->clearCache( [ $params['src'], $params['dst'] ] );
323 $this->deleteFileCache( $params['src'] ); // persistent cache
324 if ( $params['dstExists'] ?? true ) {
325 $this->deleteFileCache( $params['dst'] ); // persistent cache
326 }
327
328 return $status;
329 }
330
336 abstract protected function doMoveInternal( array $params );
337
352 final public function describeInternal( array $params ) {
354 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
355
356 if ( count( $params['headers'] ) ) {
357 $status = $this->doDescribeInternal( $params );
358 $this->clearCache( [ $params['src'] ] );
359 $this->deleteFileCache( $params['src'] ); // persistent cache
360 } else {
361 $status = $this->newStatus(); // nothing to do
362 }
363
364 return $status;
365 }
366
373 protected function doDescribeInternal( array $params ) {
374 return $this->newStatus();
375 }
376
384 final public function nullInternal( array $params ) {
385 return $this->newStatus();
386 }
387
388 final public function concatenate( array $params ) {
390 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
391 $status = $this->newStatus();
392
393 // Try to lock the source files for the scope of this function
395 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
396 if ( $status->isOK() ) {
397 // Actually do the file concatenation...
398 $start_time = microtime( true );
399 $status->merge( $this->doConcatenate( $params ) );
400 $sec = microtime( true ) - $start_time;
401 if ( !$status->isOK() ) {
402 $this->logger->error( static::class . "-{$this->name}" .
403 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
404 }
405 }
406
407 return $status;
408 }
409
416 protected function doConcatenate( array $params ) {
417 $status = $this->newStatus();
418 $tmpPath = $params['dst'];
419 unset( $params['latest'] );
420
421 // Check that the specified temp file is valid...
422 AtEase::suppressWarnings();
423 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
424 AtEase::restoreWarnings();
425 if ( !$ok ) { // not present or not empty
426 $status->fatal( 'backend-fail-opentemp', $tmpPath );
427
428 return $status;
429 }
430
431 // Get local FS versions of the chunks needed for the concatenation...
432 $fsFiles = $this->getLocalReferenceMulti( $params );
433 foreach ( $fsFiles as $path => &$fsFile ) {
434 if ( !$fsFile ) { // chunk failed to download?
435 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
436 if ( !$fsFile ) { // retry failed?
437 $status->fatal(
438 $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
439 $path
440 );
441
442 return $status;
443 }
444 }
445 }
446 unset( $fsFile ); // unset reference so we can reuse $fsFile
447
448 // Get a handle for the destination temp file
449 $tmpHandle = fopen( $tmpPath, 'ab' );
450 if ( $tmpHandle === false ) {
451 $status->fatal( 'backend-fail-opentemp', $tmpPath );
452
453 return $status;
454 }
455
456 // Build up the temp file using the source chunks (in order)...
457 foreach ( $fsFiles as $virtualSource => $fsFile ) {
458 // Get a handle to the local FS version
459 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
460 if ( $sourceHandle === false ) {
461 fclose( $tmpHandle );
462 $status->fatal( 'backend-fail-read', $virtualSource );
463
464 return $status;
465 }
466 // Append chunk to file (pass chunk size to avoid magic quotes)
467 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
468 fclose( $sourceHandle );
469 fclose( $tmpHandle );
470 $status->fatal( 'backend-fail-writetemp', $tmpPath );
471
472 return $status;
473 }
474 fclose( $sourceHandle );
475 }
476 if ( !fclose( $tmpHandle ) ) {
477 $status->fatal( 'backend-fail-closetemp', $tmpPath );
478
479 return $status;
480 }
481
482 clearstatcache(); // temp file changed
483
484 return $status;
485 }
486
490 final protected function doPrepare( array $params ) {
492 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
493 $status = $this->newStatus();
494
495 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
496 if ( $dir === null ) {
497 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
498
499 return $status; // invalid storage path
500 }
501
502 if ( $shard !== null ) { // confined to a single container/shard
503 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
504 } else { // directory is on several shards
505 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
506 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
507 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
508 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
509 }
510 }
511
512 return $status;
513 }
514
523 protected function doPrepareInternal( $container, $dir, array $params ) {
524 return $this->newStatus();
525 }
526
527 final protected function doSecure( array $params ) {
529 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
530 $status = $this->newStatus();
531
532 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
533 if ( $dir === null ) {
534 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
535
536 return $status; // invalid storage path
537 }
538
539 if ( $shard !== null ) { // confined to a single container/shard
540 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
541 } else { // directory is on several shards
542 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
543 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
544 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
545 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
546 }
547 }
548
549 return $status;
550 }
551
560 protected function doSecureInternal( $container, $dir, array $params ) {
561 return $this->newStatus();
562 }
563
564 final protected function doPublish( array $params ) {
566 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
567 $status = $this->newStatus();
568
569 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
570 if ( $dir === null ) {
571 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
572
573 return $status; // invalid storage path
574 }
575
576 if ( $shard !== null ) { // confined to a single container/shard
577 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
578 } else { // directory is on several shards
579 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
580 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
581 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
582 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
583 }
584 }
585
586 return $status;
587 }
588
597 protected function doPublishInternal( $container, $dir, array $params ) {
598 return $this->newStatus();
599 }
600
601 final protected function doClean( array $params ) {
603 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
604 $status = $this->newStatus();
605
606 // Recursive: first delete all empty subdirs recursively
607 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
608 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
609 if ( $subDirsRel !== null ) { // no errors
610 foreach ( $subDirsRel as $subDirRel ) {
611 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
612 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
613 }
614 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
615 }
616 }
617
618 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
619 if ( $dir === null ) {
620 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
621
622 return $status; // invalid storage path
623 }
624
625 // Attempt to lock this directory...
626 $filesLockEx = [ $params['dir'] ];
628 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
629 if ( !$status->isOK() ) {
630 return $status; // abort
631 }
632
633 if ( $shard !== null ) { // confined to a single container/shard
634 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
635 $this->deleteContainerCache( $fullCont ); // purge cache
636 } else { // directory is on several shards
637 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
638 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
639 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
640 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
641 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
642 }
643 }
644
645 return $status;
646 }
647
656 protected function doCleanInternal( $container, $dir, array $params ) {
657 return $this->newStatus();
658 }
659
660 final public function fileExists( array $params ) {
662 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
663
664 $stat = $this->getFileStat( $params );
665 if ( is_array( $stat ) ) {
666 return true;
667 }
668
669 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
670 }
671
672 final public function getFileTimestamp( array $params ) {
674 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
675
676 $stat = $this->getFileStat( $params );
677 if ( is_array( $stat ) ) {
678 return $stat['mtime'];
679 }
680
681 return self::TIMESTAMP_FAIL; // all failure cases
682 }
683
684 final public function getFileSize( array $params ) {
686 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
687
688 $stat = $this->getFileStat( $params );
689 if ( is_array( $stat ) ) {
690 return $stat['size'];
691 }
692
693 return self::SIZE_FAIL; // all failure cases
694 }
695
696 final public function getFileStat( array $params ) {
698 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
699
701 if ( $path === null ) {
702 return self::STAT_ERROR; // invalid storage path
703 }
704
705 // Whether to bypass cache except for process cache entries loaded directly from
706 // high consistency backend queries (caller handles any cache flushing and locking)
707 $latest = !empty( $params['latest'] );
708 // Whether to ignore cache entries missing the SHA-1 field for existing files
709 $requireSHA1 = !empty( $params['requireSHA1'] );
710
711 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
712 // Load the persistent stat cache into process cache if needed
713 if ( !$latest ) {
714 if (
715 // File stat is not in process cache
716 $stat === null ||
717 // Key/value store backends might opportunistically set file stat process
718 // cache entries from object listings that do not include the SHA-1. In that
719 // case, loading the persistent stat cache will likely yield the SHA-1.
720 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
721 ) {
722 $this->primeFileCache( [ $path ] );
723 // Get any newly process-cached entry
724 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
725 }
726 }
727
728 if ( is_array( $stat ) ) {
729 if (
730 ( !$latest || !empty( $stat['latest'] ) ) &&
731 ( !$requireSHA1 || isset( $stat['sha1'] ) )
732 ) {
733 return $stat;
734 }
735 } elseif ( $stat === self::ABSENT_LATEST ) {
736 return self::STAT_ABSENT;
737 } elseif ( $stat === self::ABSENT_NORMAL ) {
738 if ( !$latest ) {
739 return self::STAT_ABSENT;
740 }
741 }
742
743 // Load the file stat from the backend and update caches
744 $stat = $this->doGetFileStat( $params );
745 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
746
747 if ( is_array( $stat ) ) {
748 return $stat;
749 }
750
751 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
752 }
753
761 final protected function ingestFreshFileStats( array $stats, $latest ) {
762 $success = true;
763
764 foreach ( $stats as $path => $stat ) {
765 if ( is_array( $stat ) ) {
766 // Strongly consistent backends might automatically set this flag
767 $stat['latest'] ??= $latest;
768
769 $this->cheapCache->setField( $path, 'stat', $stat );
770 if ( isset( $stat['sha1'] ) ) {
771 // Some backends store the SHA-1 hash as metadata
772 $this->cheapCache->setField(
773 $path,
774 'sha1',
775 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
776 );
777 }
778 if ( isset( $stat['xattr'] ) ) {
779 // Some backends store custom headers/metadata
780 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
781 $this->cheapCache->setField(
782 $path,
783 'xattr',
784 [ 'map' => $stat['xattr'], 'latest' => $latest ]
785 );
786 }
787 // Update persistent cache (@TODO: set all entries in one batch)
788 $this->setFileCache( $path, $stat );
789 } elseif ( $stat === self::RES_ABSENT ) {
790 $this->cheapCache->setField(
791 $path,
792 'stat',
793 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
794 );
795 $this->cheapCache->setField(
796 $path,
797 'xattr',
798 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
799 );
800 $this->cheapCache->setField(
801 $path,
802 'sha1',
803 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
804 );
805 $this->logger->debug(
806 __METHOD__ . ': File {path} does not exist',
807 [ 'path' => $path ]
808 );
809 } else {
810 $success = false;
811 $this->logger->error(
812 __METHOD__ . ': Could not stat file {path}',
813 [ 'path' => $path ]
814 );
815 }
816 }
817
818 return $success;
819 }
820
826 abstract protected function doGetFileStat( array $params );
827
828 public function getFileContentsMulti( array $params ) {
830 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
831
832 $params = $this->setConcurrencyFlags( $params );
833 $contents = $this->doGetFileContentsMulti( $params );
834 foreach ( $contents as $path => $content ) {
835 if ( !is_string( $content ) ) {
836 $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
837 }
838 }
839
840 return $contents;
841 }
842
849 protected function doGetFileContentsMulti( array $params ) {
850 $contents = [];
851 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
852 if ( $fsFile instanceof FSFile ) {
853 AtEase::suppressWarnings();
854 $content = file_get_contents( $fsFile->getPath() );
855 AtEase::restoreWarnings();
856 $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
857 } else {
858 // self::RES_ERROR or self::RES_ABSENT
859 $contents[$path] = $fsFile;
860 }
861 }
862
863 return $contents;
864 }
865
866 final public function getFileXAttributes( array $params ) {
868 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
869
871 if ( $path === null ) {
872 return self::XATTRS_FAIL; // invalid storage path
873 }
874 $latest = !empty( $params['latest'] ); // use latest data?
875 if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
876 $stat = $this->cheapCache->getField( $path, 'xattr' );
877 // If we want the latest data, check that this cached
878 // value was in fact fetched with the latest available data.
879 if ( !$latest || $stat['latest'] ) {
880 return $stat['map'];
881 }
882 }
883 $fields = $this->doGetFileXAttributes( $params );
884 if ( is_array( $fields ) ) {
885 $fields = self::normalizeXAttributes( $fields );
886 $this->cheapCache->setField(
887 $path,
888 'xattr',
889 [ 'map' => $fields, 'latest' => $latest ]
890 );
891 } elseif ( $fields === self::RES_ABSENT ) {
892 $this->cheapCache->setField(
893 $path,
894 'xattr',
895 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
896 );
897 } else {
898 $fields = self::XATTRS_FAIL; // used for all failure cases
899 }
900
901 return $fields;
902 }
903
910 protected function doGetFileXAttributes( array $params ) {
911 return [ 'headers' => [], 'metadata' => [] ]; // not supported
912 }
913
914 final public function getFileSha1Base36( array $params ) {
916 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
917
919 if ( $path === null ) {
920 return self::SHA1_FAIL; // invalid storage path
921 }
922 $latest = !empty( $params['latest'] ); // use latest data?
923 if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
924 $stat = $this->cheapCache->getField( $path, 'sha1' );
925 // If we want the latest data, check that this cached
926 // value was in fact fetched with the latest available data.
927 if ( !$latest || $stat['latest'] ) {
928 return $stat['hash'];
929 }
930 }
931 $sha1 = $this->doGetFileSha1Base36( $params );
932 if ( is_string( $sha1 ) ) {
933 $this->cheapCache->setField(
934 $path,
935 'sha1',
936 [ 'hash' => $sha1, 'latest' => $latest ]
937 );
938 } elseif ( $sha1 === self::RES_ABSENT ) {
939 $this->cheapCache->setField(
940 $path,
941 'sha1',
942 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
943 );
944 } else {
945 $sha1 = self::SHA1_FAIL; // used for all failure cases
946 }
947
948 return $sha1;
949 }
950
957 protected function doGetFileSha1Base36( array $params ) {
958 $fsFile = $this->getLocalReference( $params );
959 if ( $fsFile instanceof FSFile ) {
960 $sha1 = $fsFile->getSha1Base36();
961
962 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
963 }
964
965 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
966 }
967
968 final public function getFileProps( array $params ) {
970 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
971
972 $fsFile = $this->getLocalReference( $params );
973
974 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
975 }
976
977 final public function getLocalReferenceMulti( array $params ) {
979 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
980
981 $params = $this->setConcurrencyFlags( $params );
982
983 $fsFiles = []; // (path => FSFile)
984 $latest = !empty( $params['latest'] ); // use latest data?
985 // Reuse any files already in process cache...
986 foreach ( $params['srcs'] as $src ) {
988 if ( $path === null ) {
989 $fsFiles[$src] = self::RES_ERROR; // invalid storage path
990 } elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
991 $val = $this->expensiveCache->getField( $path, 'localRef' );
992 // If we want the latest data, check that this cached
993 // value was in fact fetched with the latest available data.
994 if ( !$latest || $val['latest'] ) {
995 $fsFiles[$src] = $val['object'];
996 }
997 }
998 }
999 // Fetch local references of any remaining files...
1000 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
1001 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
1002 if ( $fsFile instanceof FSFile ) {
1003 $fsFiles[$path] = $fsFile;
1004 $this->expensiveCache->setField(
1005 $path,
1006 'localRef',
1007 [ 'object' => $fsFile, 'latest' => $latest ]
1008 );
1009 } else {
1010 // self::RES_ERROR or self::RES_ABSENT
1011 $fsFiles[$path] = $fsFile;
1012 }
1013 }
1014
1015 return $fsFiles;
1016 }
1017
1024 protected function doGetLocalReferenceMulti( array $params ) {
1025 return $this->doGetLocalCopyMulti( $params );
1026 }
1027
1028 final public function getLocalCopyMulti( array $params ) {
1030 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1031
1032 $params = $this->setConcurrencyFlags( $params );
1033
1034 return $this->doGetLocalCopyMulti( $params );
1035 }
1036
1042 abstract protected function doGetLocalCopyMulti( array $params );
1043
1050 public function getFileHttpUrl( array $params ) {
1051 return self::TEMPURL_ERROR; // not supported
1052 }
1053
1054 final public function streamFile( array $params ) {
1056 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1057 $status = $this->newStatus();
1058
1059 // Always set some fields for subclass convenience
1060 $params['options'] ??= [];
1061 $params['headers'] ??= [];
1062
1063 // Don't stream it out as text/html if there was a PHP error
1064 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
1065 print "Headers already sent, terminating.\n";
1066 $status->fatal( 'backend-fail-stream', $params['src'] );
1067 return $status;
1068 }
1069
1070 $status->merge( $this->doStreamFile( $params ) );
1071
1072 return $status;
1073 }
1074
1081 protected function doStreamFile( array $params ) {
1082 $status = $this->newStatus();
1083
1084 $flags = 0;
1085 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1086 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1087
1088 $fsFile = $this->getLocalReference( $params );
1089 if ( $fsFile ) {
1090 $streamer = new HTTPFileStreamer(
1091 $fsFile->getPath(),
1092 $this->getStreamerOptions()
1093 );
1094 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1095 } else {
1096 $res = false;
1097 HTTPFileStreamer::send404Message( $params['src'], $flags );
1098 }
1099
1100 if ( !$res ) {
1101 $status->fatal( 'backend-fail-stream', $params['src'] );
1102 }
1103
1104 return $status;
1105 }
1106
1107 final public function directoryExists( array $params ) {
1108 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1109 if ( $dir === null ) {
1110 return self::EXISTENCE_ERROR; // invalid storage path
1111 }
1112 if ( $shard !== null ) { // confined to a single container/shard
1113 return $this->doDirectoryExists( $fullCont, $dir, $params );
1114 } else { // directory is on several shards
1115 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1116 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1117 $res = false; // response
1118 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1119 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1120 if ( $exists === true ) {
1121 $res = true;
1122 break; // found one!
1123 } elseif ( $exists === self::RES_ERROR ) {
1124 $res = self::EXISTENCE_ERROR;
1125 }
1126 }
1127
1128 return $res;
1129 }
1130 }
1131
1140 abstract protected function doDirectoryExists( $container, $dir, array $params );
1141
1142 final public function getDirectoryList( array $params ) {
1143 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1144 if ( $dir === null ) {
1145 return self::EXISTENCE_ERROR; // invalid storage path
1146 }
1147 if ( $shard !== null ) {
1148 // File listing is confined to a single container/shard
1149 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1150 } else {
1151 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1152 // File listing spans multiple containers/shards
1153 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1154
1155 return new FileBackendStoreShardDirIterator( $this,
1156 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1157 }
1158 }
1159
1170 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1171
1172 final public function getFileList( array $params ) {
1173 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1174 if ( $dir === null ) {
1175 return self::LIST_ERROR; // invalid storage path
1176 }
1177 if ( $shard !== null ) {
1178 // File listing is confined to a single container/shard
1179 return $this->getFileListInternal( $fullCont, $dir, $params );
1180 } else {
1181 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1182 // File listing spans multiple containers/shards
1183 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1184
1185 return new FileBackendStoreShardFileIterator( $this,
1186 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1187 }
1188 }
1189
1200 abstract public function getFileListInternal( $container, $dir, array $params );
1201
1213 final public function getOperationsInternal( array $ops ) {
1214 $supportedOps = [
1215 'store' => StoreFileOp::class,
1216 'copy' => CopyFileOp::class,
1217 'move' => MoveFileOp::class,
1218 'delete' => DeleteFileOp::class,
1219 'create' => CreateFileOp::class,
1220 'describe' => DescribeFileOp::class,
1221 'null' => NullFileOp::class
1222 ];
1223
1224 $performOps = []; // array of FileOp objects
1225 // Build up ordered array of FileOps...
1226 foreach ( $ops as $operation ) {
1227 $opName = $operation['op'];
1228 if ( isset( $supportedOps[$opName] ) ) {
1229 $class = $supportedOps[$opName];
1230 // Get params for this operation
1231 $params = $operation;
1232 // Append the FileOp class
1233 $performOps[] = new $class( $this, $params, $this->logger );
1234 } else {
1235 throw new FileBackendError( "Operation '$opName' is not supported." );
1236 }
1237 }
1238
1239 return $performOps;
1240 }
1241
1252 final public function getPathsToLockForOpsInternal( array $performOps ) {
1253 // Build up a list of files to lock...
1254 $paths = [ 'sh' => [], 'ex' => [] ];
1255 foreach ( $performOps as $fileOp ) {
1256 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1257 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1258 }
1259 // Optimization: if doing an EX lock anyway, don't also set an SH one
1260 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1261 // Get a shared lock on the parent directory of each path changed
1262 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1263
1264 return [
1265 LockManager::LOCK_UW => $paths['sh'],
1266 LockManager::LOCK_EX => $paths['ex']
1267 ];
1268 }
1269
1270 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1271 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1272
1273 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1274 }
1275
1276 final protected function doOperationsInternal( array $ops, array $opts ) {
1278 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1279 $status = $this->newStatus();
1280
1281 // Fix up custom header name/value pairs
1282 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1283 // Build up a list of FileOps and involved paths
1284 $fileOps = $this->getOperationsInternal( $ops );
1285 $pathsUsed = [];
1286 foreach ( $fileOps as $fileOp ) {
1287 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1288 }
1289
1290 // Acquire any locks as needed for the scope of this function
1291 if ( empty( $opts['nonLocking'] ) ) {
1292 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1294 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1295 if ( !$status->isOK() ) {
1296 return $status; // abort
1297 }
1298 }
1299
1300 // Clear any file cache entries (after locks acquired)
1301 if ( empty( $opts['preserveCache'] ) ) {
1302 $this->clearCache( $pathsUsed );
1303 }
1304
1305 // Enlarge the cache to fit the stat entries of these files
1306 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1307
1308 // Load from the persistent container caches
1309 $this->primeContainerCache( $pathsUsed );
1310 // Get the latest stat info for all the files (having locked them)
1311 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1312
1313 if ( $ok ) {
1314 // Actually attempt the operation batch...
1315 $opts = $this->setConcurrencyFlags( $opts );
1316 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1317 } else {
1318 // If we could not even stat some files, then bail out
1319 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1320 foreach ( $ops as $i => $op ) { // mark each op as failed
1321 $subStatus->success[$i] = false;
1322 ++$subStatus->failCount;
1323 }
1324 $this->logger->error( static::class . "-{$this->name} " .
1325 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1326 }
1327
1328 // Merge errors into StatusValue fields
1329 $status->merge( $subStatus );
1330 $status->success = $subStatus->success; // not done in merge()
1331
1332 // Shrink the stat cache back to normal size
1333 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1334
1335 return $status;
1336 }
1337
1338 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1340 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1341 $status = $this->newStatus();
1342
1343 // Fix up custom header name/value pairs
1344 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1345 // Build up a list of FileOps and involved paths
1346 $fileOps = $this->getOperationsInternal( $ops );
1347 $pathsUsed = [];
1348 foreach ( $fileOps as $fileOp ) {
1349 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1350 }
1351
1352 // Clear any file cache entries for involved paths
1353 $this->clearCache( $pathsUsed );
1354
1355 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1356 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1357 $maxConcurrency = $this->concurrency; // throttle
1359 $statuses = []; // array of (index => StatusValue)
1361 $batch = [];
1362 foreach ( $fileOps as $index => $fileOp ) {
1363 $subStatus = $async
1364 ? $fileOp->attemptAsyncQuick()
1365 : $fileOp->attemptQuick();
1366 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1367 if ( count( $batch ) >= $maxConcurrency ) {
1368 // Execute this batch. Don't queue any more ops since they contain
1369 // open filehandles which are a limited resource (T230245).
1370 $statuses += $this->executeOpHandlesInternal( $batch );
1371 $batch = [];
1372 }
1373 $batch[$index] = $subStatus->value; // keep index
1374 } else { // error or completed
1375 $statuses[$index] = $subStatus; // keep index
1376 }
1377 }
1378 if ( count( $batch ) ) {
1379 $statuses += $this->executeOpHandlesInternal( $batch );
1380 }
1381 // Marshall and merge all the responses...
1382 foreach ( $statuses as $index => $subStatus ) {
1383 $status->merge( $subStatus );
1384 if ( $subStatus->isOK() ) {
1385 $status->success[$index] = true;
1386 ++$status->successCount;
1387 } else {
1388 $status->success[$index] = false;
1389 ++$status->failCount;
1390 }
1391 }
1392
1393 $this->clearCache( $pathsUsed );
1394
1395 return $status;
1396 }
1397
1407 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1409 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1410
1411 foreach ( $fileOpHandles as $fileOpHandle ) {
1412 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1413 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1414 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1415 throw new InvalidArgumentException( "Expected handle for this file backend." );
1416 }
1417 }
1418
1419 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1420 foreach ( $fileOpHandles as $fileOpHandle ) {
1421 $fileOpHandle->closeResources();
1422 }
1423
1424 return $statuses;
1425 }
1426
1436 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1437 if ( count( $fileOpHandles ) ) {
1438 throw new FileBackendError( "Backend does not support asynchronous operations." );
1439 }
1440
1441 return [];
1442 }
1443
1455 protected function sanitizeOpHeaders( array $op ) {
1456 static $longs = [ 'content-disposition' ];
1457
1458 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1459 $newHeaders = [];
1460 foreach ( $op['headers'] as $name => $value ) {
1461 $name = strtolower( $name );
1462 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1463 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1464 $this->logger->error( "Header '{header}' is too long.", [
1465 'filebackend' => $this->name,
1466 'header' => "$name: $value",
1467 ] );
1468 } else {
1469 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1470 }
1471 }
1472 $op['headers'] = $newHeaders;
1473 }
1474
1475 return $op;
1476 }
1477
1478 final public function preloadCache( array $paths ) {
1479 $fullConts = []; // full container names
1480 foreach ( $paths as $path ) {
1481 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1482 $fullConts[] = $fullCont;
1483 }
1484 // Load from the persistent file and container caches
1485 $this->primeContainerCache( $fullConts );
1486 $this->primeFileCache( $paths );
1487 }
1488
1489 final public function clearCache( array $paths = null ) {
1490 if ( is_array( $paths ) ) {
1491 $paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
1492 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1493 }
1494 if ( $paths === null ) {
1495 $this->cheapCache->clear();
1496 $this->expensiveCache->clear();
1497 } else {
1498 foreach ( $paths as $path ) {
1499 $this->cheapCache->clear( $path );
1500 $this->expensiveCache->clear( $path );
1501 }
1502 }
1503 $this->doClearCache( $paths );
1504 }
1505
1514 protected function doClearCache( array $paths = null ) {
1515 }
1516
1517 final public function preloadFileStat( array $params ) {
1519 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1520
1521 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1522 $stats = $this->doGetFileStatMulti( $params );
1523 if ( $stats === null ) {
1524 return true; // not supported
1525 }
1526
1527 // Whether this queried the backend in high consistency mode
1528 $latest = !empty( $params['latest'] );
1529
1530 return $this->ingestFreshFileStats( $stats, $latest );
1531 }
1532
1546 protected function doGetFileStatMulti( array $params ) {
1547 return null; // not supported
1548 }
1549
1557 abstract protected function directoriesAreVirtual();
1558
1569 final protected static function isValidShortContainerName( $container ) {
1570 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1571 // might be used by subclasses. Reserve the dot character.
1572 // The only way dots end up in containers (e.g. resolveStoragePath)
1573 // is due to the wikiId container prefix or the above suffixes.
1574 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1575 }
1576
1586 final protected static function isValidContainerName( $container ) {
1587 // This accounts for NTFS, Swift, and Ceph restrictions
1588 // and disallows directory separators or traversal characters.
1589 // Note that matching strings URL encode to the same string;
1590 // in Swift/Ceph, the length restriction is *after* URL encoding.
1591 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1592 }
1593
1607 final protected function resolveStoragePath( $storagePath ) {
1608 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1609 if ( $backend === $this->name ) { // must be for this backend
1610 $relPath = self::normalizeContainerPath( $relPath );
1611 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1612 // Get shard for the normalized path if this container is sharded
1613 $cShard = $this->getContainerShard( $shortCont, $relPath );
1614 // Validate and sanitize the relative path (backend-specific)
1615 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1616 if ( $relPath !== null ) {
1617 // Prepend any domain ID prefix to the container name
1618 $container = $this->fullContainerName( $shortCont );
1619 if ( self::isValidContainerName( $container ) ) {
1620 // Validate and sanitize the container name (backend-specific)
1621 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1622 if ( $container !== null ) {
1623 return [ $container, $relPath, $cShard ];
1624 }
1625 }
1626 }
1627 }
1628 }
1629
1630 return [ null, null, null ];
1631 }
1632
1648 final protected function resolveStoragePathReal( $storagePath ) {
1649 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1650 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1651 return [ $container, $relPath ];
1652 }
1653
1654 return [ null, null ];
1655 }
1656
1665 final protected function getContainerShard( $container, $relPath ) {
1666 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1667 if ( $levels == 1 || $levels == 2 ) {
1668 // Hash characters are either base 16 or 36
1669 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1670 // Get a regex that represents the shard portion of paths.
1671 // The concatenation of the captures gives us the shard.
1672 if ( $levels === 1 ) { // 16 or 36 shards per container
1673 $hashDirRegex = '(' . $char . ')';
1674 } else { // 256 or 1296 shards per container
1675 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1676 $hashDirRegex = $char . '/(' . $char . '{2})';
1677 } else { // short hash dir format (e.g. "a/b/c")
1678 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1679 }
1680 }
1681 // Allow certain directories to be above the hash dirs so as
1682 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1683 // They must be 2+ chars to avoid any hash directory ambiguity.
1684 $m = [];
1685 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1686 return '.' . implode( '', array_slice( $m, 1 ) );
1687 }
1688
1689 return null; // failed to match
1690 }
1691
1692 return ''; // no sharding
1693 }
1694
1703 final public function isSingleShardPathInternal( $storagePath ) {
1704 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1705
1706 return ( $shard !== null );
1707 }
1708
1717 final protected function getContainerHashLevels( $container ) {
1718 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1719 $config = $this->shardViaHashLevels[$container];
1720 $hashLevels = (int)$config['levels'];
1721 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1722 $hashBase = (int)$config['base'];
1723 if ( $hashBase == 16 || $hashBase == 36 ) {
1724 return [ $hashLevels, $hashBase, $config['repeat'] ];
1725 }
1726 }
1727 }
1728
1729 return [ 0, 0, false ]; // no sharding
1730 }
1731
1738 final protected function getContainerSuffixes( $container ) {
1739 $shards = [];
1740 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1741 if ( $digits > 0 ) {
1742 $numShards = $base ** $digits;
1743 for ( $index = 0; $index < $numShards; $index++ ) {
1744 $shards[] = '.' . \Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1745 }
1746 }
1747
1748 return $shards;
1749 }
1750
1757 final protected function fullContainerName( $container ) {
1758 if ( $this->domainId != '' ) {
1759 return "{$this->domainId}-$container";
1760 } else {
1761 return $container;
1762 }
1763 }
1764
1774 protected function resolveContainerName( $container ) {
1775 return $container;
1776 }
1777
1789 protected function resolveContainerPath( $container, $relStoragePath ) {
1790 return $relStoragePath;
1791 }
1792
1799 private function containerCacheKey( $container ) {
1800 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1801 }
1802
1809 final protected function setContainerCache( $container, array $val ) {
1810 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1811 $this->logger->warning( "Unable to set stat cache for container {container}.",
1812 [ 'filebackend' => $this->name, 'container' => $container ]
1813 );
1814 }
1815 }
1816
1823 final protected function deleteContainerCache( $container ) {
1824 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1825 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1826 [ 'filebackend' => $this->name, 'container' => $container ]
1827 );
1828 }
1829 }
1830
1838 final protected function primeContainerCache( array $items ) {
1840 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1841
1842 $paths = []; // list of storage paths
1843 $contNames = []; // (cache key => resolved container name)
1844 // Get all the paths/containers from the items...
1845 foreach ( $items as $item ) {
1846 if ( self::isStoragePath( $item ) ) {
1847 $paths[] = $item;
1848 } elseif ( is_string( $item ) ) { // full container name
1849 $contNames[$this->containerCacheKey( $item )] = $item;
1850 }
1851 }
1852 // Get all the corresponding cache keys for paths...
1853 foreach ( $paths as $path ) {
1854 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1855 if ( $fullCont !== null ) { // valid path for this backend
1856 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1857 }
1858 }
1859
1860 $contInfo = []; // (resolved container name => cache value)
1861 // Get all cache entries for these container cache keys...
1862 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1863 foreach ( $values as $cacheKey => $val ) {
1864 $contInfo[$contNames[$cacheKey]] = $val;
1865 }
1866
1867 // Populate the container process cache for the backend...
1868 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1869 }
1870
1879 protected function doPrimeContainerCache( array $containerInfo ) {
1880 }
1881
1888 private function fileCacheKey( $path ) {
1889 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1890 }
1891
1900 final protected function setFileCache( $path, array $val ) {
1902 if ( $path === null ) {
1903 return; // invalid storage path
1904 }
1905 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1906 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1907 $key = $this->fileCacheKey( $path );
1908 // Set the cache unless it is currently salted.
1909 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1910 $this->logger->warning( "Unable to set stat cache for file {path}.",
1911 [ 'filebackend' => $this->name, 'path' => $path ]
1912 );
1913 }
1914 }
1915
1924 final protected function deleteFileCache( $path ) {
1926 if ( $path === null ) {
1927 return; // invalid storage path
1928 }
1929 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1930 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1931 [ 'filebackend' => $this->name, 'path' => $path ]
1932 );
1933 }
1934 }
1935
1943 final protected function primeFileCache( array $items ) {
1945 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1946
1947 $paths = []; // list of storage paths
1948 $pathNames = []; // (cache key => storage path)
1949 // Get all the paths/containers from the items...
1950 foreach ( $items as $item ) {
1951 if ( self::isStoragePath( $item ) ) {
1953 if ( $path !== null ) {
1954 $paths[] = $path;
1955 }
1956 }
1957 }
1958 // Get all the corresponding cache keys for paths...
1959 foreach ( $paths as $path ) {
1960 [ , $rel, ] = $this->resolveStoragePath( $path );
1961 if ( $rel !== null ) { // valid path for this backend
1962 $pathNames[$this->fileCacheKey( $path )] = $path;
1963 }
1964 }
1965 // Get all cache entries for these file cache keys.
1966 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1967 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1968 // Load all of the results into process cache...
1969 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1970 $path = $pathNames[$cacheKey];
1971 // This flag only applies to stat info loaded directly
1972 // from a high consistency backend query to the process cache
1973 unset( $stat['latest'] );
1974
1975 $this->cheapCache->setField( $path, 'stat', $stat );
1976 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1977 // Some backends store SHA-1 as metadata
1978 $this->cheapCache->setField(
1979 $path,
1980 'sha1',
1981 [ 'hash' => $stat['sha1'], 'latest' => false ]
1982 );
1983 }
1984 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1985 // Some backends store custom headers/metadata
1986 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1987 $this->cheapCache->setField(
1988 $path,
1989 'xattr',
1990 [ 'map' => $stat['xattr'], 'latest' => false ]
1991 );
1992 }
1993 }
1994 }
1995
2003 final protected static function normalizeXAttributes( array $xattr ) {
2004 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
2005
2006 foreach ( $xattr['headers'] as $name => $value ) {
2007 $newXAttr['headers'][strtolower( $name )] = $value;
2008 }
2009
2010 foreach ( $xattr['metadata'] as $name => $value ) {
2011 $newXAttr['metadata'][strtolower( $name )] = $value;
2012 }
2013
2014 return $newXAttr;
2015 }
2016
2023 final protected function setConcurrencyFlags( array $opts ) {
2024 $opts['concurrency'] = 1; // off
2025 if ( $this->parallelize === 'implicit' ) {
2026 if ( $opts['parallelize'] ?? true ) {
2027 $opts['concurrency'] = $this->concurrency;
2028 }
2029 } elseif ( $this->parallelize === 'explicit' ) {
2030 if ( !empty( $opts['parallelize'] ) ) {
2031 $opts['concurrency'] = $this->concurrency;
2032 }
2033 }
2034
2035 return $opts;
2036 }
2037
2047 protected function getContentType( $storagePath, $content, $fsPath ) {
2048 if ( $this->mimeCallback ) {
2049 return call_user_func_array( $this->mimeCallback, func_get_args() );
2050 }
2051
2052 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2053 return $mime ?: 'unknown/unknown';
2054 }
2055}
2056
2058class_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.
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
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...
int $maxFileSize
Size in bytes, defaults to 32 GiB.
doPrepare(array $params)
FileBackend::prepare() StatusValue Good status without value for success, fatal otherwise.
doClearCache(array $paths=null)
Clears any additional stat caches for storage paths.
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.
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.
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.