MediaWiki master
FileBackendStore.php
Go to the documentation of this file.
1<?php
25use Wikimedia\AtEase\AtEase;
29use Wikimedia\Timestamp\ConvertibleTimestamp;
30
45abstract class FileBackendStore extends FileBackend {
47 protected $memCache;
49 protected $srvCache;
51 protected $cheapCache;
53 protected $expensiveCache;
54
56 protected $shardViaHashLevels = [];
57
59 protected $mimeCallback;
60
61 protected $maxFileSize = 32 * 1024 * 1024 * 1024; // integer bytes (32GiB)
62
63 protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
64 protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
65 protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
66
68 protected const RES_ABSENT = false;
70 protected const RES_ERROR = null;
71
73 protected const ABSENT_NORMAL = 'FNE-N';
75 protected const ABSENT_LATEST = 'FNE-L';
76
90 public function __construct( array $config ) {
91 parent::__construct( $config );
92 $this->mimeCallback = $config['mimeCallback'] ?? null;
93 $this->srvCache = new EmptyBagOStuff(); // disabled by default
94 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
95 $this->cheapCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
96 $this->expensiveCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
97 }
98
106 final public function maxFileSizeInternal() {
107 return min( $this->maxFileSize, PHP_INT_MAX );
108 }
109
120 abstract public function isPathUsableInternal( $storagePath );
121
140 final public function createInternal( array $params ) {
142 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
143
144 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
145 $status = $this->newStatus( 'backend-fail-maxsize',
146 $params['dst'], $this->maxFileSizeInternal() );
147 } else {
148 $status = $this->doCreateInternal( $params );
149 $this->clearCache( [ $params['dst'] ] );
150 if ( $params['dstExists'] ?? true ) {
151 $this->deleteFileCache( $params['dst'] ); // persistent cache
152 }
153 }
154
155 return $status;
156 }
157
163 abstract protected function doCreateInternal( array $params );
164
183 final public function storeInternal( array $params ) {
185 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
186
187 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
188 $status = $this->newStatus( 'backend-fail-maxsize',
189 $params['dst'], $this->maxFileSizeInternal() );
190 } else {
191 $status = $this->doStoreInternal( $params );
192 $this->clearCache( [ $params['dst'] ] );
193 if ( $params['dstExists'] ?? true ) {
194 $this->deleteFileCache( $params['dst'] ); // persistent cache
195 }
196 }
197
198 return $status;
199 }
200
206 abstract protected function doStoreInternal( array $params );
207
227 final public function copyInternal( array $params ) {
229 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
230
231 $status = $this->doCopyInternal( $params );
232 $this->clearCache( [ $params['dst'] ] );
233 if ( $params['dstExists'] ?? true ) {
234 $this->deleteFileCache( $params['dst'] ); // persistent cache
235 }
236
237 return $status;
238 }
239
245 abstract protected function doCopyInternal( array $params );
246
261 final public function deleteInternal( array $params ) {
263 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
264
265 $status = $this->doDeleteInternal( $params );
266 $this->clearCache( [ $params['src'] ] );
267 $this->deleteFileCache( $params['src'] ); // persistent cache
268 return $status;
269 }
270
276 abstract protected function doDeleteInternal( array $params );
277
297 final public function moveInternal( array $params ) {
299 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
300
301 $status = $this->doMoveInternal( $params );
302 $this->clearCache( [ $params['src'], $params['dst'] ] );
303 $this->deleteFileCache( $params['src'] ); // persistent cache
304 if ( $params['dstExists'] ?? true ) {
305 $this->deleteFileCache( $params['dst'] ); // persistent cache
306 }
307
308 return $status;
309 }
310
316 abstract protected function doMoveInternal( array $params );
317
332 final public function describeInternal( array $params ) {
334 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
335
336 if ( count( $params['headers'] ) ) {
337 $status = $this->doDescribeInternal( $params );
338 $this->clearCache( [ $params['src'] ] );
339 $this->deleteFileCache( $params['src'] ); // persistent cache
340 } else {
341 $status = $this->newStatus(); // nothing to do
342 }
343
344 return $status;
345 }
346
353 protected function doDescribeInternal( array $params ) {
354 return $this->newStatus();
355 }
356
364 final public function nullInternal( array $params ) {
365 return $this->newStatus();
366 }
367
368 final public function concatenate( array $params ) {
370 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
371 $status = $this->newStatus();
372
373 // Try to lock the source files for the scope of this function
375 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
376 if ( $status->isOK() ) {
377 // Actually do the file concatenation...
378 $start_time = microtime( true );
379 $status->merge( $this->doConcatenate( $params ) );
380 $sec = microtime( true ) - $start_time;
381 if ( !$status->isOK() ) {
382 $this->logger->error( static::class . "-{$this->name}" .
383 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
384 }
385 }
386
387 return $status;
388 }
389
396 protected function doConcatenate( array $params ) {
397 $status = $this->newStatus();
398 $tmpPath = $params['dst'];
399 unset( $params['latest'] );
400
401 // Check that the specified temp file is valid...
402 AtEase::suppressWarnings();
403 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
404 AtEase::restoreWarnings();
405 if ( !$ok ) { // not present or not empty
406 $status->fatal( 'backend-fail-opentemp', $tmpPath );
407
408 return $status;
409 }
410
411 // Get local FS versions of the chunks needed for the concatenation...
412 $fsFiles = $this->getLocalReferenceMulti( $params );
413 foreach ( $fsFiles as $path => &$fsFile ) {
414 if ( !$fsFile ) { // chunk failed to download?
415 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
416 if ( !$fsFile ) { // retry failed?
417 $status->fatal(
418 $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
419 $path
420 );
421
422 return $status;
423 }
424 }
425 }
426 unset( $fsFile ); // unset reference so we can reuse $fsFile
427
428 // Get a handle for the destination temp file
429 $tmpHandle = fopen( $tmpPath, 'ab' );
430 if ( $tmpHandle === false ) {
431 $status->fatal( 'backend-fail-opentemp', $tmpPath );
432
433 return $status;
434 }
435
436 // Build up the temp file using the source chunks (in order)...
437 foreach ( $fsFiles as $virtualSource => $fsFile ) {
438 // Get a handle to the local FS version
439 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
440 if ( $sourceHandle === false ) {
441 fclose( $tmpHandle );
442 $status->fatal( 'backend-fail-read', $virtualSource );
443
444 return $status;
445 }
446 // Append chunk to file (pass chunk size to avoid magic quotes)
447 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
448 fclose( $sourceHandle );
449 fclose( $tmpHandle );
450 $status->fatal( 'backend-fail-writetemp', $tmpPath );
451
452 return $status;
453 }
454 fclose( $sourceHandle );
455 }
456 if ( !fclose( $tmpHandle ) ) {
457 $status->fatal( 'backend-fail-closetemp', $tmpPath );
458
459 return $status;
460 }
461
462 clearstatcache(); // temp file changed
463
464 return $status;
465 }
466
470 final protected function doPrepare( array $params ) {
472 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
473 $status = $this->newStatus();
474
475 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
476 if ( $dir === null ) {
477 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
478
479 return $status; // invalid storage path
480 }
481
482 if ( $shard !== null ) { // confined to a single container/shard
483 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
484 } else { // directory is on several shards
485 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
486 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
487 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
488 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
489 }
490 }
491
492 return $status;
493 }
494
503 protected function doPrepareInternal( $container, $dir, array $params ) {
504 return $this->newStatus();
505 }
506
507 final protected function doSecure( array $params ) {
509 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
510 $status = $this->newStatus();
511
512 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
513 if ( $dir === null ) {
514 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
515
516 return $status; // invalid storage path
517 }
518
519 if ( $shard !== null ) { // confined to a single container/shard
520 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
521 } else { // directory is on several shards
522 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
523 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
524 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
525 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
526 }
527 }
528
529 return $status;
530 }
531
540 protected function doSecureInternal( $container, $dir, array $params ) {
541 return $this->newStatus();
542 }
543
544 final protected function doPublish( array $params ) {
546 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
547 $status = $this->newStatus();
548
549 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
550 if ( $dir === null ) {
551 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
552
553 return $status; // invalid storage path
554 }
555
556 if ( $shard !== null ) { // confined to a single container/shard
557 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
558 } else { // directory is on several shards
559 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
560 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
561 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
562 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
563 }
564 }
565
566 return $status;
567 }
568
577 protected function doPublishInternal( $container, $dir, array $params ) {
578 return $this->newStatus();
579 }
580
581 final protected function doClean( array $params ) {
583 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
584 $status = $this->newStatus();
585
586 // Recursive: first delete all empty subdirs recursively
587 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
588 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
589 if ( $subDirsRel !== null ) { // no errors
590 foreach ( $subDirsRel as $subDirRel ) {
591 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
592 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
593 }
594 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
595 }
596 }
597
598 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
599 if ( $dir === null ) {
600 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
601
602 return $status; // invalid storage path
603 }
604
605 // Attempt to lock this directory...
606 $filesLockEx = [ $params['dir'] ];
608 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
609 if ( !$status->isOK() ) {
610 return $status; // abort
611 }
612
613 if ( $shard !== null ) { // confined to a single container/shard
614 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
615 $this->deleteContainerCache( $fullCont ); // purge cache
616 } else { // directory is on several shards
617 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
618 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
619 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
620 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
621 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
622 }
623 }
624
625 return $status;
626 }
627
636 protected function doCleanInternal( $container, $dir, array $params ) {
637 return $this->newStatus();
638 }
639
640 final public function fileExists( array $params ) {
642 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
643
644 $stat = $this->getFileStat( $params );
645 if ( is_array( $stat ) ) {
646 return true;
647 }
648
649 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
650 }
651
652 final public function getFileTimestamp( array $params ) {
654 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
655
656 $stat = $this->getFileStat( $params );
657 if ( is_array( $stat ) ) {
658 return $stat['mtime'];
659 }
660
661 return self::TIMESTAMP_FAIL; // all failure cases
662 }
663
664 final public function getFileSize( array $params ) {
666 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
667
668 $stat = $this->getFileStat( $params );
669 if ( is_array( $stat ) ) {
670 return $stat['size'];
671 }
672
673 return self::SIZE_FAIL; // all failure cases
674 }
675
676 final public function getFileStat( array $params ) {
678 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
679
681 if ( $path === null ) {
682 return self::STAT_ERROR; // invalid storage path
683 }
684
685 // Whether to bypass cache except for process cache entries loaded directly from
686 // high consistency backend queries (caller handles any cache flushing and locking)
687 $latest = !empty( $params['latest'] );
688 // Whether to ignore cache entries missing the SHA-1 field for existing files
689 $requireSHA1 = !empty( $params['requireSHA1'] );
690
691 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
692 // Load the persistent stat cache into process cache if needed
693 if ( !$latest ) {
694 if (
695 // File stat is not in process cache
696 $stat === null ||
697 // Key/value store backends might opportunistically set file stat process
698 // cache entries from object listings that do not include the SHA-1. In that
699 // case, loading the persistent stat cache will likely yield the SHA-1.
700 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
701 ) {
702 $this->primeFileCache( [ $path ] );
703 // Get any newly process-cached entry
704 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
705 }
706 }
707
708 if ( is_array( $stat ) ) {
709 if (
710 ( !$latest || !empty( $stat['latest'] ) ) &&
711 ( !$requireSHA1 || isset( $stat['sha1'] ) )
712 ) {
713 return $stat;
714 }
715 } elseif ( $stat === self::ABSENT_LATEST ) {
716 return self::STAT_ABSENT;
717 } elseif ( $stat === self::ABSENT_NORMAL ) {
718 if ( !$latest ) {
719 return self::STAT_ABSENT;
720 }
721 }
722
723 // Load the file stat from the backend and update caches
724 $stat = $this->doGetFileStat( $params );
725 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
726
727 if ( is_array( $stat ) ) {
728 return $stat;
729 }
730
731 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
732 }
733
741 final protected function ingestFreshFileStats( array $stats, $latest ) {
742 $success = true;
743
744 foreach ( $stats as $path => $stat ) {
745 if ( is_array( $stat ) ) {
746 // Strongly consistent backends might automatically set this flag
747 $stat['latest'] ??= $latest;
748
749 $this->cheapCache->setField( $path, 'stat', $stat );
750 if ( isset( $stat['sha1'] ) ) {
751 // Some backends store the SHA-1 hash as metadata
752 $this->cheapCache->setField(
753 $path,
754 'sha1',
755 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
756 );
757 }
758 if ( isset( $stat['xattr'] ) ) {
759 // Some backends store custom headers/metadata
760 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
761 $this->cheapCache->setField(
762 $path,
763 'xattr',
764 [ 'map' => $stat['xattr'], 'latest' => $latest ]
765 );
766 }
767 // Update persistent cache (@TODO: set all entries in one batch)
768 $this->setFileCache( $path, $stat );
769 } elseif ( $stat === self::RES_ABSENT ) {
770 $this->cheapCache->setField(
771 $path,
772 'stat',
773 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
774 );
775 $this->cheapCache->setField(
776 $path,
777 'xattr',
778 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
779 );
780 $this->cheapCache->setField(
781 $path,
782 'sha1',
783 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
784 );
785 $this->logger->debug(
786 __METHOD__ . ': File {path} does not exist',
787 [ 'path' => $path ]
788 );
789 } else {
790 $success = false;
791 $this->logger->error(
792 __METHOD__ . ': Could not stat file {path}',
793 [ 'path' => $path ]
794 );
795 }
796 }
797
798 return $success;
799 }
800
806 abstract protected function doGetFileStat( array $params );
807
808 public function getFileContentsMulti( array $params ) {
810 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
811
812 $params = $this->setConcurrencyFlags( $params );
813 $contents = $this->doGetFileContentsMulti( $params );
814 foreach ( $contents as $path => $content ) {
815 if ( !is_string( $content ) ) {
816 $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
817 }
818 }
819
820 return $contents;
821 }
822
829 protected function doGetFileContentsMulti( array $params ) {
830 $contents = [];
831 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
832 if ( $fsFile instanceof FSFile ) {
833 AtEase::suppressWarnings();
834 $content = file_get_contents( $fsFile->getPath() );
835 AtEase::restoreWarnings();
836 $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
837 } else {
838 // self::RES_ERROR or self::RES_ABSENT
839 $contents[$path] = $fsFile;
840 }
841 }
842
843 return $contents;
844 }
845
846 final public function getFileXAttributes( array $params ) {
848 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
849
851 if ( $path === null ) {
852 return self::XATTRS_FAIL; // invalid storage path
853 }
854 $latest = !empty( $params['latest'] ); // use latest data?
855 if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
856 $stat = $this->cheapCache->getField( $path, 'xattr' );
857 // If we want the latest data, check that this cached
858 // value was in fact fetched with the latest available data.
859 if ( !$latest || $stat['latest'] ) {
860 return $stat['map'];
861 }
862 }
863 $fields = $this->doGetFileXAttributes( $params );
864 if ( is_array( $fields ) ) {
865 $fields = self::normalizeXAttributes( $fields );
866 $this->cheapCache->setField(
867 $path,
868 'xattr',
869 [ 'map' => $fields, 'latest' => $latest ]
870 );
871 } elseif ( $fields === self::RES_ABSENT ) {
872 $this->cheapCache->setField(
873 $path,
874 'xattr',
875 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
876 );
877 } else {
878 $fields = self::XATTRS_FAIL; // used for all failure cases
879 }
880
881 return $fields;
882 }
883
890 protected function doGetFileXAttributes( array $params ) {
891 return [ 'headers' => [], 'metadata' => [] ]; // not supported
892 }
893
894 final public function getFileSha1Base36( array $params ) {
896 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
897
899 if ( $path === null ) {
900 return self::SHA1_FAIL; // invalid storage path
901 }
902 $latest = !empty( $params['latest'] ); // use latest data?
903 if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
904 $stat = $this->cheapCache->getField( $path, 'sha1' );
905 // If we want the latest data, check that this cached
906 // value was in fact fetched with the latest available data.
907 if ( !$latest || $stat['latest'] ) {
908 return $stat['hash'];
909 }
910 }
911 $sha1 = $this->doGetFileSha1Base36( $params );
912 if ( is_string( $sha1 ) ) {
913 $this->cheapCache->setField(
914 $path,
915 'sha1',
916 [ 'hash' => $sha1, 'latest' => $latest ]
917 );
918 } elseif ( $sha1 === self::RES_ABSENT ) {
919 $this->cheapCache->setField(
920 $path,
921 'sha1',
922 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
923 );
924 } else {
925 $sha1 = self::SHA1_FAIL; // used for all failure cases
926 }
927
928 return $sha1;
929 }
930
937 protected function doGetFileSha1Base36( array $params ) {
938 $fsFile = $this->getLocalReference( $params );
939 if ( $fsFile instanceof FSFile ) {
940 $sha1 = $fsFile->getSha1Base36();
941
942 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
943 }
944
945 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
946 }
947
948 final public function getFileProps( array $params ) {
950 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
951
952 $fsFile = $this->getLocalReference( $params );
953
954 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
955 }
956
957 final public function getLocalReferenceMulti( array $params ) {
959 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
960
961 $params = $this->setConcurrencyFlags( $params );
962
963 $fsFiles = []; // (path => FSFile)
964 $latest = !empty( $params['latest'] ); // use latest data?
965 // Reuse any files already in process cache...
966 foreach ( $params['srcs'] as $src ) {
968 if ( $path === null ) {
969 $fsFiles[$src] = self::RES_ERROR; // invalid storage path
970 } elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
971 $val = $this->expensiveCache->getField( $path, 'localRef' );
972 // If we want the latest data, check that this cached
973 // value was in fact fetched with the latest available data.
974 if ( !$latest || $val['latest'] ) {
975 $fsFiles[$src] = $val['object'];
976 }
977 }
978 }
979 // Fetch local references of any remaining files...
980 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
981 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
982 if ( $fsFile instanceof FSFile ) {
983 $fsFiles[$path] = $fsFile;
984 $this->expensiveCache->setField(
985 $path,
986 'localRef',
987 [ 'object' => $fsFile, 'latest' => $latest ]
988 );
989 } else {
990 // self::RES_ERROR or self::RES_ABSENT
991 $fsFiles[$path] = $fsFile;
992 }
993 }
994
995 return $fsFiles;
996 }
997
1004 protected function doGetLocalReferenceMulti( array $params ) {
1005 return $this->doGetLocalCopyMulti( $params );
1006 }
1007
1008 final public function getLocalCopyMulti( array $params ) {
1010 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1011
1012 $params = $this->setConcurrencyFlags( $params );
1013
1014 return $this->doGetLocalCopyMulti( $params );
1015 }
1016
1022 abstract protected function doGetLocalCopyMulti( array $params );
1023
1030 public function getFileHttpUrl( array $params ) {
1031 return self::TEMPURL_ERROR; // not supported
1032 }
1033
1034 final public function streamFile( array $params ) {
1036 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1037 $status = $this->newStatus();
1038
1039 // Always set some fields for subclass convenience
1040 $params['options'] ??= [];
1041 $params['headers'] ??= [];
1042
1043 // Don't stream it out as text/html if there was a PHP error
1044 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
1045 print "Headers already sent, terminating.\n";
1046 $status->fatal( 'backend-fail-stream', $params['src'] );
1047 return $status;
1048 }
1049
1050 $status->merge( $this->doStreamFile( $params ) );
1051
1052 return $status;
1053 }
1054
1061 protected function doStreamFile( array $params ) {
1062 $status = $this->newStatus();
1063
1064 $flags = 0;
1065 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1066 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1067
1068 $fsFile = $this->getLocalReference( $params );
1069 if ( $fsFile ) {
1070 $streamer = new HTTPFileStreamer(
1071 $fsFile->getPath(),
1072 $this->getStreamerOptions()
1073 );
1074 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1075 } else {
1076 $res = false;
1077 HTTPFileStreamer::send404Message( $params['src'], $flags );
1078 }
1079
1080 if ( !$res ) {
1081 $status->fatal( 'backend-fail-stream', $params['src'] );
1082 }
1083
1084 return $status;
1085 }
1086
1087 final public function directoryExists( array $params ) {
1088 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1089 if ( $dir === null ) {
1090 return self::EXISTENCE_ERROR; // invalid storage path
1091 }
1092 if ( $shard !== null ) { // confined to a single container/shard
1093 return $this->doDirectoryExists( $fullCont, $dir, $params );
1094 } else { // directory is on several shards
1095 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1096 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1097 $res = false; // response
1098 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1099 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1100 if ( $exists === true ) {
1101 $res = true;
1102 break; // found one!
1103 } elseif ( $exists === self::RES_ERROR ) {
1104 $res = self::EXISTENCE_ERROR;
1105 }
1106 }
1107
1108 return $res;
1109 }
1110 }
1111
1120 abstract protected function doDirectoryExists( $container, $dir, array $params );
1121
1122 final public function getDirectoryList( array $params ) {
1123 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1124 if ( $dir === null ) {
1125 return self::EXISTENCE_ERROR; // invalid storage path
1126 }
1127 if ( $shard !== null ) {
1128 // File listing is confined to a single container/shard
1129 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1130 } else {
1131 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1132 // File listing spans multiple containers/shards
1133 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1134
1135 return new FileBackendStoreShardDirIterator( $this,
1136 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1137 }
1138 }
1139
1150 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1151
1152 final public function getFileList( array $params ) {
1153 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1154 if ( $dir === null ) {
1155 return self::LIST_ERROR; // invalid storage path
1156 }
1157 if ( $shard !== null ) {
1158 // File listing is confined to a single container/shard
1159 return $this->getFileListInternal( $fullCont, $dir, $params );
1160 } else {
1161 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1162 // File listing spans multiple containers/shards
1163 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1164
1165 return new FileBackendStoreShardFileIterator( $this,
1166 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1167 }
1168 }
1169
1180 abstract public function getFileListInternal( $container, $dir, array $params );
1181
1193 final public function getOperationsInternal( array $ops ) {
1194 $supportedOps = [
1195 'store' => StoreFileOp::class,
1196 'copy' => CopyFileOp::class,
1197 'move' => MoveFileOp::class,
1198 'delete' => DeleteFileOp::class,
1199 'create' => CreateFileOp::class,
1200 'describe' => DescribeFileOp::class,
1201 'null' => NullFileOp::class
1202 ];
1203
1204 $performOps = []; // array of FileOp objects
1205 // Build up ordered array of FileOps...
1206 foreach ( $ops as $operation ) {
1207 $opName = $operation['op'];
1208 if ( isset( $supportedOps[$opName] ) ) {
1209 $class = $supportedOps[$opName];
1210 // Get params for this operation
1211 $params = $operation;
1212 // Append the FileOp class
1213 $performOps[] = new $class( $this, $params, $this->logger );
1214 } else {
1215 throw new FileBackendError( "Operation '$opName' is not supported." );
1216 }
1217 }
1218
1219 return $performOps;
1220 }
1221
1232 final public function getPathsToLockForOpsInternal( array $performOps ) {
1233 // Build up a list of files to lock...
1234 $paths = [ 'sh' => [], 'ex' => [] ];
1235 foreach ( $performOps as $fileOp ) {
1236 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1237 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1238 }
1239 // Optimization: if doing an EX lock anyway, don't also set an SH one
1240 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1241 // Get a shared lock on the parent directory of each path changed
1242 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1243
1244 return [
1245 LockManager::LOCK_UW => $paths['sh'],
1246 LockManager::LOCK_EX => $paths['ex']
1247 ];
1248 }
1249
1250 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1251 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1252
1253 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1254 }
1255
1256 final protected function doOperationsInternal( array $ops, array $opts ) {
1258 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1259 $status = $this->newStatus();
1260
1261 // Fix up custom header name/value pairs
1262 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1263 // Build up a list of FileOps and involved paths
1264 $fileOps = $this->getOperationsInternal( $ops );
1265 $pathsUsed = [];
1266 foreach ( $fileOps as $fileOp ) {
1267 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1268 }
1269
1270 // Acquire any locks as needed for the scope of this function
1271 if ( empty( $opts['nonLocking'] ) ) {
1272 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1274 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1275 if ( !$status->isOK() ) {
1276 return $status; // abort
1277 }
1278 }
1279
1280 // Clear any file cache entries (after locks acquired)
1281 if ( empty( $opts['preserveCache'] ) ) {
1282 $this->clearCache( $pathsUsed );
1283 }
1284
1285 // Enlarge the cache to fit the stat entries of these files
1286 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1287
1288 // Load from the persistent container caches
1289 $this->primeContainerCache( $pathsUsed );
1290 // Get the latest stat info for all the files (having locked them)
1291 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1292
1293 if ( $ok ) {
1294 // Actually attempt the operation batch...
1295 $opts = $this->setConcurrencyFlags( $opts );
1296 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1297 } else {
1298 // If we could not even stat some files, then bail out
1299 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1300 foreach ( $ops as $i => $op ) { // mark each op as failed
1301 $subStatus->success[$i] = false;
1302 ++$subStatus->failCount;
1303 }
1304 $this->logger->error( static::class . "-{$this->name} " .
1305 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1306 }
1307
1308 // Merge errors into StatusValue fields
1309 $status->merge( $subStatus );
1310 $status->success = $subStatus->success; // not done in merge()
1311
1312 // Shrink the stat cache back to normal size
1313 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1314
1315 return $status;
1316 }
1317
1318 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1320 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1321 $status = $this->newStatus();
1322
1323 // Fix up custom header name/value pairs
1324 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1325 // Build up a list of FileOps and involved paths
1326 $fileOps = $this->getOperationsInternal( $ops );
1327 $pathsUsed = [];
1328 foreach ( $fileOps as $fileOp ) {
1329 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1330 }
1331
1332 // Clear any file cache entries for involved paths
1333 $this->clearCache( $pathsUsed );
1334
1335 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1336 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1337 $maxConcurrency = $this->concurrency; // throttle
1339 $statuses = []; // array of (index => StatusValue)
1341 $batch = [];
1342 foreach ( $fileOps as $index => $fileOp ) {
1343 $subStatus = $async
1344 ? $fileOp->attemptAsyncQuick()
1345 : $fileOp->attemptQuick();
1346 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1347 if ( count( $batch ) >= $maxConcurrency ) {
1348 // Execute this batch. Don't queue any more ops since they contain
1349 // open filehandles which are a limited resource (T230245).
1350 $statuses += $this->executeOpHandlesInternal( $batch );
1351 $batch = [];
1352 }
1353 $batch[$index] = $subStatus->value; // keep index
1354 } else { // error or completed
1355 $statuses[$index] = $subStatus; // keep index
1356 }
1357 }
1358 if ( count( $batch ) ) {
1359 $statuses += $this->executeOpHandlesInternal( $batch );
1360 }
1361 // Marshall and merge all the responses...
1362 foreach ( $statuses as $index => $subStatus ) {
1363 $status->merge( $subStatus );
1364 if ( $subStatus->isOK() ) {
1365 $status->success[$index] = true;
1366 ++$status->successCount;
1367 } else {
1368 $status->success[$index] = false;
1369 ++$status->failCount;
1370 }
1371 }
1372
1373 $this->clearCache( $pathsUsed );
1374
1375 return $status;
1376 }
1377
1387 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1389 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1390
1391 foreach ( $fileOpHandles as $fileOpHandle ) {
1392 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1393 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1394 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1395 throw new InvalidArgumentException( "Expected handle for this file backend." );
1396 }
1397 }
1398
1399 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1400 foreach ( $fileOpHandles as $fileOpHandle ) {
1401 $fileOpHandle->closeResources();
1402 }
1403
1404 return $statuses;
1405 }
1406
1416 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1417 if ( count( $fileOpHandles ) ) {
1418 throw new FileBackendError( "Backend does not support asynchronous operations." );
1419 }
1420
1421 return [];
1422 }
1423
1435 protected function sanitizeOpHeaders( array $op ) {
1436 static $longs = [ 'content-disposition' ];
1437
1438 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1439 $newHeaders = [];
1440 foreach ( $op['headers'] as $name => $value ) {
1441 $name = strtolower( $name );
1442 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1443 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1444 $this->logger->error( "Header '{header}' is too long.", [
1445 'filebackend' => $this->name,
1446 'header' => "$name: $value",
1447 ] );
1448 } else {
1449 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1450 }
1451 }
1452 $op['headers'] = $newHeaders;
1453 }
1454
1455 return $op;
1456 }
1457
1458 final public function preloadCache( array $paths ) {
1459 $fullConts = []; // full container names
1460 foreach ( $paths as $path ) {
1461 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1462 $fullConts[] = $fullCont;
1463 }
1464 // Load from the persistent file and container caches
1465 $this->primeContainerCache( $fullConts );
1466 $this->primeFileCache( $paths );
1467 }
1468
1469 final public function clearCache( array $paths = null ) {
1470 if ( is_array( $paths ) ) {
1471 $paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
1472 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1473 }
1474 if ( $paths === null ) {
1475 $this->cheapCache->clear();
1476 $this->expensiveCache->clear();
1477 } else {
1478 foreach ( $paths as $path ) {
1479 $this->cheapCache->clear( $path );
1480 $this->expensiveCache->clear( $path );
1481 }
1482 }
1483 $this->doClearCache( $paths );
1484 }
1485
1494 protected function doClearCache( array $paths = null ) {
1495 }
1496
1497 final public function preloadFileStat( array $params ) {
1499 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1500
1501 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1502 $stats = $this->doGetFileStatMulti( $params );
1503 if ( $stats === null ) {
1504 return true; // not supported
1505 }
1506
1507 // Whether this queried the backend in high consistency mode
1508 $latest = !empty( $params['latest'] );
1509
1510 return $this->ingestFreshFileStats( $stats, $latest );
1511 }
1512
1526 protected function doGetFileStatMulti( array $params ) {
1527 return null; // not supported
1528 }
1529
1537 abstract protected function directoriesAreVirtual();
1538
1549 final protected static function isValidShortContainerName( $container ) {
1550 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1551 // might be used by subclasses. Reserve the dot character.
1552 // The only way dots end up in containers (e.g. resolveStoragePath)
1553 // is due to the wikiId container prefix or the above suffixes.
1554 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1555 }
1556
1566 final protected static function isValidContainerName( $container ) {
1567 // This accounts for NTFS, Swift, and Ceph restrictions
1568 // and disallows directory separators or traversal characters.
1569 // Note that matching strings URL encode to the same string;
1570 // in Swift/Ceph, the length restriction is *after* URL encoding.
1571 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1572 }
1573
1587 final protected function resolveStoragePath( $storagePath ) {
1588 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1589 if ( $backend === $this->name ) { // must be for this backend
1590 $relPath = self::normalizeContainerPath( $relPath );
1591 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1592 // Get shard for the normalized path if this container is sharded
1593 $cShard = $this->getContainerShard( $shortCont, $relPath );
1594 // Validate and sanitize the relative path (backend-specific)
1595 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1596 if ( $relPath !== null ) {
1597 // Prepend any domain ID prefix to the container name
1598 $container = $this->fullContainerName( $shortCont );
1599 if ( self::isValidContainerName( $container ) ) {
1600 // Validate and sanitize the container name (backend-specific)
1601 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1602 if ( $container !== null ) {
1603 return [ $container, $relPath, $cShard ];
1604 }
1605 }
1606 }
1607 }
1608 }
1609
1610 return [ null, null, null ];
1611 }
1612
1628 final protected function resolveStoragePathReal( $storagePath ) {
1629 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1630 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1631 return [ $container, $relPath ];
1632 }
1633
1634 return [ null, null ];
1635 }
1636
1645 final protected function getContainerShard( $container, $relPath ) {
1646 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1647 if ( $levels == 1 || $levels == 2 ) {
1648 // Hash characters are either base 16 or 36
1649 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1650 // Get a regex that represents the shard portion of paths.
1651 // The concatenation of the captures gives us the shard.
1652 if ( $levels === 1 ) { // 16 or 36 shards per container
1653 $hashDirRegex = '(' . $char . ')';
1654 } else { // 256 or 1296 shards per container
1655 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1656 $hashDirRegex = $char . '/(' . $char . '{2})';
1657 } else { // short hash dir format (e.g. "a/b/c")
1658 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1659 }
1660 }
1661 // Allow certain directories to be above the hash dirs so as
1662 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1663 // They must be 2+ chars to avoid any hash directory ambiguity.
1664 $m = [];
1665 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1666 return '.' . implode( '', array_slice( $m, 1 ) );
1667 }
1668
1669 return null; // failed to match
1670 }
1671
1672 return ''; // no sharding
1673 }
1674
1683 final public function isSingleShardPathInternal( $storagePath ) {
1684 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1685
1686 return ( $shard !== null );
1687 }
1688
1697 final protected function getContainerHashLevels( $container ) {
1698 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1699 $config = $this->shardViaHashLevels[$container];
1700 $hashLevels = (int)$config['levels'];
1701 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1702 $hashBase = (int)$config['base'];
1703 if ( $hashBase == 16 || $hashBase == 36 ) {
1704 return [ $hashLevels, $hashBase, $config['repeat'] ];
1705 }
1706 }
1707 }
1708
1709 return [ 0, 0, false ]; // no sharding
1710 }
1711
1718 final protected function getContainerSuffixes( $container ) {
1719 $shards = [];
1720 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1721 if ( $digits > 0 ) {
1722 $numShards = $base ** $digits;
1723 for ( $index = 0; $index < $numShards; $index++ ) {
1724 $shards[] = '.' . Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1725 }
1726 }
1727
1728 return $shards;
1729 }
1730
1737 final protected function fullContainerName( $container ) {
1738 if ( $this->domainId != '' ) {
1739 return "{$this->domainId}-$container";
1740 } else {
1741 return $container;
1742 }
1743 }
1744
1754 protected function resolveContainerName( $container ) {
1755 return $container;
1756 }
1757
1769 protected function resolveContainerPath( $container, $relStoragePath ) {
1770 return $relStoragePath;
1771 }
1772
1779 private function containerCacheKey( $container ) {
1780 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1781 }
1782
1789 final protected function setContainerCache( $container, array $val ) {
1790 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1791 $this->logger->warning( "Unable to set stat cache for container {container}.",
1792 [ 'filebackend' => $this->name, 'container' => $container ]
1793 );
1794 }
1795 }
1796
1803 final protected function deleteContainerCache( $container ) {
1804 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1805 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1806 [ 'filebackend' => $this->name, 'container' => $container ]
1807 );
1808 }
1809 }
1810
1818 final protected function primeContainerCache( array $items ) {
1820 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1821
1822 $paths = []; // list of storage paths
1823 $contNames = []; // (cache key => resolved container name)
1824 // Get all the paths/containers from the items...
1825 foreach ( $items as $item ) {
1826 if ( self::isStoragePath( $item ) ) {
1827 $paths[] = $item;
1828 } elseif ( is_string( $item ) ) { // full container name
1829 $contNames[$this->containerCacheKey( $item )] = $item;
1830 }
1831 }
1832 // Get all the corresponding cache keys for paths...
1833 foreach ( $paths as $path ) {
1834 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1835 if ( $fullCont !== null ) { // valid path for this backend
1836 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1837 }
1838 }
1839
1840 $contInfo = []; // (resolved container name => cache value)
1841 // Get all cache entries for these container cache keys...
1842 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1843 foreach ( $values as $cacheKey => $val ) {
1844 $contInfo[$contNames[$cacheKey]] = $val;
1845 }
1846
1847 // Populate the container process cache for the backend...
1848 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1849 }
1850
1859 protected function doPrimeContainerCache( array $containerInfo ) {
1860 }
1861
1868 private function fileCacheKey( $path ) {
1869 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1870 }
1871
1880 final protected function setFileCache( $path, array $val ) {
1881 $path = FileBackend::normalizeStoragePath( $path );
1882 if ( $path === null ) {
1883 return; // invalid storage path
1884 }
1885 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1886 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1887 $key = $this->fileCacheKey( $path );
1888 // Set the cache unless it is currently salted.
1889 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1890 $this->logger->warning( "Unable to set stat cache for file {path}.",
1891 [ 'filebackend' => $this->name, 'path' => $path ]
1892 );
1893 }
1894 }
1895
1904 final protected function deleteFileCache( $path ) {
1905 $path = FileBackend::normalizeStoragePath( $path );
1906 if ( $path === null ) {
1907 return; // invalid storage path
1908 }
1909 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1910 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1911 [ 'filebackend' => $this->name, 'path' => $path ]
1912 );
1913 }
1914 }
1915
1923 final protected function primeFileCache( array $items ) {
1925 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1926
1927 $paths = []; // list of storage paths
1928 $pathNames = []; // (cache key => storage path)
1929 // Get all the paths/containers from the items...
1930 foreach ( $items as $item ) {
1931 if ( self::isStoragePath( $item ) ) {
1932 $path = FileBackend::normalizeStoragePath( $item );
1933 if ( $path !== null ) {
1934 $paths[] = $path;
1935 }
1936 }
1937 }
1938 // Get all the corresponding cache keys for paths...
1939 foreach ( $paths as $path ) {
1940 [ , $rel, ] = $this->resolveStoragePath( $path );
1941 if ( $rel !== null ) { // valid path for this backend
1942 $pathNames[$this->fileCacheKey( $path )] = $path;
1943 }
1944 }
1945 // Get all cache entries for these file cache keys.
1946 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1947 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1948 // Load all of the results into process cache...
1949 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1950 $path = $pathNames[$cacheKey];
1951 // This flag only applies to stat info loaded directly
1952 // from a high consistency backend query to the process cache
1953 unset( $stat['latest'] );
1954
1955 $this->cheapCache->setField( $path, 'stat', $stat );
1956 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1957 // Some backends store SHA-1 as metadata
1958 $this->cheapCache->setField(
1959 $path,
1960 'sha1',
1961 [ 'hash' => $stat['sha1'], 'latest' => false ]
1962 );
1963 }
1964 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1965 // Some backends store custom headers/metadata
1966 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1967 $this->cheapCache->setField(
1968 $path,
1969 'xattr',
1970 [ 'map' => $stat['xattr'], 'latest' => false ]
1971 );
1972 }
1973 }
1974 }
1975
1983 final protected static function normalizeXAttributes( array $xattr ) {
1984 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1985
1986 foreach ( $xattr['headers'] as $name => $value ) {
1987 $newXAttr['headers'][strtolower( $name )] = $value;
1988 }
1989
1990 foreach ( $xattr['metadata'] as $name => $value ) {
1991 $newXAttr['metadata'][strtolower( $name )] = $value;
1992 }
1993
1994 return $newXAttr;
1995 }
1996
2003 final protected function setConcurrencyFlags( array $opts ) {
2004 $opts['concurrency'] = 1; // off
2005 if ( $this->parallelize === 'implicit' ) {
2006 if ( $opts['parallelize'] ?? true ) {
2007 $opts['concurrency'] = $this->concurrency;
2008 }
2009 } elseif ( $this->parallelize === 'explicit' ) {
2010 if ( !empty( $opts['parallelize'] ) ) {
2011 $opts['concurrency'] = $this->concurrency;
2012 }
2013 }
2014
2015 return $opts;
2016 }
2017
2027 protected function getContentType( $storagePath, $content, $fsPath ) {
2028 if ( $this->mimeCallback ) {
2029 return call_user_func_array( $this->mimeCallback, func_get_args() );
2030 }
2031
2032 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2033 return $mime ?: 'unknown/unknown';
2034 }
2035}
array $params
The job parameters.
Class representing a non-directory file on the file system.
Definition FSFile.php:32
File backend exception for checked exceptions (e.g.
FileBackendStore helper class for performing asynchronous file operations.
Base class for all backends using particular storage medium.
preloadFileStat(array $params)
Preload file stat information (concurrently if possible) into in-process cache.
doGetLocalReferenceMulti(array $params)
resolveContainerName( $container)
Resolve a container name, checking if it's allowed by the backend.
static normalizeXAttributes(array $xattr)
Normalize file headers/metadata to the FileBackend::getFileXAttributes() format.
getLocalReferenceMulti(array $params)
Like getLocalReference() except it takes an array of storage paths and yields an order-preserved map ...
setFileCache( $path, array $val)
Set the cached stat info for a file path.
doPublish(array $params)
moveInternal(array $params)
Move a file from one storage path to another in the backend.
setContainerCache( $container, array $val)
Set the cached info for a container.
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.
doGetFileContentsMulti(array $params)
doStreamFile(array $params)
doSecure(array $params)
MapCacheLRU $expensiveCache
Map of paths to large (RAM/disk) cache items.
doClean(array $params)
getFileTimestamp(array $params)
Get the last-modified timestamp of the file at a storage path.
doGetLocalCopyMulti(array $params)
getScopedLocksForOps(array $ops, StatusValue $status)
Get an array of scoped locks needed for a batch of file operations.
doCleanInternal( $container, $dir, array $params)
getPathsToLockForOpsInternal(array $performOps)
Get a list of storage paths to lock for a list of operations Returns an array with LockManager::LOCK_...
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
doPrepareInternal( $container, $dir, array $params)
concatenate(array $params)
Concatenate a list of storage files into a single file system file.
storeInternal(array $params)
Store a file into the backend from a file on disk.
getFileProps(array $params)
Get the properties of the content of the file at a storage path in the backend.
getDirectoryList(array $params)
Get an iterator to list all directories under a storage directory.
doQuickOperationsInternal(array $ops, array $opts)
resolveStoragePath( $storagePath)
Splits a storage path into an internal container name, an internal relative file name,...
copyInternal(array $params)
Copy a file from one storage path to another in the backend.
doStoreInternal(array $params)
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doGetFileStat(array $params)
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
MapCacheLRU $cheapCache
Map of paths to small (RAM/disk) cache items.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
doPublishInternal( $container, $dir, array $params)
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
getFileSha1Base36(array $params)
Get a SHA-1 hash of the content of the file at a storage path in the backend.
static isValidContainerName( $container)
Check if a full container name is valid.
ingestFreshFileStats(array $stats, $latest)
Ingest file stat entries that just came from querying the backend (not cache)
getFileListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
doCopyInternal(array $params)
getLocalCopyMulti(array $params)
Like getLocalCopy() except it takes an array of storage paths and yields an order preserved-map of st...
getFileContentsMulti(array $params)
Like getFileContents() except it takes an array of storage paths and returns an order preserved map o...
doClearCache(array $paths=null)
Clears any additional stat caches for storage paths.
fullContainerName( $container)
Get the full container name, including the domain ID prefix.
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...
doOperationsInternal(array $ops, array $opts)
isSingleShardPathInternal( $storagePath)
Check if a storage path maps to a single shard.
directoryExists(array $params)
Check if a directory exists at a given storage path.
doDeleteInternal(array $params)
getContainerSuffixes( $container)
Get a list of full container shard suffixes for a container.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
sanitizeOpHeaders(array $op)
Normalize and filter HTTP headers from a file operation.
doDescribeInternal(array $params)
doGetFileSha1Base36(array $params)
deleteInternal(array $params)
Delete a file at the storage path.
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
doMoveInternal(array $params)
maxFileSizeInternal()
Get the maximum allowable file size given backend medium restrictions and basic performance constrain...
describeInternal(array $params)
Alter metadata for a file at the storage path.
streamFile(array $params)
Stream the content of the file at a storage path in the backend.
getOperationsInternal(array $ops)
Return a list of FileOp objects from a list of operations.
deleteFileCache( $path)
Delete the cached stat info for a file path.
setConcurrencyFlags(array $opts)
Set the 'concurrency' option from a list of operation options.
getFileXAttributes(array $params)
Get metadata about a file at a storage path in the backend.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
preloadCache(array $paths)
Preload persistent file stat cache and property cache into in-process cache.
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
doDirectoryExists( $container, $dir, array $params)
WANObjectCache $memCache
doPrepare(array $params)
FileBackend::prepare() StatusValue Good status without value for success, fatal otherwise.
getFileHttpUrl(array $params)
__construct(array $config)
doGetFileXAttributes(array $params)
doExecuteOpHandlesInternal(array $fileOpHandles)
nullInternal(array $params)
No-op file operation that does nothing.
array< string, array > $shardViaHashLevels
Map of container names to sharding config.
getFileSize(array $params)
Get the size (bytes) of a file at a storage path in the backend.
callable null $mimeCallback
Method to get the MIME type of files.
doConcatenate(array $params)
doSecureInternal( $container, $dir, array $params)
doCreateInternal(array $params)
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getDirectoryListInternal( $container, $dir, array $params)
Do not call this function from places outside FileBackend.
static isValidShortContainerName( $container)
Check if a short container name is valid.
getContainerHashLevels( $container)
Get the sharding config for a container.
getContainerShard( $container, $relPath)
Get the container name shard suffix for a given path.
deleteContainerCache( $container)
Delete the cached info for a container.
createInternal(array $params)
Create a file in the backend with the given contents.
getFileList(array $params)
Get an iterator to list all stored files under a storage directory.
static attempt(array $performOps, array $opts)
Attempt to perform a series of file operations.
Functions related to the output of file content.
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.
Multi-datacenter aware caching interface.
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.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:88
A BagOStuff object with no objects in it.