From a875a49189ca86280b4edddbf689856bafc64d3c Mon Sep 17 00:00:00 2001 From: francisco souza <108725+fsouza@users.noreply.github.com> Date: Tue, 1 Aug 2023 13:54:50 -0300 Subject: [PATCH] backend/fs: return empty BucketAttrs if the metadata file is missing This keeps the server compatible with the directory structure from versions older than 1.46.0. Closes #1271. --- internal/backend/fs.go | 3 ++ internal/backend/fs_test.go | 76 +++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 internal/backend/fs_test.go diff --git a/internal/backend/fs.go b/internal/backend/fs.go index 688927dae4..64f1106820 100644 --- a/internal/backend/fs.go +++ b/internal/backend/fs.go @@ -159,6 +159,9 @@ func (s *storageFS) GetBucket(name string) (Bucket, error) { func getBucketAttributes(path string) (BucketAttrs, error) { content, err := os.ReadFile(path + bucketMetadataSuffix) if err != nil { + if os.IsNotExist(err) { + return BucketAttrs{}, nil + } return BucketAttrs{}, err } var attrs BucketAttrs diff --git a/internal/backend/fs_test.go b/internal/backend/fs_test.go new file mode 100644 index 0000000000..d946de62ec --- /dev/null +++ b/internal/backend/fs_test.go @@ -0,0 +1,76 @@ +// Copyright 2023 Francisco Souza. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package backend + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestGetAttributes(t *testing.T) { + t.Parallel() + + tempDir := t.TempDir() + testBucket := filepath.Join(tempDir, "some-bucket") + bucketAttrs := BucketAttrs{ + DefaultEventBasedHold: false, + VersioningEnabled: true, + } + data, _ := json.Marshal(bucketAttrs) + err := os.WriteFile(testBucket+bucketMetadataSuffix, data, 0o644) + if err != nil { + t.Fatal(err) + } + notABucket := filepath.Join(tempDir, "not-a-bucket") + err = os.WriteFile(notABucket+bucketMetadataSuffix, []byte("this is not valid json"), 0o644) + if err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + inputPath string + expectedAttrs BucketAttrs + expectErr bool + }{ + { + name: "file not found", + inputPath: filepath.Join(tempDir, "unknown-bucket"), + }, + { + name: "existing bucket", + inputPath: testBucket, + expectedAttrs: bucketAttrs, + }, + { + name: "invalid file", + inputPath: notABucket, + expectErr: true, + }, + } + + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + t.Parallel() + attrs, err := getBucketAttributes(test.inputPath) + if test.expectErr && err == nil { + t.Fatal("expected error, but got ") + } + + if !test.expectErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if diff := cmp.Diff(attrs, test.expectedAttrs); diff != "" { + t.Errorf("incorrect attributes returned\nwant: %#v\ngot: %#v\ndiff: %s", test.expectedAttrs, attrs, diff) + } + }) + } +}