MediaWiki 1.42.0-rc.0
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 [
1069 'obResetFunc' => $this->obResetFunc,
1070 'streamMimeFunc' => $this->streamMimeFunc
1071 ]
1072 );
1073 $res = $streamer->stream( $params['headers'], true, $params['options'], $flags );
1074 } else {
1075 $res = false;
1076 HTTPFileStreamer::send404Message( $params['src'], $flags );
1077 }
1078
1079 if ( !$res ) {
1080 $status->fatal( 'backend-fail-stream', $params['src'] );
1081 }
1082
1083 return $status;
1084 }
1085
1086 final public function directoryExists( array $params ) {
1087 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1088 if ( $dir === null ) {
1089 return self::EXISTENCE_ERROR; // invalid storage path
1090 }
1091 if ( $shard !== null ) { // confined to a single container/shard
1092 return $this->doDirectoryExists( $fullCont, $dir, $params );
1093 } else { // directory is on several shards
1094 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1095 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1096 $res = false; // response
1097 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1098 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
1099 if ( $exists === true ) {
1100 $res = true;
1101 break; // found one!
1102 } elseif ( $exists === self::RES_ERROR ) {
1103 $res = self::EXISTENCE_ERROR;
1104 }
1105 }
1106
1107 return $res;
1108 }
1109 }
1110
1119 abstract protected function doDirectoryExists( $container, $dir, array $params );
1120
1121 final public function getDirectoryList( array $params ) {
1122 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1123 if ( $dir === null ) {
1124 return self::EXISTENCE_ERROR; // invalid storage path
1125 }
1126 if ( $shard !== null ) {
1127 // File listing is confined to a single container/shard
1128 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
1129 } else {
1130 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1131 // File listing spans multiple containers/shards
1132 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1133
1134 return new FileBackendStoreShardDirIterator( $this,
1135 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1136 }
1137 }
1138
1149 abstract public function getDirectoryListInternal( $container, $dir, array $params );
1150
1151 final public function getFileList( array $params ) {
1152 [ $fullCont, $dir, $shard ] = $this->resolveStoragePath( $params['dir'] );
1153 if ( $dir === null ) {
1154 return self::LIST_ERROR; // invalid storage path
1155 }
1156 if ( $shard !== null ) {
1157 // File listing is confined to a single container/shard
1158 return $this->getFileListInternal( $fullCont, $dir, $params );
1159 } else {
1160 $this->logger->debug( __METHOD__ . ": iterating over all container shards." );
1161 // File listing spans multiple containers/shards
1162 [ , $shortCont, ] = self::splitStoragePath( $params['dir'] );
1163
1164 return new FileBackendStoreShardFileIterator( $this,
1165 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1166 }
1167 }
1168
1179 abstract public function getFileListInternal( $container, $dir, array $params );
1180
1192 final public function getOperationsInternal( array $ops ) {
1193 $supportedOps = [
1194 'store' => StoreFileOp::class,
1195 'copy' => CopyFileOp::class,
1196 'move' => MoveFileOp::class,
1197 'delete' => DeleteFileOp::class,
1198 'create' => CreateFileOp::class,
1199 'describe' => DescribeFileOp::class,
1200 'null' => NullFileOp::class
1201 ];
1202
1203 $performOps = []; // array of FileOp objects
1204 // Build up ordered array of FileOps...
1205 foreach ( $ops as $operation ) {
1206 $opName = $operation['op'];
1207 if ( isset( $supportedOps[$opName] ) ) {
1208 $class = $supportedOps[$opName];
1209 // Get params for this operation
1210 $params = $operation;
1211 // Append the FileOp class
1212 $performOps[] = new $class( $this, $params, $this->logger );
1213 } else {
1214 throw new FileBackendError( "Operation '$opName' is not supported." );
1215 }
1216 }
1217
1218 return $performOps;
1219 }
1220
1231 final public function getPathsToLockForOpsInternal( array $performOps ) {
1232 // Build up a list of files to lock...
1233 $paths = [ 'sh' => [], 'ex' => [] ];
1234 foreach ( $performOps as $fileOp ) {
1235 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
1236 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
1237 }
1238 // Optimization: if doing an EX lock anyway, don't also set an SH one
1239 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
1240 // Get a shared lock on the parent directory of each path changed
1241 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
1242
1243 return [
1244 LockManager::LOCK_UW => $paths['sh'],
1245 LockManager::LOCK_EX => $paths['ex']
1246 ];
1247 }
1248
1249 public function getScopedLocksForOps( array $ops, StatusValue $status ) {
1250 $paths = $this->getPathsToLockForOpsInternal( $this->getOperationsInternal( $ops ) );
1251
1252 return $this->getScopedFileLocks( $paths, 'mixed', $status );
1253 }
1254
1255 final protected function doOperationsInternal( array $ops, array $opts ) {
1257 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1258 $status = $this->newStatus();
1259
1260 // Fix up custom header name/value pairs
1261 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1262 // Build up a list of FileOps and involved paths
1263 $fileOps = $this->getOperationsInternal( $ops );
1264 $pathsUsed = [];
1265 foreach ( $fileOps as $fileOp ) {
1266 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1267 }
1268
1269 // Acquire any locks as needed for the scope of this function
1270 if ( empty( $opts['nonLocking'] ) ) {
1271 $pathsByLockType = $this->getPathsToLockForOpsInternal( $fileOps );
1273 $scopeLock = $this->getScopedFileLocks( $pathsByLockType, 'mixed', $status );
1274 if ( !$status->isOK() ) {
1275 return $status; // abort
1276 }
1277 }
1278
1279 // Clear any file cache entries (after locks acquired)
1280 if ( empty( $opts['preserveCache'] ) ) {
1281 $this->clearCache( $pathsUsed );
1282 }
1283
1284 // Enlarge the cache to fit the stat entries of these files
1285 $this->cheapCache->setMaxSize( max( 2 * count( $pathsUsed ), self::CACHE_CHEAP_SIZE ) );
1286
1287 // Load from the persistent container caches
1288 $this->primeContainerCache( $pathsUsed );
1289 // Get the latest stat info for all the files (having locked them)
1290 $ok = $this->preloadFileStat( [ 'srcs' => $pathsUsed, 'latest' => true ] );
1291
1292 if ( $ok ) {
1293 // Actually attempt the operation batch...
1294 $opts = $this->setConcurrencyFlags( $opts );
1295 $subStatus = FileOpBatch::attempt( $fileOps, $opts );
1296 } else {
1297 // If we could not even stat some files, then bail out
1298 $subStatus = $this->newStatus( 'backend-fail-internal', $this->name );
1299 foreach ( $ops as $i => $op ) { // mark each op as failed
1300 $subStatus->success[$i] = false;
1301 ++$subStatus->failCount;
1302 }
1303 $this->logger->error( static::class . "-{$this->name} " .
1304 " stat failure; aborted operations: " . FormatJson::encode( $ops ) );
1305 }
1306
1307 // Merge errors into StatusValue fields
1308 $status->merge( $subStatus );
1309 $status->success = $subStatus->success; // not done in merge()
1310
1311 // Shrink the stat cache back to normal size
1312 $this->cheapCache->setMaxSize( self::CACHE_CHEAP_SIZE );
1313
1314 return $status;
1315 }
1316
1317 final protected function doQuickOperationsInternal( array $ops, array $opts ) {
1319 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1320 $status = $this->newStatus();
1321
1322 // Fix up custom header name/value pairs
1323 $ops = array_map( [ $this, 'sanitizeOpHeaders' ], $ops );
1324 // Build up a list of FileOps and involved paths
1325 $fileOps = $this->getOperationsInternal( $ops );
1326 $pathsUsed = [];
1327 foreach ( $fileOps as $fileOp ) {
1328 $pathsUsed = array_merge( $pathsUsed, $fileOp->storagePathsReadOrChanged() );
1329 }
1330
1331 // Clear any file cache entries for involved paths
1332 $this->clearCache( $pathsUsed );
1333
1334 // Parallel ops may be disabled in config due to dependencies (e.g. needing popen())
1335 $async = ( $this->parallelize === 'implicit' && count( $ops ) > 1 );
1336 $maxConcurrency = $this->concurrency; // throttle
1338 $statuses = []; // array of (index => StatusValue)
1340 $batch = [];
1341 foreach ( $fileOps as $index => $fileOp ) {
1342 $subStatus = $async
1343 ? $fileOp->attemptAsyncQuick()
1344 : $fileOp->attemptQuick();
1345 if ( $subStatus->value instanceof FileBackendStoreOpHandle ) { // async
1346 if ( count( $batch ) >= $maxConcurrency ) {
1347 // Execute this batch. Don't queue any more ops since they contain
1348 // open filehandles which are a limited resource (T230245).
1349 $statuses += $this->executeOpHandlesInternal( $batch );
1350 $batch = [];
1351 }
1352 $batch[$index] = $subStatus->value; // keep index
1353 } else { // error or completed
1354 $statuses[$index] = $subStatus; // keep index
1355 }
1356 }
1357 if ( count( $batch ) ) {
1358 $statuses += $this->executeOpHandlesInternal( $batch );
1359 }
1360 // Marshall and merge all the responses...
1361 foreach ( $statuses as $index => $subStatus ) {
1362 $status->merge( $subStatus );
1363 if ( $subStatus->isOK() ) {
1364 $status->success[$index] = true;
1365 ++$status->successCount;
1366 } else {
1367 $status->success[$index] = false;
1368 ++$status->failCount;
1369 }
1370 }
1371
1372 $this->clearCache( $pathsUsed );
1373
1374 return $status;
1375 }
1376
1386 final public function executeOpHandlesInternal( array $fileOpHandles ) {
1388 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1389
1390 foreach ( $fileOpHandles as $fileOpHandle ) {
1391 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle ) ) {
1392 throw new InvalidArgumentException( "Expected FileBackendStoreOpHandle object." );
1393 } elseif ( $fileOpHandle->backend->getName() !== $this->getName() ) {
1394 throw new InvalidArgumentException( "Expected handle for this file backend." );
1395 }
1396 }
1397
1398 $statuses = $this->doExecuteOpHandlesInternal( $fileOpHandles );
1399 foreach ( $fileOpHandles as $fileOpHandle ) {
1400 $fileOpHandle->closeResources();
1401 }
1402
1403 return $statuses;
1404 }
1405
1415 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1416 if ( count( $fileOpHandles ) ) {
1417 throw new FileBackendError( "Backend does not support asynchronous operations." );
1418 }
1419
1420 return [];
1421 }
1422
1434 protected function sanitizeOpHeaders( array $op ) {
1435 static $longs = [ 'content-disposition' ];
1436
1437 if ( isset( $op['headers'] ) ) { // op sets HTTP headers
1438 $newHeaders = [];
1439 foreach ( $op['headers'] as $name => $value ) {
1440 $name = strtolower( $name );
1441 $maxHVLen = in_array( $name, $longs ) ? INF : 255;
1442 if ( strlen( $name ) > 255 || strlen( $value ) > $maxHVLen ) {
1443 $this->logger->error( "Header '{header}' is too long.", [
1444 'filebackend' => $this->name,
1445 'header' => "$name: $value",
1446 ] );
1447 } else {
1448 $newHeaders[$name] = strlen( $value ) ? $value : ''; // null/false => ""
1449 }
1450 }
1451 $op['headers'] = $newHeaders;
1452 }
1453
1454 return $op;
1455 }
1456
1457 final public function preloadCache( array $paths ) {
1458 $fullConts = []; // full container names
1459 foreach ( $paths as $path ) {
1460 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1461 $fullConts[] = $fullCont;
1462 }
1463 // Load from the persistent file and container caches
1464 $this->primeContainerCache( $fullConts );
1465 $this->primeFileCache( $paths );
1466 }
1467
1468 final public function clearCache( array $paths = null ) {
1469 if ( is_array( $paths ) ) {
1470 $paths = array_map( [ FileBackend::class, 'normalizeStoragePath' ], $paths );
1471 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1472 }
1473 if ( $paths === null ) {
1474 $this->cheapCache->clear();
1475 $this->expensiveCache->clear();
1476 } else {
1477 foreach ( $paths as $path ) {
1478 $this->cheapCache->clear( $path );
1479 $this->expensiveCache->clear( $path );
1480 }
1481 }
1482 $this->doClearCache( $paths );
1483 }
1484
1493 protected function doClearCache( array $paths = null ) {
1494 }
1495
1496 final public function preloadFileStat( array $params ) {
1498 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1499
1500 $params['concurrency'] = ( $this->parallelize !== 'off' ) ? $this->concurrency : 1;
1501 $stats = $this->doGetFileStatMulti( $params );
1502 if ( $stats === null ) {
1503 return true; // not supported
1504 }
1505
1506 // Whether this queried the backend in high consistency mode
1507 $latest = !empty( $params['latest'] );
1508
1509 return $this->ingestFreshFileStats( $stats, $latest );
1510 }
1511
1525 protected function doGetFileStatMulti( array $params ) {
1526 return null; // not supported
1527 }
1528
1536 abstract protected function directoriesAreVirtual();
1537
1548 final protected static function isValidShortContainerName( $container ) {
1549 // Suffixes like '.xxx' (hex shard chars) or '.seg' (file segments)
1550 // might be used by subclasses. Reserve the dot character.
1551 // The only way dots end up in containers (e.g. resolveStoragePath)
1552 // is due to the wikiId container prefix or the above suffixes.
1553 return self::isValidContainerName( $container ) && !preg_match( '/[.]/', $container );
1554 }
1555
1565 final protected static function isValidContainerName( $container ) {
1566 // This accounts for NTFS, Swift, and Ceph restrictions
1567 // and disallows directory separators or traversal characters.
1568 // Note that matching strings URL encode to the same string;
1569 // in Swift/Ceph, the length restriction is *after* URL encoding.
1570 return (bool)preg_match( '/^[a-z0-9][a-z0-9-_.]{0,199}$/i', $container );
1571 }
1572
1586 final protected function resolveStoragePath( $storagePath ) {
1587 [ $backend, $shortCont, $relPath ] = self::splitStoragePath( $storagePath );
1588 if ( $backend === $this->name ) { // must be for this backend
1589 $relPath = self::normalizeContainerPath( $relPath );
1590 if ( $relPath !== null && self::isValidShortContainerName( $shortCont ) ) {
1591 // Get shard for the normalized path if this container is sharded
1592 $cShard = $this->getContainerShard( $shortCont, $relPath );
1593 // Validate and sanitize the relative path (backend-specific)
1594 $relPath = $this->resolveContainerPath( $shortCont, $relPath );
1595 if ( $relPath !== null ) {
1596 // Prepend any domain ID prefix to the container name
1597 $container = $this->fullContainerName( $shortCont );
1598 if ( self::isValidContainerName( $container ) ) {
1599 // Validate and sanitize the container name (backend-specific)
1600 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1601 if ( $container !== null ) {
1602 return [ $container, $relPath, $cShard ];
1603 }
1604 }
1605 }
1606 }
1607 }
1608
1609 return [ null, null, null ];
1610 }
1611
1627 final protected function resolveStoragePathReal( $storagePath ) {
1628 [ $container, $relPath, $cShard ] = $this->resolveStoragePath( $storagePath );
1629 if ( $cShard !== null && substr( $relPath, -1 ) !== '/' ) {
1630 return [ $container, $relPath ];
1631 }
1632
1633 return [ null, null ];
1634 }
1635
1644 final protected function getContainerShard( $container, $relPath ) {
1645 [ $levels, $base, $repeat ] = $this->getContainerHashLevels( $container );
1646 if ( $levels == 1 || $levels == 2 ) {
1647 // Hash characters are either base 16 or 36
1648 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1649 // Get a regex that represents the shard portion of paths.
1650 // The concatenation of the captures gives us the shard.
1651 if ( $levels === 1 ) { // 16 or 36 shards per container
1652 $hashDirRegex = '(' . $char . ')';
1653 } else { // 256 or 1296 shards per container
1654 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1655 $hashDirRegex = $char . '/(' . $char . '{2})';
1656 } else { // short hash dir format (e.g. "a/b/c")
1657 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1658 }
1659 }
1660 // Allow certain directories to be above the hash dirs so as
1661 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1662 // They must be 2+ chars to avoid any hash directory ambiguity.
1663 $m = [];
1664 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1665 return '.' . implode( '', array_slice( $m, 1 ) );
1666 }
1667
1668 return null; // failed to match
1669 }
1670
1671 return ''; // no sharding
1672 }
1673
1682 final public function isSingleShardPathInternal( $storagePath ) {
1683 [ , , $shard ] = $this->resolveStoragePath( $storagePath );
1684
1685 return ( $shard !== null );
1686 }
1687
1696 final protected function getContainerHashLevels( $container ) {
1697 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1698 $config = $this->shardViaHashLevels[$container];
1699 $hashLevels = (int)$config['levels'];
1700 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1701 $hashBase = (int)$config['base'];
1702 if ( $hashBase == 16 || $hashBase == 36 ) {
1703 return [ $hashLevels, $hashBase, $config['repeat'] ];
1704 }
1705 }
1706 }
1707
1708 return [ 0, 0, false ]; // no sharding
1709 }
1710
1717 final protected function getContainerSuffixes( $container ) {
1718 $shards = [];
1719 [ $digits, $base ] = $this->getContainerHashLevels( $container );
1720 if ( $digits > 0 ) {
1721 $numShards = $base ** $digits;
1722 for ( $index = 0; $index < $numShards; $index++ ) {
1723 $shards[] = '.' . Wikimedia\base_convert( (string)$index, 10, $base, $digits );
1724 }
1725 }
1726
1727 return $shards;
1728 }
1729
1736 final protected function fullContainerName( $container ) {
1737 if ( $this->domainId != '' ) {
1738 return "{$this->domainId}-$container";
1739 } else {
1740 return $container;
1741 }
1742 }
1743
1753 protected function resolveContainerName( $container ) {
1754 return $container;
1755 }
1756
1768 protected function resolveContainerPath( $container, $relStoragePath ) {
1769 return $relStoragePath;
1770 }
1771
1778 private function containerCacheKey( $container ) {
1779 return "filebackend:{$this->name}:{$this->domainId}:container:{$container}";
1780 }
1781
1788 final protected function setContainerCache( $container, array $val ) {
1789 if ( !$this->memCache->set( $this->containerCacheKey( $container ), $val, 14 * 86400 ) ) {
1790 $this->logger->warning( "Unable to set stat cache for container {container}.",
1791 [ 'filebackend' => $this->name, 'container' => $container ]
1792 );
1793 }
1794 }
1795
1802 final protected function deleteContainerCache( $container ) {
1803 if ( !$this->memCache->delete( $this->containerCacheKey( $container ), 300 ) ) {
1804 $this->logger->warning( "Unable to delete stat cache for container {container}.",
1805 [ 'filebackend' => $this->name, 'container' => $container ]
1806 );
1807 }
1808 }
1809
1817 final protected function primeContainerCache( array $items ) {
1819 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1820
1821 $paths = []; // list of storage paths
1822 $contNames = []; // (cache key => resolved container name)
1823 // Get all the paths/containers from the items...
1824 foreach ( $items as $item ) {
1825 if ( self::isStoragePath( $item ) ) {
1826 $paths[] = $item;
1827 } elseif ( is_string( $item ) ) { // full container name
1828 $contNames[$this->containerCacheKey( $item )] = $item;
1829 }
1830 }
1831 // Get all the corresponding cache keys for paths...
1832 foreach ( $paths as $path ) {
1833 [ $fullCont, , ] = $this->resolveStoragePath( $path );
1834 if ( $fullCont !== null ) { // valid path for this backend
1835 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1836 }
1837 }
1838
1839 $contInfo = []; // (resolved container name => cache value)
1840 // Get all cache entries for these container cache keys...
1841 $values = $this->memCache->getMulti( array_keys( $contNames ) );
1842 foreach ( $values as $cacheKey => $val ) {
1843 $contInfo[$contNames[$cacheKey]] = $val;
1844 }
1845
1846 // Populate the container process cache for the backend...
1847 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1848 }
1849
1858 protected function doPrimeContainerCache( array $containerInfo ) {
1859 }
1860
1867 private function fileCacheKey( $path ) {
1868 return "filebackend:{$this->name}:{$this->domainId}:file:" . sha1( $path );
1869 }
1870
1879 final protected function setFileCache( $path, array $val ) {
1881 if ( $path === null ) {
1882 return; // invalid storage path
1883 }
1884 $mtime = (int)ConvertibleTimestamp::convert( TS_UNIX, $val['mtime'] );
1885 $ttl = $this->memCache->adaptiveTTL( $mtime, 7 * 86400, 300, 0.1 );
1886 $key = $this->fileCacheKey( $path );
1887 // Set the cache unless it is currently salted.
1888 if ( !$this->memCache->set( $key, $val, $ttl ) ) {
1889 $this->logger->warning( "Unable to set stat cache for file {path}.",
1890 [ 'filebackend' => $this->name, 'path' => $path ]
1891 );
1892 }
1893 }
1894
1903 final protected function deleteFileCache( $path ) {
1905 if ( $path === null ) {
1906 return; // invalid storage path
1907 }
1908 if ( !$this->memCache->delete( $this->fileCacheKey( $path ), 300 ) ) {
1909 $this->logger->warning( "Unable to delete stat cache for file {path}.",
1910 [ 'filebackend' => $this->name, 'path' => $path ]
1911 );
1912 }
1913 }
1914
1922 final protected function primeFileCache( array $items ) {
1924 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1925
1926 $paths = []; // list of storage paths
1927 $pathNames = []; // (cache key => storage path)
1928 // Get all the paths/containers from the items...
1929 foreach ( $items as $item ) {
1930 if ( self::isStoragePath( $item ) ) {
1932 if ( $path !== null ) {
1933 $paths[] = $path;
1934 }
1935 }
1936 }
1937 // Get all the corresponding cache keys for paths...
1938 foreach ( $paths as $path ) {
1939 [ , $rel, ] = $this->resolveStoragePath( $path );
1940 if ( $rel !== null ) { // valid path for this backend
1941 $pathNames[$this->fileCacheKey( $path )] = $path;
1942 }
1943 }
1944 // Get all cache entries for these file cache keys.
1945 // Note that negatives are not cached by getFileStat()/preloadFileStat().
1946 $values = $this->memCache->getMulti( array_keys( $pathNames ) );
1947 // Load all of the results into process cache...
1948 foreach ( array_filter( $values, 'is_array' ) as $cacheKey => $stat ) {
1949 $path = $pathNames[$cacheKey];
1950 // This flag only applies to stat info loaded directly
1951 // from a high consistency backend query to the process cache
1952 unset( $stat['latest'] );
1953
1954 $this->cheapCache->setField( $path, 'stat', $stat );
1955 if ( isset( $stat['sha1'] ) && strlen( $stat['sha1'] ) == 31 ) {
1956 // Some backends store SHA-1 as metadata
1957 $this->cheapCache->setField(
1958 $path,
1959 'sha1',
1960 [ 'hash' => $stat['sha1'], 'latest' => false ]
1961 );
1962 }
1963 if ( isset( $stat['xattr'] ) && is_array( $stat['xattr'] ) ) {
1964 // Some backends store custom headers/metadata
1965 $stat['xattr'] = self::normalizeXAttributes( $stat['xattr'] );
1966 $this->cheapCache->setField(
1967 $path,
1968 'xattr',
1969 [ 'map' => $stat['xattr'], 'latest' => false ]
1970 );
1971 }
1972 }
1973 }
1974
1982 final protected static function normalizeXAttributes( array $xattr ) {
1983 $newXAttr = [ 'headers' => [], 'metadata' => [] ];
1984
1985 foreach ( $xattr['headers'] as $name => $value ) {
1986 $newXAttr['headers'][strtolower( $name )] = $value;
1987 }
1988
1989 foreach ( $xattr['metadata'] as $name => $value ) {
1990 $newXAttr['metadata'][strtolower( $name )] = $value;
1991 }
1992
1993 return $newXAttr;
1994 }
1995
2002 final protected function setConcurrencyFlags( array $opts ) {
2003 $opts['concurrency'] = 1; // off
2004 if ( $this->parallelize === 'implicit' ) {
2005 if ( $opts['parallelize'] ?? true ) {
2006 $opts['concurrency'] = $this->concurrency;
2007 }
2008 } elseif ( $this->parallelize === 'explicit' ) {
2009 if ( !empty( $opts['parallelize'] ) ) {
2010 $opts['concurrency'] = $this->concurrency;
2011 }
2012 }
2013
2014 return $opts;
2015 }
2016
2026 protected function getContentType( $storagePath, $content, $fsPath ) {
2027 if ( $this->mimeCallback ) {
2028 return call_user_func_array( $this->mimeCallback, func_get_args() );
2029 }
2030
2031 $mime = ( $fsPath !== null ) ? mime_content_type( $fsPath ) : false;
2032 return $mime ?: 'unknown/unknown';
2033 }
2034}
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.