Repository navigation
Improve S3 Directory Listing #973
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jfantinhardesty
wants to merge
18
commits into
main
Choose a base branch
from
cleanup-performance-improvements
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
62e4c1c
Cleanup getattr and truncate file cases in file cache
jfantinhardesty 44d197a
Create flag for getAttr headobject probe on file extension
jfantinhardesty b23d850
Refactor some code with checkCacheSpace function to simplify checking…
jfantinhardesty 1f3ea4a
Improve S3 rename file to possibly check for directory of same name w…
jfantinhardesty 7c2dc46
Merge branch 'main' into cleanup-performance-improvements
jfantinhardesty 3276d71
Fix lint and context errors
jfantinhardesty 3ab5dea
Remove unused function
jfantinhardesty df12bdb
Fix failing test
jfantinhardesty 28bdfa3
First pass at using new method to require dir markers for directory c…
jfantinhardesty 8e8b71f
Merge branch 'main' into cleanup-performance-improvements
jfantinhardesty 7715cd3
Fix error in truncate and other comments
jfantinhardesty c347970
Revert file_cache.go changes (already implemented mostly in another PR)
jfantinhardesty b68f954
Cleanup add-dir-marker command
jfantinhardesty c081ecc
Merge branch 'main' into cleanup-performance-improvements
jfantinhardesty bdbc832
Cleanup comments
jfantinhardesty b6b6552
Merge branch 'main' into cleanup-performance-improvements
jfantinhardesty b9962be
Merge branch 'main' into cleanup-performance-improvements
jfantinhardesty fdb0318
Add more comments, address Michael's feedback
jfantinhardesty File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,290 @@ | ||
| /* | ||
| Licensed under the MIT License <http://opensource.org/licenses/MIT>. | ||
|
|
||
| Copyright © 2026 Seagate Technology LLC and/or its Affiliates | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE | ||
| */ | ||
|
|
||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "github.com/Seagate/cloudfuse/common" | ||
| "github.com/Seagate/cloudfuse/common/config" | ||
| "github.com/Seagate/cloudfuse/common/log" | ||
| "github.com/Seagate/cloudfuse/component/s3storage" | ||
| "github.com/aws/aws-sdk-go-v2/aws" | ||
| "github.com/aws/aws-sdk-go-v2/service/s3" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| type addDirMarkersOptions struct { | ||
| dryRun bool | ||
| } | ||
|
|
||
| type markerScanResult struct { | ||
| objectsScanned int | ||
| markersAdded int | ||
| } | ||
|
|
||
| var addDirMarkersOpts addDirMarkersOptions | ||
|
|
||
| var addDirMarkersCmd = &cobra.Command{ | ||
| Use: "add-dir-markers", | ||
| Short: "Add missing directory markers to an S3 bucket.", | ||
| Long: "Scans the configured S3 bucket or subdirectory and creates zero-byte marker objects for every implied directory that does not already have one.", | ||
| GroupID: groupUtil, | ||
| Args: cobra.NoArgs, | ||
| Example: ` # Preview missing markers | ||
| cloudfuse add-dir-markers --config-file=config.yaml --dry-run | ||
|
|
||
| # Add the missing markers | ||
| cloudfuse add-dir-markers --config-file=config.yaml`, | ||
| RunE: runAddDirMarkers, | ||
| } | ||
|
|
||
| // runAddDirMarkers loads the s3storage config, builds an S3 client from it, and | ||
| // backfills any missing directory markers under the configured bucket/subdirectory. | ||
| func runAddDirMarkers(_ *cobra.Command, _ []string) error { | ||
| // Fall back to the default config file if one was not passed in | ||
| if options.ConfigFile == "" { | ||
| if _, err := os.Stat(common.DefaultConfigFilePath); err != nil { | ||
| if os.IsNotExist(err) { | ||
| return fmt.Errorf("config file not provided") | ||
| } | ||
| return fmt.Errorf("failed to inspect default config file: %w", err) | ||
| } | ||
| options.ConfigFile = common.DefaultConfigFilePath | ||
| } | ||
| if err := parseConfig(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| s3Options := s3storage.Options{} | ||
| if err := config.UnmarshalKey("s3storage", &s3Options); err != nil { | ||
| return fmt.Errorf("failed to read s3storage config: %w", err) | ||
| } | ||
| if strings.TrimSpace(s3Options.BucketName) == "" { | ||
| return fmt.Errorf("s3storage.bucket-name must be set in the config") | ||
| } | ||
|
|
||
| _ = log.SetDefaultLogger("silent", common.LogConfig{Level: common.ELogLevel.LOG_DEBUG()}) | ||
| comp := s3storage.News3storageComponent() | ||
| if err := comp.Configure(true); err != nil { | ||
| return fmt.Errorf("s3storage configure failed: %w", err) | ||
| } | ||
| if err := comp.Start(context.Background()); err != nil { | ||
| return fmt.Errorf("s3storage start failed: %w", err) | ||
| } | ||
| defer func() { _ = comp.Stop() }() | ||
|
|
||
| s3Component, ok := comp.(*s3storage.S3Storage) | ||
| if !ok { | ||
| return fmt.Errorf("unexpected s3storage component type") | ||
| } | ||
| client, ok := s3Component.Storage.(*s3storage.Client) | ||
| if !ok { | ||
| return fmt.Errorf("unexpected S3 client type") | ||
| } | ||
|
|
||
| var onMissingMarker func(string) | ||
| if addDirMarkersOpts.dryRun { | ||
| onMissingMarker = func(marker string) { | ||
| fmt.Fprintln(os.Stdout, marker) | ||
| } | ||
| } | ||
|
|
||
| result, err := backfillDirectoryMarkers( | ||
| context.Background(), | ||
| client.AwsS3Client, | ||
| s3Options.BucketName, | ||
| s3Options.PrefixPath, | ||
| addDirMarkersOpts.dryRun, | ||
| onMissingMarker, | ||
| ) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| action := "added" | ||
| if addDirMarkersOpts.dryRun { | ||
| action = "would add" | ||
| } | ||
| location := strings.Trim(s3Options.PrefixPath, "/") | ||
| if location == "" { | ||
| location = "<bucket root>" | ||
| } | ||
| fmt.Fprintf( | ||
| os.Stdout, | ||
| "Directory marker scan complete for %s/%s: scanned %d objects, %s %d markers.\n", | ||
| s3Options.BucketName, | ||
| location, | ||
| result.objectsScanned, | ||
| action, | ||
| result.markersAdded, | ||
| ) | ||
| return nil | ||
| } | ||
|
|
||
| // directoryMarkerS3API is the subset of the S3 client used by the backfill, | ||
| // so tests can substitute a fake. | ||
| type directoryMarkerS3API interface { | ||
| ListObjectsV2( | ||
| context.Context, | ||
| *s3.ListObjectsV2Input, | ||
| ...func(*s3.Options), | ||
| ) (*s3.ListObjectsV2Output, error) | ||
| PutObject( | ||
| context.Context, | ||
| *s3.PutObjectInput, | ||
| ...func(*s3.Options), | ||
| ) (*s3.PutObjectOutput, error) | ||
| } | ||
|
|
||
| // backfillDirectoryMarkers lists every object under prefix and creates a | ||
| // zero-byte "dir/" marker object for each implied parent directory that does not | ||
| // already have one. If dryRun is set, no objects are written. onMissingMarker, | ||
| // if not nil, is called with the key of each missing marker. | ||
| func backfillDirectoryMarkers( | ||
| ctx context.Context, | ||
| api directoryMarkerS3API, | ||
| bucket string, | ||
| prefix string, | ||
| dryRun bool, | ||
| onMissingMarker func(string), | ||
| ) (markerScanResult, error) { | ||
| result := markerScanResult{} | ||
| scanPrefix := strings.Trim(prefix, "/") | ||
| if scanPrefix != "" { | ||
| scanPrefix += "/" | ||
| } | ||
|
|
||
| // Markers known to exist (or already created) for the current key's ancestors | ||
| activeMarkers := make(map[string]struct{}) | ||
| var continuationToken *string | ||
| for { | ||
| output, err := api.ListObjectsV2(ctx, &s3.ListObjectsV2Input{ | ||
| Bucket: aws.String(bucket), | ||
| Prefix: aws.String(scanPrefix), | ||
| ContinuationToken: continuationToken, | ||
| }) | ||
| if err != nil { | ||
| return result, fmt.Errorf("failed to list objects under %q: %w", scanPrefix, err) | ||
| } | ||
| for _, object := range output.Contents { | ||
| if object.Key == nil { | ||
| continue | ||
| } | ||
| result.objectsScanned++ | ||
| key := aws.ToString(object.Key) | ||
| if scanPrefix != "" && !strings.HasPrefix(key, scanPrefix) { | ||
| continue | ||
| } | ||
|
|
||
| // Since keys are sorted, once a key falls outside a directory we will | ||
| // never see that directory again, so its marker can be forgotten. | ||
| for marker := range activeMarkers { | ||
| if !strings.HasPrefix(key, marker) { | ||
| delete(activeMarkers, marker) | ||
| } | ||
| } | ||
| if strings.HasSuffix(key, "/") { | ||
| activeMarkers[key] = struct{}{} | ||
| } | ||
|
|
||
| // Walk each parent directory of this key ("a/", "a/b/", ...) | ||
| // and create a marker for any that we have not seen yet. | ||
| for i := 0; i < len(key); i++ { | ||
| if key[i] != '/' { | ||
| continue | ||
| } | ||
| marker := key[:i+1] | ||
| // Skip directories above the configured subdirectory | ||
| if len(marker) < len(scanPrefix) { | ||
| continue | ||
| } | ||
| if _, found := activeMarkers[marker]; found { | ||
| continue | ||
| } | ||
|
|
||
| activeMarkers[marker] = struct{}{} | ||
| if onMissingMarker != nil { | ||
| onMissingMarker(marker) | ||
| } | ||
| if !dryRun { | ||
| _, err := api.PutObject(ctx, &s3.PutObjectInput{ | ||
| Bucket: aws.String(bucket), | ||
| Key: aws.String(marker), | ||
| Body: bytes.NewReader(nil), | ||
| ContentLength: aws.Int64(0), | ||
| }) | ||
| if err != nil { | ||
| return result, fmt.Errorf( | ||
| "failed to create directory marker %q: %w", | ||
| marker, | ||
| err, | ||
| ) | ||
| } | ||
| } | ||
| result.markersAdded++ | ||
| } | ||
| } | ||
| if !aws.ToBool(output.IsTruncated) { | ||
| break | ||
| } | ||
| if output.NextContinuationToken == nil || *output.NextContinuationToken == "" { | ||
| return result, fmt.Errorf( | ||
| "S3 returned a truncated listing without a continuation token", | ||
| ) | ||
| } | ||
| continuationToken = output.NextContinuationToken | ||
| } | ||
|
|
||
| return result, nil | ||
| } | ||
|
|
||
| func init() { | ||
| rootCmd.AddCommand(addDirMarkersCmd) | ||
| addDirMarkersCmd.Flags().StringVarP( | ||
| &options.ConfigFile, | ||
| "config-file", | ||
| "c", | ||
| "", | ||
| "Path to cloudfuse config file (default: ./config.yaml)", | ||
| ) | ||
| addDirMarkersCmd.Flags().StringVarP( | ||
| &options.PassPhrase, | ||
| "passphrase", | ||
| "p", | ||
| "", | ||
| "Base64 encoded key used to decrypt an encrypted config file.", | ||
| ) | ||
| addDirMarkersCmd.Flags().BoolVar( | ||
| &addDirMarkersOpts.dryRun, | ||
| "dry-run", | ||
| false, | ||
| "List missing markers without creating them", | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.