MediaWiki master
FileBackendStore.php
Go to the documentation of this file.
1<?php
24use Wikimedia\AtEase\AtEase;
25use Wikimedia\Timestamp\ConvertibleTimestamp;
26
41abstract class FileBackendStore extends FileBackend {
43 protected $memCache;
45 protected $srvCache;
47 protected $cheapCache;
49 protected $expensiveCache;
50
52 protected $shardViaHashLevels = [];
53
55 protected $mimeCallback;
56
57 protected $maxFileSize = 32 * 1024 * 1024 * 1024; // integer bytes (32GiB)
58
59 protected const CACHE_TTL = 10; // integer; TTL in seconds for process cache entries
60 protected const CACHE_CHEAP_SIZE = 500; // integer; max entries in "cheap cache"
61 protected const CACHE_EXPENSIVE_SIZE = 5; // integer; max entries in "expensive cache"
62
64 protected const RES_ABSENT = false;
66 protected const RES_ERROR = null;
67
69 protected const ABSENT_NORMAL = 'FNE-N';
71 protected const ABSENT_LATEST = 'FNE-L';
72
86 public function __construct( array $config ) {
87 parent::__construct( $config );
88 $this->mimeCallback = $config['mimeCallback'] ?? null;
89 $this->srvCache = new EmptyBagOStuff(); // disabled by default
90 $this->memCache = WANObjectCache::newEmpty(); // disabled by default
91 $this->cheapCache = new MapCacheLRU( self::CACHE_CHEAP_SIZE );
92 $this->expensiveCache = new MapCacheLRU( self::CACHE_EXPENSIVE_SIZE );
93 }
94
102 final public function maxFileSizeInternal() {
103 return min( $this->maxFileSize, PHP_INT_MAX );
104 }
105
116 abstract public function isPathUsableInternal( $storagePath );
117
136 final public function createInternal( array $params ) {
138 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
139
140 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
141 $status = $this->newStatus( 'backend-fail-maxsize',
142 $params['dst'], $this->maxFileSizeInternal() );
143 } else {
144 $status = $this->doCreateInternal( $params );
145 $this->clearCache( [ $params['dst'] ] );
146 if ( $params['dstExists'] ?? true ) {
147 $this->deleteFileCache( $params['dst'] ); // persistent cache
148 }
149 }
150
151 return $status;
152 }
153
159 abstract protected function doCreateInternal( array $params );
160
179 final public function storeInternal( array $params ) {
181 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
182
183 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
184 $status = $this->newStatus( 'backend-fail-maxsize',
185 $params['dst'], $this->maxFileSizeInternal() );
186 } else {
187 $status = $this->doStoreInternal( $params );
188 $this->clearCache( [ $params['dst'] ] );
189 if ( $params['dstExists'] ?? true ) {
190 $this->deleteFileCache( $params['dst'] ); // persistent cache
191 }
192 }
193
194 return $status;
195 }
196
202 abstract protected function doStoreInternal( array $params );
203
223 final public function copyInternal( array $params ) {
225 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
226
227 $status = $this->doCopyInternal( $params );
228 $this->clearCache( [ $params['dst'] ] );
229 if ( $params['dstExists'] ?? true ) {
230 $this->deleteFileCache( $params['dst'] ); // persistent cache
231 }
232
233 return $status;
234 }
235
241 abstract protected function doCopyInternal( array $params );
242
257 final public function deleteInternal( array $params ) {
259 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
260
261 $status = $this->doDeleteInternal( $params );
262 $this->clearCache( [ $params['src'] ] );
263 $this->deleteFileCache( $params['src'] ); // persistent cache
264 return $status;
265 }
266
272 abstract protected function doDeleteInternal( array $params );
273
293 final public function moveInternal( array $params ) {
295 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
296
297 $status = $this->doMoveInternal( $params );
298 $this->clearCache( [ $params['src'], $params['dst'] ] );
299 $this->deleteFileCache( $params['src'] ); // persistent cache
300 if ( $params['dstExists'] ?? true ) {
301 $this->deleteFileCache( $params['dst'] ); // persistent cache
302 }
303
304 return $status;
305 }
306
312 abstract protected function doMoveInternal( array $params );
313
328 final public function describeInternal( array $params ) {
330 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
331
332 if ( count( $params['headers'] ) ) {
333 $status = $this->doDescribeInternal( $params );
334 $this->clearCache( [ $params['src'] ] );
335 $this->deleteFileCache( $params['src'] ); // persistent cache
336 } else {
337 $status = $this->newStatus(); // nothing to do
338 }
339
340 return $status;
341 }
342
349 protected function doDescribeInternal( array $params ) {
350 return $this->newStatus();
351 }
352
360 final public function nullInternal( array $params ) {
361 return $this->newStatus();
362 }
363
364 final public function concatenate( array $params ) {
366 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
367 $status = $this->newStatus();
368
369 // Try to lock the source files for the scope of this function
371 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
372 if ( $status->isOK() ) {
373 // Actually do the file concatenation...
374 $start_time = microtime( true );
375 $status->merge( $this->doConcatenate( $params ) );
376 $sec = microtime( true ) - $start_time;
377 if ( !$status->isOK() ) {
378 $this->logger->error( static::class . "-{$this->name}" .
379 " failed to concatenate " . count( $params['srcs'] ) . " file(s) [$sec sec]" );
380 }
381 }
382
383 return $status;
384 }
385
392 protected function doConcatenate( array $params ) {
393 $status = $this->newStatus();
394 $tmpPath = $params['dst'];
395 unset( $params['latest'] );
396
397 // Check that the specified temp file is valid...
398 AtEase::suppressWarnings();
399 $ok = ( is_file( $tmpPath ) && filesize( $tmpPath ) == 0 );
400 AtEase::restoreWarnings();
401 if ( !$ok ) { // not present or not empty
402 $status->fatal( 'backend-fail-opentemp', $tmpPath );
403
404 return $status;
405 }
406
407 // Get local FS versions of the chunks needed for the concatenation...
408 $fsFiles = $this->getLocalReferenceMulti( $params );
409 foreach ( $fsFiles as $path => &$fsFile ) {
410 if ( !$fsFile ) { // chunk failed to download?
411 $fsFile = $this->getLocalReference( [ 'src' => $path ] );
412 if ( !$fsFile ) { // retry failed?
413 $status->fatal(
414 $fsFile === self::RES_ERROR ? 'backend-fail-read' : 'backend-fail-notexists',
415 $path
416 );
417
418 return $status;
419 }
420 }
421 }
422 unset( $fsFile ); // unset reference so we can reuse $fsFile
423
424 // Get a handle for the destination temp file
425 $tmpHandle = fopen( $tmpPath, 'ab' );
426 if ( $tmpHandle === false ) {
427 $status->fatal( 'backend-fail-opentemp', $tmpPath );
428
429 return $status;
430 }
431
432 // Build up the temp file using the source chunks (in order)...
433 foreach ( $fsFiles as $virtualSource => $fsFile ) {
434 // Get a handle to the local FS version
435 $sourceHandle = fopen( $fsFile->getPath(), 'rb' );
436 if ( $sourceHandle === false ) {
437 fclose( $tmpHandle );
438 $status->fatal( 'backend-fail-read', $virtualSource );
439
440 return $status;
441 }
442 // Append chunk to file (pass chunk size to avoid magic quotes)
443 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
444 fclose( $sourceHandle );
445 fclose( $tmpHandle );
446 $status->fatal( 'backend-fail-writetemp', $tmpPath );
447
448 return $status;
449 }
450 fclose( $sourceHandle );
451 }
452 if ( !fclose( $tmpHandle ) ) {
453 $status->fatal( 'backend-fail-closetemp', $tmpPath );
454
455 return $status;
456 }
457
458 clearstatcache(); // temp file changed
459
460 return $status;
461 }
462
466 final protected function doPrepare( array $params ) {
468 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
469 $status = $this->newStatus();
470
471 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
472 if ( $dir === null ) {
473 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
474
475 return $status; // invalid storage path
476 }
477
478 if ( $shard !== null ) { // confined to a single container/shard
479 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
480 } else { // directory is on several shards
481 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
482 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
483 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
484 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
485 }
486 }
487
488 return $status;
489 }
490
499 protected function doPrepareInternal( $container, $dir, array $params ) {
500 return $this->newStatus();
501 }
502
503 final protected function doSecure( array $params ) {
505 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
506 $status = $this->newStatus();
507
508 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
509 if ( $dir === null ) {
510 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
511
512 return $status; // invalid storage path
513 }
514
515 if ( $shard !== null ) { // confined to a single container/shard
516 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
517 } else { // directory is on several shards
518 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
519 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
520 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
521 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
522 }
523 }
524
525 return $status;
526 }
527
536 protected function doSecureInternal( $container, $dir, array $params ) {
537 return $this->newStatus();
538 }
539
540 final protected function doPublish( array $params ) {
542 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
543 $status = $this->newStatus();
544
545 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
546 if ( $dir === null ) {
547 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
548
549 return $status; // invalid storage path
550 }
551
552 if ( $shard !== null ) { // confined to a single container/shard
553 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
554 } else { // directory is on several shards
555 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
556 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
557 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
558 $status->merge( $this->doPublishInternal( "{$fullCont}{$suffix}", $dir, $params ) );
559 }
560 }
561
562 return $status;
563 }
564
573 protected function doPublishInternal( $container, $dir, array $params ) {
574 return $this->newStatus();
575 }
576
577 final protected function doClean( array $params ) {
579 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
580 $status = $this->newStatus();
581
582 // Recursive: first delete all empty subdirs recursively
583 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
584 $subDirsRel = $this->getTopDirectoryList( [ 'dir' => $params['dir'] ] );
585 if ( $subDirsRel !== null ) { // no errors
586 foreach ( $subDirsRel as $subDirRel ) {
587 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
588 $status->merge( $this->doClean( [ 'dir' => $subDir ] + $params ) );
589 }
590 unset( $subDirsRel ); // free directory for rmdir() on Windows (for FS backends)
591 }
592 }
593
594 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
595 if ( $dir === null ) {
596 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
597
598 return $status; // invalid storage path
599 }
600
601 // Attempt to lock this directory...
602 $filesLockEx = [ $params['dir'] ];
604 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
605 if ( !$status->isOK() ) {
606 return $status; // abort
607 }
608
609 if ( $shard !== null ) { // confined to a single container/shard
610 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
611 $this->deleteContainerCache( $fullCont ); // purge cache
612 } else { // directory is on several shards
613 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
614 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
615 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
616 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
617 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
618 }
619 }
620
621 return $status;
622 }
623
632 protected function doCleanInternal( $container, $dir, array $params ) {
633 return $this->newStatus();
634 }
635
636 final public function fileExists( array $params ) {
638 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
639
640 $stat = $this->getFileStat( $params );
641 if ( is_array( $stat ) ) {
642 return true;
643 }
644
645 return $stat === self::RES_ABSENT ? false : self::EXISTENCE_ERROR;
646 }
647
648 final public function getFileTimestamp( array $params ) {
650 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
651
652 $stat = $this->getFileStat( $params );
653 if ( is_array( $stat ) ) {
654 return $stat['mtime'];
655 }
656
657 return self::TIMESTAMP_FAIL; // all failure cases
658 }
659
660 final public function getFileSize( array $params ) {
662 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
663
664 $stat = $this->getFileStat( $params );
665 if ( is_array( $stat ) ) {
666 return $stat['size'];
667 }
668
669 return self::SIZE_FAIL; // all failure cases
670 }
671
672 final public function getFileStat( array $params ) {
674 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
675
677 if ( $path === null ) {
678 return self::STAT_ERROR; // invalid storage path
679 }
680
681 // Whether to bypass cache except for process cache entries loaded directly from
682 // high consistency backend queries (caller handles any cache flushing and locking)
683 $latest = !empty( $params['latest'] );
684 // Whether to ignore cache entries missing the SHA-1 field for existing files
685 $requireSHA1 = !empty( $params['requireSHA1'] );
686
687 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
688 // Load the persistent stat cache into process cache if needed
689 if ( !$latest ) {
690 if (
691 // File stat is not in process cache
692 $stat === null ||
693 // Key/value store backends might opportunistically set file stat process
694 // cache entries from object listings that do not include the SHA-1. In that
695 // case, loading the persistent stat cache will likely yield the SHA-1.
696 ( $requireSHA1 && is_array( $stat ) && !isset( $stat['sha1'] ) )
697 ) {
698 $this->primeFileCache( [ $path ] );
699 // Get any newly process-cached entry
700 $stat = $this->cheapCache->getField( $path, 'stat', self::CACHE_TTL );
701 }
702 }
703
704 if ( is_array( $stat ) ) {
705 if (
706 ( !$latest || !empty( $stat['latest'] ) ) &&
707 ( !$requireSHA1 || isset( $stat['sha1'] ) )
708 ) {
709 return $stat;
710 }
711 } elseif ( $stat === self::ABSENT_LATEST ) {
712 return self::STAT_ABSENT;
713 } elseif ( $stat === self::ABSENT_NORMAL ) {
714 if ( !$latest ) {
715 return self::STAT_ABSENT;
716 }
717 }
718
719 // Load the file stat from the backend and update caches
720 $stat = $this->doGetFileStat( $params );
721 $this->ingestFreshFileStats( [ $path => $stat ], $latest );
722
723 if ( is_array( $stat ) ) {
724 return $stat;
725 }
726
727 return $stat === self::RES_ERROR ? self::STAT_ERROR : self::STAT_ABSENT;
728 }
729
737 final protected function ingestFreshFileStats( array $stats, $latest ) {
738 $success = true;
739
740 foreach ( $stats as $path => $stat ) {
741 if ( is_array( $stat ) ) {
742 // Strongly consistent backends might automatically set this flag
743 $stat['latest'] ??= $latest;
744
745 $this->cheapCache->setField( $path, 'stat', $stat );
746 if ( isset( $stat['sha1'] ) ) {
747 // Some backends store the SHA-1 hash as metadata
748 $this->cheapCache->setField(
749 $path,
750 'sha1',
751 [ 'hash' => $stat['sha1'], 'latest' => $latest ]
752 );
753 }
754 if ( isset( $stat['xattr'] ) ) {
755 // Some backends store custom headers/metadata
756 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
757 $this->cheapCache->setField(
758 $path,
759 'xattr',
760 [ 'map' => $stat['xattr'], 'latest' => $latest ]
761 );
762 }
763 // Update persistent cache (@TODO: set all entries in one batch)
764 $this->setFileCache( $path, $stat );
765 } elseif ( $stat === self::RES_ABSENT ) {
766 $this->cheapCache->setField(
767 $path,
768 'stat',
769 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
770 );
771 $this->cheapCache->setField(
772 $path,
773 'xattr',
774 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
775 );
776 $this->cheapCache->setField(
777 $path,
778 'sha1',
779 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
780 );
781 $this->logger->debug(
782 __METHOD__ . ': File {path} does not exist',
783 [ 'path' => $path ]
784 );
785 } else {
786 $success = false;
787 $this->logger->error(
788 __METHOD__ . ': Could not stat file {path}',
789 [ 'path' => $path ]
790 );
791 }
792 }
793
794 return $success;
795 }
796
802 abstract protected function doGetFileStat( array $params );
803
804 public function getFileContentsMulti( array $params ) {
806 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
807
808 $params = $this->setConcurrencyFlags( $params );
809 $contents = $this->doGetFileContentsMulti( $params );
810 foreach ( $contents as $path => $content ) {
811 if ( !is_string( $content ) ) {
812 $contents[$path] = self::CONTENT_FAIL; // used for all failure cases
813 }
814 }
815
816 return $contents;
817 }
818
825 protected function doGetFileContentsMulti( array $params ) {
826 $contents = [];
827 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
828 if ( $fsFile instanceof FSFile ) {
829 AtEase::suppressWarnings();
830 $content = file_get_contents( $fsFile->getPath() );
831 AtEase::restoreWarnings();
832 $contents[$path] = is_string( $content ) ? $content : self::RES_ERROR;
833 } else {
834 // self::RES_ERROR or self::RES_ABSENT
835 $contents[$path] = $fsFile;
836 }
837 }
838
839 return $contents;
840 }
841
842 final public function getFileXAttributes( array $params ) {
844 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
845
847 if ( $path === null ) {
848 return self::XATTRS_FAIL; // invalid storage path
849 }
850 $latest = !empty( $params['latest'] ); // use latest data?
851 if ( $this->cheapCache->hasField( $path, 'xattr', self::CACHE_TTL ) ) {
852 $stat = $this->cheapCache->getField( $path, 'xattr' );
853 // If we want the latest data, check that this cached
854 // value was in fact fetched with the latest available data.
855 if ( !$latest || $stat['latest'] ) {
856 return $stat['map'];
857 }
858 }
859 $fields = $this->doGetFileXAttributes( $params );
860 if ( is_array( $fields ) ) {
861 $fields = self::normalizeXAttributes( $fields );
862 $this->cheapCache->setField(
863 $path,
864 'xattr',
865 [ 'map' => $fields, 'latest' => $latest ]
866 );
867 } elseif ( $fields === self::RES_ABSENT ) {
868 $this->cheapCache->setField(
869 $path,
870 'xattr',
871 [ 'map' => self::XATTRS_FAIL, 'latest' => $latest ]
872 );
873 } else {
874 $fields = self::XATTRS_FAIL; // used for all failure cases
875 }
876
877 return $fields;
878 }
879
886 protected function doGetFileXAttributes( array $params ) {
887 return [ 'headers' => [], 'metadata' => [] ]; // not supported
888 }
889
890 final public function getFileSha1Base36( array $params ) {
892 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
893
895 if ( $path === null ) {
896 return self::SHA1_FAIL; // invalid storage path
897 }
898 $latest = !empty( $params['latest'] ); // use latest data?
899 if ( $this->cheapCache->hasField( $path, 'sha1', self::CACHE_TTL ) ) {
900 $stat = $this->cheapCache->getField( $path, 'sha1' );
901 // If we want the latest data, check that this cached
902 // value was in fact fetched with the latest available data.
903 if ( !$latest || $stat['latest'] ) {
904 return $stat['hash'];
905 }
906 }
907 $sha1 = $this->doGetFileSha1Base36( $params );
908 if ( is_string( $sha1 ) ) {
909 $this->cheapCache->setField(
910 $path,
911 'sha1',
912 [ 'hash' => $sha1, 'latest' => $latest ]
913 );
914 } elseif ( $sha1 === self::RES_ABSENT ) {
915 $this->cheapCache->setField(
916 $path,
917 'sha1',
918 [ 'hash' => self::SHA1_FAIL, 'latest' => $latest ]
919 );
920 } else {
921 $sha1 = self::SHA1_FAIL; // used for all failure cases
922 }
923
924 return $sha1;
925 }
926
933 protected function doGetFileSha1Base36( array $params ) {
934 $fsFile = $this->getLocalReference( $params );
935 if ( $fsFile instanceof FSFile ) {
936 $sha1 = $fsFile->getSha1Base36();
937
938 return is_string( $sha1 ) ? $sha1 : self::RES_ERROR;
939 }
940
941 return $fsFile === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
942 }
943
944 final public function getFileProps( array $params ) {
946 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
947
948 $fsFile = $this->getLocalReference( $params );
949
950 return $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
951 }
952
953 final public function getLocalReferenceMulti( array $params ) {
955 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
956
957 $params = $this->setConcurrencyFlags( $params );
958
959 $fsFiles = []; // (path => FSFile)
960 $latest = !empty( $params['latest'] ); // use latest data?
961 // Reuse any files already in process cache...
962 foreach ( $params['srcs'] as $src ) {
964 if ( $path === null ) {
965 $fsFiles[$src] = self::RES_ERROR; // invalid storage path
966 } elseif ( $this->expensiveCache->hasField( $path, 'localRef' ) ) {
967 $val = $this->expensiveCache->getField( $path, 'localRef' );
968 // If we want the latest data, check that this cached
969 // value was in fact fetched with the latest available data.
970 if ( !$latest || $val['latest'] ) {
971 $fsFiles[$src] = $val['object'];
972 }
973 }
974 }
975 // Fetch local references of any remaining files...
976 $params['srcs'] = array_diff( $params['srcs'], array_keys( $fsFiles ) );
977 foreach ( $this->doGetLocalReferenceMulti( $params ) as $path => $fsFile ) {
978 if ( $fsFile instanceof FSFile ) {
979 $fsFiles[$path] = $fsFile;
980 $this->expensiveCache->setField(
981 $path,
982 'localRef',
983 [ 'object' => $fsFile, 'latest' => $latest ]
984 );
985 } else {
986 // self::RES_ERROR or self::RES_ABSENT
987 $fsFiles[$path] = $fsFile;
988 }
989 }
990
991 return $fsFiles;
992 }
993
1000 protected function doGetLocalReferenceMulti( array $params ) {
1001 return $this->doGetLocalCopyMulti( $params );
1002 }
1003
1004 final public function getLocalCopyMulti( array $params ) {
1006 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1007
1008 $params = $this->setConcurrencyFlags( $params );
1009
1010 return $this->doGetLocalCopyMulti( $params );
1011 }
1012
1018 abstract protected function doGetLocalCopyMulti( array $params );
1019
1026 public function getFileHttpUrl( array $params ) {
1027 return self::TEMPURL_ERROR; // not supported
1028 }
1029
1030 final public function streamFile( array $params ) {
1032 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1033 $status = $this->newStatus();
1034
1035 // Always set some fields for subclass convenience
1036 $params['options'] ??= [];
1037 $params['headers'] ??= [];
1038
1039 // Don't stream it out as text/html if there was a PHP error
1040 if ( ( empty( $params['headless'] ) || $params['headers'] ) && headers_sent() ) {
1041 print "Headers already sent, terminating.\n";
1042 $status->fatal( 'backend-fail-stream', $params['src'] );
1043 return $status;
1044 }
1045
1046 $status->merge( $this->doStreamFile( $params ) );
1047
1048 return $status;
1049 }
1050
1057 protected function doStreamFile( array $params ) {
1058 $status = $this->newStatus();
1059
1060 $flags = 0;
1061 $flags |= !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1062 $flags |= !empty( $params['allowOB'] ) ? HTTPFileStreamer::STREAM_ALLOW_OB : 0;
1063
1064 $fsFile = $this->getLocalReference( $params );
1065 if ( $fsFile ) {
1066 $streamer = new HTTPFileStreamer(
1067 $fsFile->getPath(),
1068 $this->getStreamerOptions()
1069 );
1070 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1071 } else {
1072 $res = false;
1073 HTTPFileStreamer::send404Message( $params['src'], $flags );
1074 }
1075
1076 if ( !$res ) {
1077 $status->fatal( 'backend-fail-stream', $params['src'] );
1078 }
1079
1080 return $status;
1081 }
1082
1083 final public function directoryExists( array $params ) {
1084 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1085 if ( $dir === null ) {
1086 return self::EXISTENCE_ERROR; // invalid storage path
1087 }
1088 if ( $shard !== null ) { // confined to a single container/shard
1089 return $this->doDirectoryExists( $fullCont, $dir, $params );
1090 } else { // directory is on several shards
1091 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1092 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1093 $res = false; // response
1094 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1095 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1096 if ( $exists === true ) {
1097 $res = true;
1098 break; // found one!
1099 } elseif ( $exists === self::RES_ERROR ) {
1100 $res = self::EXISTENCE_ERROR;
1101 }
1102 }
1103
1104 return $res;
1105 }
1106 }
1107
1116 abstract protected function doDirectoryExists( $container, $dir, array $params );
1117
1118 final public function getDirectoryList( array $params ) {
1119 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1120 if ( $dir === null ) {
1121 return self::EXISTENCE_ERROR; // invalid storage path
1122 }
1123 if ( $shard !== null ) {
1124 // File listing is confined to a single container/shard
1125 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1126 } else {
1127 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1128 // File listing spans multiple containers/shards
1129 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1130
1131 return new FileBackendStoreShardDirIterator( $this,
1132 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1133 }
1134 }
1135
1146 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1147
1148 final public function getFileList( array $params ) {
1149 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1150 if ( $dir === null ) {
1151 return self::LIST_ERROR; // invalid storage path
1152 }
1153 if ( $shard !== null ) {
1154 // File listing is confined to a single container/shard
1155 return $this->getFileListInternal( $fullCont, $dir, $params );
1156 } else {
1157 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1158 // File listing spans multiple containers/shards
1159 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1160
1161 return new FileBackendStoreShardFileIterator( $this,
1162 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1163 }
1164 }
1165
1176 abstract public function getFileListInternal( $container, $dir, array $params );
1177
1189 final public function getOperationsInternal( array $ops ) {
1190 $supportedOps = [
1191 'store' => StoreFileOp::class,
1192 'copy' => CopyFileOp::class,
1193 'move' => MoveFileOp::class,
1194 'delete' => DeleteFileOp::class,
1195 'create' => CreateFileOp::class,
1196 'describe' => DescribeFileOp::class,
1197 'null' => NullFileOp::class
1198 ];
1199
1200 $performOps = []; // array of FileOp objects
1201 // Build up ordered array of FileOps...
1202 foreach ( $ops as $operation ) {
1203 $opName = $operation['op'];
1204 if ( isset( $supportedOps[$opName] ) ) {
1205 $class = $supportedOps[$opName];
1206 // Get params for this operation
1207 $params = $operation;
1208 // Append the FileOp class
1209 $performOps[] = new $class( $this, $params, $this->logger );
1210 } else {
1211 throw new FileBackendError( "Operation '$opName' is not supported." );
1212 }
1213 }
1214
1215 return $performOps;
1216 }
1217
1228 final public function getPathsToLockForOpsInternal( array $performOps ) {
1229 // Build up a list of files to lock...
1230 $paths = [ 'sh' => [], 'ex' => [] ];
1231 foreach ( $performOps as $fileOp ) {
1232 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1233 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1234 }
1235 // Optimization: if doing an EX lock anyway, don't also set an SH one
1236 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1237 // Get a shared lock on the parent directory of each path changed
1238 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1239
1240 return [
1241 LockManager::LOCK_UW => $paths['sh'],
1242 LockManager::LOCK_EX => $paths['ex']
1243 ];
1244 }
1245
1246 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1247 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1248
1249 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1250 }
1251
1252 final protected function doOperationsInternal( array $ops, array $opts ) {
1254 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1255 $status = $this->newStatus();
1256
1257 // Fix up custom header name/value pairs
1258 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1259 // Build up a list of FileOps and involved paths
1260 $fileOps = $this->getOperationsInternal( $ops );
1261 $pathsUsed = [];
1262 foreach ( $fileOps as $fileOp ) {
1263 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1264 }
1265
1266 // Acquire any locks as needed for the scope of this function
1267 if ( empty( $opts['nonLocking'] ) ) {
1268 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1270 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1271 if ( !$status->isOK() ) {
1272 return $status; // abort
1273 }
1274 }
1275
1276 // Clear any file cache entries (after locks acquired)
1277 if ( empty( $opts['preserveCache'] ) ) {
1278 $this->clearCache( $pathsUsed );
1279 }
1280
1281 // Enlarge the cache to fit the stat entries of these files
1282 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1283
1284 // Load from the persistent container caches
1285 $this->primeContainerCache( $pathsUsed );
1286 // Get the latest stat info for all the files (having locked them)
1287 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1288
1289 if ( $ok ) {
1290 // Actually attempt the operation batch...
1291 $opts = $this->setConcurrencyFlags( $opts );
1292 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1293 } else {
1294 // If we could not even stat some files, then bail out
1295 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1296 foreach ( $ops as $i => $op ) { // mark each op as failed
1297 $subStatus->success[$i] = false;
1298 ++$subStatus->failCount;
1299 }
1300 $this->logger->error( static::class . "-{$this->name} " .
1301 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1302 }
1303
1304 // Merge errors into StatusValue fields
1305 $status->merge( $subStatus );
1306 $status->success = $subStatus->success; // not done in merge()
1307
1308 // Shrink the stat cache back to normal size
1309 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1310
1311 return $status;
1312 }
1313
1314 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1316 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1317 $status = $this->newStatus();
1318
1319 // Fix up custom header name/value pairs
1320 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1321 // Build up a list of FileOps and involved paths
1322 $fileOps = $this->getOperationsInternal( $ops );
1323 $pathsUsed = [];
1324 foreach ( $fileOps as $fileOp ) {
1325 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1326 }
1327
1328 // Clear any file cache entries for involved paths
1329 $this->clearCache( $pathsUsed );
1330
1331 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1332 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1333 $maxConcurrency = $this->concurrency; // throttle
1335 $statuses = []; // array of (index => StatusValue)
1337 $batch = [];
1338 foreach ( $fileOps as $index => $fileOp ) {
1339 $subStatus = $async
1340 ? $fileOp->attemptAsyncQuick()
1341 : $fileOp->attemptQuick();
1342 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1343 if ( count( $batch ) >= $maxConcurrency ) {
1344 // Execute this batch. Don't queue any more ops since they contain
1345 // open filehandles which are a limited resource (T230245).
1346 $statuses += $this->executeOpHandlesInternal( $batch );
1347 $batch = [];
1348 }
1349 $batch[$index] = $subStatus->value; // keep index
1350 } else { // error or completed
1351 $statuses[$index] = $subStatus; // keep index
1352 }
1353 }
1354 if ( count( $batch ) ) {
1355 $statuses += $this->executeOpHandlesInternal( $batch );
1356 }
1357 // Marshall and merge all the responses...
1358 foreach ( $statuses as $index => $subStatus ) {
1359 $status->merge( $subStatus );
1360 if ( $subStatus->isOK() ) {
1361 $status->success[$index] = true;
1362 ++$status->successCount;
1363 } else {
1364 $status->success[$index] = false;
1365 ++$status->failCount;
1366 }
1367 }
1368
1369 $this->clearCache( $pathsUsed );
1370
1371 return $status;
1372 }
1373
1383 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1385 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1386
1387 foreach ( $fileOpHandles as $fileOpHandle ) {
1388 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1389 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1390 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1391 throw new InvalidArgumentException( "Expected handle for this file backend." );
1392 }
1393 }
1394
1395 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1396 foreach ( $fileOpHandles as $fileOpHandle ) {
1397 $fileOpHandle->closeResources();
1398 }
1399
1400 return $statuses;
1401 }
1402
1412 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1413 if ( count( $fileOpHandles ) ) {
1414 throw new FileBackendError( "Backend does not support asynchronous operations." );
1415 }
1416
1417 return [];
1418 }
1419
1431 protected function sanitizeOpHeaders( array $op ) {
1432 static $longs = [ 'content-disposition' ];
1433
1434 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1435 $newHeaders = [];
1436 foreach ( $op['headers'] as $name => $value ) {
1437 $name = strtolower( $name );
1438 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1439 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1440 $this->logger->error( "Header '{header}' is too long.", [
1441 'filebackend' => $this->name,
1442 'header' => "$name: $value",
1443 ] );
1444 } else {
1445 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1446 }
1447 }
1448 $op['headers'] = $newHeaders;
1449 }
1450
1451 return $op;
1452 }
1453
1454 final public function preloadCache( array $paths ) {
1455 $fullConts = []; // full container names
1456 foreach ( $paths as $path ) {
1457 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1458 $fullConts[] = $fullCont;
1459 }
1460 // Load from the persistent file and container caches
1461 $this->primeContainerCache( $fullConts );
1462 $this->primeFileCache( $paths );
1463 }
1464
1465 final public function clearCache( array $paths = null ) {
1466 if ( is_array( $paths ) ) {
1467 $paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
1468 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1469 }
1470 if ( $paths === null ) {
1471 $this->cheapCache->clear();
1472 $this->expensiveCache->clear();
1473 } else {
1474 foreach ( $paths as $path ) {
1475 $this->cheapCache->clear( $path );
1476 $this->expensiveCache->clear( $path );
1477 }
1478 }
1479 $this->doClearCache( $paths );
1480 }
1481
1490 protected function doClearCache( array $paths = null ) {
1491 }
1492
1493 final public function preloadFileStat( array $params ) {
1495 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1496
1497 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1498 $stats = $this->doGetFileStatMulti( $params );
1499 if ( $stats === null ) {
1500 return true; // not supported
1501 }
1502
1503 // Whether this queried the backend in high consistency mode
1504 $latest = !empty( $params['latest'] );
1505
1506 return $this->ingestFreshFileStats( $stats, $latest );
1507 }
1508
1522 protected function doGetFileStatMulti( array $params ) {
1523 return null; // not supported
1524 }
1525
1533 abstract protected function directoriesAreVirtual();
1534
1545 final protected static function isValidShortContainerName( $container ) {
1546 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1547 // might be used by subclasses. Reserve the dot character.
1548 // The only way dots end up in containers (e.g. resolveStoragePath)
1549 // is due to the wikiId container prefix or the above suffixes.
1550 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1551 }
1552
1562 final protected static function isValidContainerName( $container ) {
1563 // This accounts for NTFS, Swift, and Ceph restrictions
1564 // and disallows directory separators or traversal characters.
1565 // Note that matching strings URL encode to the same string;
1566 // in Swift/Ceph, the length restriction is *after* URL encoding.
1567 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1568 }
1569
1583 final protected function resolveStoragePath( $storagePath ) {
1584 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1585 if ( $backend === $this->name ) { // must be for this backend
1586 $relPath = self::normalizeContainerPath( $relPath );
1587 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1588 // Get shard for the normalized path if this container is sharded
1589 $cShard = $this->getContainerShard( $shortCont, $relPath );
1590 // Validate and sanitize the relative path (backend-specific)
1591 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1592 if ( $relPath !== null ) {
1593 // Prepend any domain ID prefix to the container name
1594 $container = $this->fullContainerName( $shortCont );
1595 if ( self::isValidContainerName( $container ) ) {
1596 // Validate and sanitize the container name (backend-specific)
1597 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1598 if ( $container !== null ) {
1599 return [ $container, $relPath, $cShard ];
1600 }
1601 }
1602 }
1603 }
1604 }
1605
1606 return [ null, null, null ];
1607 }
1608
1624 final protected function resolveStoragePathReal( $storagePath ) {
1625 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1626 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1627 return [ $container, $relPath ];
1628 }
1629
1630 return [ null, null ];
1631 }
1632
1641 final protected function getContainerShard( $container, $relPath ) {
1642 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1643 if ( $levels == 1 || $levels == 2 ) {
1644 // Hash characters are either base 16 or 36
1645 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1646 // Get a regex that represents the shard portion of paths.
1647 // The concatenation of the captures gives us the shard.
1648 if ( $levels === 1 ) { // 16 or 36 shards per container
1649 $hashDirRegex = '(' . $char . ')';
1650 } else { // 256 or 1296 shards per container
1651 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1652 $hashDirRegex = $char . '/(' . $char . '{2})';
1653 } else { // short hash dir format (e.g. "a/b/c")
1654 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1655 }
1656 }
1657 // Allow certain directories to be above the hash dirs so as
1658 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1659 // They must be 2+ chars to avoid any hash directory ambiguity.
1660 $m = [];
1661 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1662 return '.' . implode( '', array_slice( $m, 1 ) );
1663 }
1664
1665 return null; // failed to match
1666 }
1667
1668 return ''; // no sharding
1669 }
1670
1679 final public function isSingleShardPathInternal( $storagePath ) {
1680 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1681
1682 return ( $shard !== null );
1683 }
1684
1693 final protected function getContainerHashLevels( $container ) {
1694 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1695 $config = $this->shardViaHashLevels[$container];
1696 $hashLevels = (int)$config['levels'];
1697 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1698 $hashBase = (int)$config['base'];
1699 if ( $hashBase == 16 || $hashBase == 36 ) {
1700 return [ $hashLevels, $hashBase, $config['repeat'] ];
1701 }
1702 }
1703 }
1704
1705 return [ 0, 0, false ]; // no sharding
1706 }
1707
1714 final protected function getContainerSuffixes( $container ) {
1715 $shards = [];
1716 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1717 if ( $digits > 0 ) {
1718 $numShards = $base ** $digits;
1719 for ( $index = 0; $index < $numShards; $index++ ) {
1720 $shards[] = '.' . Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1721 }
1722 }
1723
1724 return $shards;
1725 }
1726
1733 final protected function fullContainerName( $container ) {
1734 if ( $this->domainId != '' ) {
1735 return "{$this->domainId}-$container";
1736 } else {
1737 return $container;
1738 }
1739 }
1740
1750 protected function resolveContainerName( $container ) {
1751 return $container;
1752 }
1753
1765 protected function resolveContainerPath( $container, $relStoragePath ) {
1766 return $relStoragePath;
1767 }
1768
1775 private function containerCacheKey( $container ) {
1776 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1777 }
1778
1785 final protected function setContainerCache( $container, array $val ) {
1786 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1787 $this->logger->warning( "Unable to set stat cache for container {container}.",
1788 [ 'filebackend' => $this->name, 'container' => $container ]
1789 );
1790 }
1791 }
1792
1799 final protected function deleteContainerCache( $container ) {
1800 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1801 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1802 [ 'filebackend' => $this->name, 'container' => $container ]
1803 );
1804 }
1805 }
1806
1814 final protected function primeContainerCache( array $items ) {
1816 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1817
1818 $paths = []; // list of storage paths
1819 $contNames = []; // (cache key => resolved container name)
1820 // Get all the paths/containers from the items...
1821 foreach ( $items as $item ) {
1822 if ( self::isStoragePath( $item ) ) {
1823 $paths[] = $item;
1824 } elseif ( is_string( $item ) ) { // full container name
1825 $contNames[$this->containerCacheKey( $item )] = $item;
1826 }
1827 }
1828 // Get all the corresponding cache keys for paths...
1829 foreach ( $paths as $path ) {
1830 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1831 if ( $fullCont !== null ) { // valid path for this backend
1832 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1833 }
1834 }
1835
1836 $contInfo = []; // (resolved container name => cache value)
1837 // Get all cache entries for these container cache keys...
1838 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1839 foreach ( $values as $cacheKey => $val ) {
1840 $contInfo[$contNames[$cacheKey]] = $val;
1841 }
1842
1843 // Populate the container process cache for the backend...
1844 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1845 }
1846
1855 protected function doPrimeContainerCache( array $containerInfo ) {
1856 }
1857
1864 private function fileCacheKey( $path ) {
1865 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1866 }
1867
1876 final protected function setFileCache( $path, array $val ) {
1878 if ( $path === null ) {
1879 return; // invalid storage path
1880 }
1881 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1882 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1883 $key = $this->fileCacheKey( $path );
1884 // Set the cache unless it is currently salted.
1885 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1886 $this->logger->warning( "Unable to set stat cache for file {path}.",
1887 [ 'filebackend' => $this->name, 'path' => $path ]
1888 );
1889 }
1890 }
1891
1900 final protected function deleteFileCache( $path ) {
1902 if ( $path === null ) {
1903 return; // invalid storage path
1904 }
1905 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1906 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1907 [ 'filebackend' => $this->name, 'path' => $path ]
1908 );
1909 }
1910 }
1911
1919 final protected function primeFileCache( array $items ) {
1921 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1922
1923 $paths = []; // list of storage paths
1924 $pathNames = []; // (cache key => storage path)
1925 // Get all the paths/containers from the items...
1926 foreach ( $items as $item ) {
1927 if ( self::isStoragePath( $item ) ) {
1929 if ( $path !== null ) {
1930 $paths[] = $path;
1931 }
1932 }
1933 }
1934 // Get all the corresponding cache keys for paths...
1935 foreach ( $paths as $path ) {
1936 [ , $rel, ] = $this->resolveStoragePath( $path );
1937 if ( $rel !== null ) { // valid path for this backend
1938 $pathNames[$this->fileCacheKey( $path )] = $path;
1939 }
1940 }
1941 // Get all cache entries for these file cache keys.
1942 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1943 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1944 // Load all of the results into process cache...
1945 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1946 $path = $pathNames[$cacheKey];
1947 // This flag only applies to stat info loaded directly
1948 // from a high consistency backend query to the process cache
1949 unset( $stat['latest'] );
1950
1951 $this->cheapCache->setField( $path, 'stat', $stat );
1952 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1953 // Some backends store SHA-1 as metadata
1954 $this->cheapCache->setField(
1955 $path,
1956 'sha1',
1957 [ 'hash' => $stat['sha1'], 'latest' => false ]
1958 );
1959 }
1960 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1961 // Some backends store custom headers/metadata
1962 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1963 $this->cheapCache->setField(
1964 $path,
1965 'xattr',
1966 [ 'map' => $stat['xattr'], 'latest' => false ]
1967 );
1968 }
1969 }
1970 }
1971
1979 final protected static function normalizeXAttributes( array $xattr ) {
1980 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1981
1982 foreach ( $xattr['headers'] as $name => $value ) {
1983 $newXAttr['headers'][strtolower( $name )] = $value;
1984 }
1985
1986 foreach ( $xattr['metadata'] as $name => $value ) {
1987 $newXAttr['metadata'][strtolower( $name )] = $value;
1988 }
1989
1990 return $newXAttr;
1991 }
1992
1999 final protected function setConcurrencyFlags( array $opts ) {
2000 $opts['concurrency'] = 1; // off
2001 if ( $this->parallelize === 'implicit' ) {
2002 if ( $opts['parallelize'] ?? true ) {
2003 $opts['concurrency'] = $this->concurrency;
2004 }
2005 } elseif ( $this->parallelize === 'explicit' ) {
2006 if ( !empty( $opts['parallelize'] ) ) {
2007 $opts['concurrency'] = $this->concurrency;
2008 }
2009 }
2010
2011 return $opts;
2012 }
2013
2023 protected function getContentType( $storagePath, $content, $fsPath ) {
2024 if ( $this->mimeCallback ) {
2025 return call_user_func_array( $this->mimeCallback, func_get_args() );
2026 }
2027
2028 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2029 return $mime ?: 'unknown/unknown';
2030 }
2031}
array $params
The job parameters.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:85
A BagOStuff object with no objects in it.
Class representing a non-directory file on the file system.
Definition FSFile.php:32
static placeholderProps()
Placeholder file properties to use for files that don't exist.
Definition FSFile.php:150
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.
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
static normalizeContainerPath( $path)
Validate and normalize a relative storage path.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
getTopDirectoryList(array $params)
Same as FileBackend::getDirectoryList() except only lists directories that are immediately under the ...
scopedProfileSection( $section)
newStatus(... $args)
Yields the result of the status wrapper callback on either:
static normalizeStoragePath( $storagePath)
Normalize a storage path by cleaning up directory separators.
int $concurrency
How many operations can be done in parallel.
getLocalReference(array $params)
Returns a file system file, identical in content to the file at a storage path.
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.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Multi-datacenter aware caching interface.