From feb488a84dfe971e4c5770da5ff8fe08cc2621f8 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Tue, 24 Nov 2026 15:25:00 -0800 Subject: [PATCH] s3api: create the stored object's missing directory before a recovery answers success (#12963) * s3api: create a recovered PUT's missing directory The filer stores a new entry before its parent directories, and a parent that fails to insert leaves the entry stored with an error returned. Both PUT recoveries then find the stored entry and answer success, so the object reads by key but no listing shows it, and an overwrite takes the filer's existing-entry branch, which creates no parents either. Before claiming the stored entry, create its directory when it is missing, and answer an error when that fails. Co-Authored-By: Claude Opus 5.5 * s3api: create a committed completion's missing directory A CompleteMultipartUpload whose commit stored the object but failed on its parent directory answered success through the committed-despite branch, and a retry that finds the committed object answered success the same way. Both now create the object's directory first and fail while it cannot be created; the upload directory is kept, so the retry can finish the job. Co-Authored-By: Claude Opus 5.5 * s3api: test recoveries that create the stored object's directory Co-Authored-By: Claude Opus 5.5 * s3api: check every directory level when repairing an object's parent A repair mkdir stores the directory it creates before that directory's own parents, so a failure there can leave a lower level stored without its parent, and a retry that saw the lower level answered success. Walk from the bucket down and create each missing level. A file left by a failed prefix-object promotion is not a directory a listing descends, so it fails the repair rather than passing as an existing directory. Co-Authored-By: Claude Opus 5.5 * s3api: free unused parts when a completion's directory repair fails The early return skipped the cleanup of parts the committed object does not use, and the retry that finds the commit removes the remaining entries metadata-only, so the unused parts' data leaked. Run that cleanup and keep only the upload directory for the retry. Co-Authored-By: Claude Opus 5.5 * s3api: test the per-level parent repair and the failed repair's cleanup Co-Authored-By: Claude Opus 5.5 * s3api: bound the parent repair with the recovery's lookup budget The repair's filer calls ran on a background context, so a filer that stopped answering held the object write lock without a deadline. The PUT recoveries pass their lookup context, and the completion gives the repair the same createLookupTimeout. Co-Authored-By: Claude Opus 5.5 * s3api: fail the parent repair when the bucket directory is missing The filer creates missing ancestors for a directory create, so walking down from an absent bucket directory would recreate a bucket deleted during the write as a plain directory. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/s3api/filer_multipart.go | 26 +- weed/s3api/filer_util.go | 40 +++ weed/s3api/s3api_object_handlers_put.go | 8 + .../s3api_object_parent_recovery_test.go | 232 ++++++++++++++++++ 4 files changed, 303 insertions(+), 3 deletions(-) create mode 100644 weed/s3api/s3api_object_parent_recovery_test.go diff --git a/weed/s3api/filer_multipart.go b/weed/s3api/filer_multipart.go index 87face0a47..f273552682 100644 --- a/weed/s3api/filer_multipart.go +++ b/weed/s3api/filer_multipart.go @@ -389,6 +389,12 @@ func applyMultipartSSES3HeadersFromUploadEntry(dst *filer_pb.Entry, sses3Info *m func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *s3.CompleteMultipartUploadInput, parts *CompleteMultipartUpload, uploadDirectory, entryName, dirName string, completedPartNumbers []int, completedPartMap map[int][]string, maxPartNo int) (*multipartCompletionState, *CompleteMultipartUploadResult, s3err.ErrorCode) { if output, _ := s3a.committedCompletion(r, input); output != nil { + parentCtx, cancel := context.WithTimeout(context.Background(), createLookupTimeout) + defer cancel() + if err := s3a.ensureObjectParent(parentCtx, *input.Bucket, dirName); err != nil { + glog.Errorf("completeMultipartUpload %s/%s: committed object's directory %s is missing: %v", *input.Bucket, *input.Key, dirName, err) + return nil, nil, s3err.ErrInternalError + } cleanupEntries, _, cleanupErr := s3a.uploadFiler(*input.Bucket, *input.Key).list(uploadDirectory, "", "", false, s3_constants.MaxS3MultipartParts+1) if cleanupErr != nil && !errors.Is(cleanupErr, filer_pb.ErrNotFound) { glog.Warningf("completeMultipartUpload: failed to list stale upload directory %s for cleanup: %v", uploadDirectory, cleanupErr) @@ -1045,6 +1051,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl return s3a.checkConditionalHeaders(r, *input.Bucket, *input.Key) }, completionBody) } + var parentErr error if finalizeCode != s3err.ErrNone { // A finalize can fail after its commit. When the key now holds this // upload's object, answer as a retry would. @@ -1066,7 +1073,14 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl if !sameFileChunks(committedEntry.GetChunks(), completionState.finalParts) { completionState.metadataOnlyCleanup = true } - output = committed + parentCtx, cancel := context.WithTimeout(context.Background(), createLookupTimeout) + parentErr = s3a.ensureObjectParent(parentCtx, *input.Bucket, dirName) + cancel() + if parentErr != nil { + glog.Errorf("completeMultipartUpload %s/%s upload %s: committed object's directory %s is missing: %v", *input.Bucket, *input.Key, *input.UploadId, dirName, parentErr) + } else { + output = committed + } } if completionState != nil { @@ -1079,14 +1093,20 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl // still references the chunks; removing it metadata-only orphans them. if err := s3a.deleteUnusedPartEntries(cleanupCtx, uploadDirectory, *input.Bucket, *input.Key, *input.UploadId, completionState); err != nil { glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err) - } else if err := s3a.uploadFiler(*input.Bucket, *input.Key).rm(cleanupCtx, s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil { - glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err) + } else if parentErr == nil { + // Otherwise the upload stays for the retry that creates the directory. + if err := s3a.uploadFiler(*input.Bucket, *input.Key).rm(cleanupCtx, s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil { + glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err) + } } } if len(completionState.supersededPartManifests) > 0 { s3a.deleteOrphanedChunks(completionState.supersededPartManifests) } } + if parentErr != nil { + return nil, finalizeCode + } return } diff --git a/weed/s3api/filer_util.go b/weed/s3api/filer_util.go index 3ec242a4d3..7a2c965f4a 100644 --- a/weed/s3api/filer_util.go +++ b/weed/s3api/filer_util.go @@ -32,6 +32,46 @@ func (s3a *S3ApiServer) mkdirExclusive(parentDirectoryPath string, dirName strin } +// ensureObjectParent creates the directories from the bucket down to dir, the +// directory a stored object entry lives in, that are missing: the filer stores +// an entry before its parent directories, so a create that failed on a parent +// leaves an object GET finds but no listing shows. Each level is checked, as a +// failed mkdir can leave a lower directory stored without its parent. The +// bucket directory and upload directories are never created here: a missing +// bucket fails the repair, as the filer would recreate it as a plain directory. +func (s3a *S3ApiServer) ensureObjectParent(ctx context.Context, bucket, dir string) error { + bucketDir, uploads := s3a.bucketDir(bucket), s3a.genUploadsFolder(bucket) + if !strings.HasPrefix(dir, bucketDir+"/") || dir == uploads || strings.HasPrefix(dir, uploads+"/") { + return nil + } + if exists, err := filer_pb.Exists(ctx, s3a, s3a.bucketRoot(bucket), bucket, true); err != nil { + return err + } else if !exists { + return fmt.Errorf("bucket directory %s is missing", bucketDir) + } + parent := bucketDir + for _, name := range strings.Split(strings.TrimPrefix(dir, bucketDir+"/"), "/") { + if name == "" { + continue + } + if exists, err := filer_pb.Exists(ctx, s3a, parent, name, true); err != nil || !exists { + if err := filer_pb.MkdirExclusive(ctx, s3a, parent, name, nil); errors.Is(err, filer_pb.ErrEntryAlreadyExists) { + // A file left there by a failed promotion is not a directory a listing descends. + if exists, err = filer_pb.Exists(ctx, s3a, parent, name, true); err == nil && !exists { + err = fmt.Errorf("%s/%s is not a directory", parent, name) + } + if err != nil { + return err + } + } else if err != nil { + return err + } + } + parent += "/" + name + } + return nil +} + // concurrentEntryIsForeign: after PutBucket's exclusive mkdir met an entry, // whether that entry must be answered BucketAlreadyExists without looking at // its owner: a table bucket (it carries no S3 owner and must never read as diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index d9733c451e..815056f80d 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -1333,6 +1333,10 @@ func (s3a *S3ApiServer) createAfterAmbiguousRoute(filePath, bucket, object strin glog.Warningf("putToFiler: ambiguous routed PUT for %s cannot prove an empty stored entry is its own; not claiming it", filePath) return s3err.ErrServiceUnavailable } + if err := s3a.ensureObjectParent(lookupCtx, bucket, dir); err != nil { + glog.Errorf("putToFiler: ambiguous routed PUT for %s stored the entry but its directory is still missing: %v", filePath, err) + return s3err.ErrInternalError + } *entryCreated = true if finalize != nil && finalize.afterCreate != nil { if code := finalize.afterCreate(entry); code != s3err.ErrNone { @@ -1468,6 +1472,10 @@ func (s3a *S3ApiServer) confirmCreateLanded(filePath, bucket, object, routeObjec return s3err.ErrNone } } + if err := s3a.ensureObjectParent(lookupCtx, bucket, dir); err != nil { + glog.Errorf("putToFiler: create entry for %s failed and its directory is still missing: %v", filePath, err) + return s3err.ErrNone + } glog.Warningf("putToFiler: create entry for %s failed but the entry exists, treating the write as successful", filePath) if finalize == nil || finalize.afterCreate == nil { landed = true diff --git a/weed/s3api/s3api_object_parent_recovery_test.go b/weed/s3api/s3api_object_parent_recovery_test.go new file mode 100644 index 0000000000..20706dc874 --- /dev/null +++ b/weed/s3api/s3api_object_parent_recovery_test.go @@ -0,0 +1,232 @@ +package s3api + +import ( + "context" + "net/http/httptest" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func parentRecoveryServer(t *testing.T, f *parentFailFiler) *S3ApiServer { + s3a := ambiguousRouteServer(t, startFakeFiler(t, f)) + s3a.option.BucketsPath = "/buckets" + f.put("/buckets", &filer_pb.Entry{Name: "b", IsDirectory: true}) + return s3a +} + +// parentFailFiler is a memCompleteFiler whose directory creates fail while +// mkdirFails is set. Lookups and directory creates are counted. +type parentFailFiler struct { + *memCompleteFiler + mkdirFails bool + mkdirs int + lookups int +} + +func (f *parentFailFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.mu.Lock() + f.lookups++ + f.mu.Unlock() + return f.memCompleteFiler.LookupDirectoryEntry(ctx, req) +} + +func (f *parentFailFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + if !req.Entry.IsDirectory { + return f.memCompleteFiler.CreateEntry(ctx, req) + } + f.mu.Lock() + defer f.mu.Unlock() + f.mkdirs++ + if f.mkdirFails { + return nil, status.Error(codes.Internal, "mkdir failed") + } + if f.entries[req.Directory][req.Entry.Name] != nil { + return &filer_pb.CreateEntryResponse{Error: filer_pb.ErrEntryAlreadyExists.Error(), ErrorCode: filer_pb.FilerError_ENTRY_ALREADY_EXISTS}, nil + } + f.put(req.Directory, req.Entry) + return &filer_pb.CreateEntryResponse{}, nil +} + +func newParentFailFiler() *parentFailFiler { + return &parentFailFiler{memCompleteFiler: &memCompleteFiler{entries: map[string]map[string]*filer_pb.Entry{}}} +} + +func (f *parentFailFiler) isDir(dir, name string) bool { + f.mu.Lock() + defer f.mu.Unlock() + entry := f.entries[dir][name] + return entry != nil && entry.IsDirectory +} + +func TestAmbiguousRouteRecoveryCreatesMissingParent(t *testing.T) { + uploaded := []*filer_pb.FileChunk{{FileId: "5,01637037d6", Size: 55}} + chunksAlive := func(context.Context, []*filer_pb.FileChunk) bool { return true } + recover := func(t *testing.T, f *parentFailFiler) (s3err.ErrorCode, bool) { + s3a := parentRecoveryServer(t, f) + addr := s3a.option.Filers[0] + f.put("/buckets/b/d", &filer_pb.Entry{Name: "o", Chunks: []*filer_pb.FileChunk{{FileId: "5,01637037d6", Size: 55}}}) + entryCreated := false + code := s3a.createAfterAmbiguousRoute("/buckets/b/d/o", "b", "d/o", addr, &filer_pb.Entry{Name: "o"}, uploaded, nil, &entryCreated, chunksAlive, + func(*filer_pb.WriteCondition) s3err.ErrorCode { + t.Fatal("re-committed an entry the route already stored") + return s3err.ErrNone + }) + return code, entryCreated + } + + t.Run("missing parent is created", func(t *testing.T) { + f := newParentFailFiler() + if code, entryCreated := recover(t, f); code != s3err.ErrNone || !entryCreated { + t.Fatalf("code=%v entryCreated=%v", code, entryCreated) + } + if !f.isDir("/buckets/b", "d") { + t.Fatal("the recovered object's directory was not created") + } + }) + + t.Run("parent that cannot be created fails the write", func(t *testing.T) { + f := newParentFailFiler() + f.mkdirFails = true + if code, entryCreated := recover(t, f); code == s3err.ErrNone || entryCreated { + t.Fatalf("code=%v entryCreated=%v; want an error while the object is unlisted", code, entryCreated) + } + }) + + t.Run("existing parent is left alone", func(t *testing.T) { + f := newParentFailFiler() + f.put("/buckets/b", &filer_pb.Entry{Name: "d", IsDirectory: true}) + if code, entryCreated := recover(t, f); code != s3err.ErrNone || !entryCreated { + t.Fatalf("code=%v entryCreated=%v", code, entryCreated) + } + if f.mkdirs != 0 { + t.Fatalf("mkdirs = %d, want none for a present directory", f.mkdirs) + } + }) +} + +func TestConfirmCreateLandedCreatesMissingParent(t *testing.T) { + uploaded := []*filer_pb.FileChunk{{FileId: "5,01637037d6", Size: 55}} + for _, mkdirFails := range []bool{false, true} { + f := newParentFailFiler() + f.mkdirFails = mkdirFails + s3a := parentRecoveryServer(t, f) + f.put("/buckets/b/d", &filer_pb.Entry{Name: "o", Chunks: []*filer_pb.FileChunk{{FileId: "5,01637037d6", Size: 55}}}) + landed, absent := s3a.confirmCreateLanded("/buckets/b/d/o", "b", "d/o", "d/o", &filer_pb.Entry{Name: "o"}, uploaded, nil) + if absent || landed == mkdirFails || f.isDir("/buckets/b", "d") == mkdirFails { + t.Fatalf("mkdirFails=%v: landed=%v absent=%v dir=%v", mkdirFails, landed, absent, f.isDir("/buckets/b", "d")) + } + } +} + +func TestEnsureObjectParentChecksEveryLevel(t *testing.T) { + t.Run("lower directory stored without its parent", func(t *testing.T) { + f := newParentFailFiler() + s3a := parentRecoveryServer(t, f) + f.put("/buckets/b/a", &filer_pb.Entry{Name: "c", IsDirectory: true}) + if err := s3a.ensureObjectParent(context.Background(), "b", "/buckets/b/a/c"); err != nil { + t.Fatal(err) + } + if !f.isDir("/buckets/b", "a") { + t.Fatal("the missing ancestor was not created") + } + }) + t.Run("parent left a file", func(t *testing.T) { + f := newParentFailFiler() + s3a := parentRecoveryServer(t, f) + f.put("/buckets/b", &filer_pb.Entry{Name: "d"}) + if err := s3a.ensureObjectParent(context.Background(), "b", "/buckets/b/d"); err == nil { + t.Fatal("accepted a file as the object's directory") + } + }) + t.Run("missing bucket is not recreated", func(t *testing.T) { + f := newParentFailFiler() + s3a := parentRecoveryServer(t, f) + delete(f.entries["/buckets"], "b") + if err := s3a.ensureObjectParent(context.Background(), "b", "/buckets/b/d"); err == nil { + t.Fatal("repaired an object's directory under a deleted bucket") + } + if f.mkdirs != 0 { + t.Fatalf("mkdirs = %d, want none under a missing bucket", f.mkdirs) + } + }) +} + +// A part's upload directory is never recreated: it is gone only when the +// upload was aborted or completed. +func TestEnsureObjectParentSkipsBucketAndUploads(t *testing.T) { + f := newParentFailFiler() + s3a := parentRecoveryServer(t, f) + for _, dir := range []string{s3a.bucketDir("b"), s3a.genUploadsFolder("b"), s3a.genUploadsFolder("b") + "/u1", "/buckets"} { + if err := s3a.ensureObjectParent(context.Background(), "b", dir); err != nil { + t.Fatalf("%s: %v", dir, err) + } + } + if f.mkdirs != 0 || f.lookups != 0 { + t.Fatalf("mkdirs=%d lookups=%d, want none", f.mkdirs, f.lookups) + } +} + +// A completion that committed its object but not the object's directory +// answers an error, and the retry that finds the commit creates the directory. +func TestCompleteMultipartUploadCreatesCommittedObjectsParent(t *testing.T) { + f := newParentFailFiler() + f.createFailure = status.Error(codes.Internal, "mkdir after the entry failed") + f.storedOnFailure = func(entry *filer_pb.Entry) *filer_pb.Entry { return entry } + f.mkdirFails = true + s3a := newFailoverTestServer(t, startFakeFiler(t, f)) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + uploadsDir := s3a.genUploadsFolder("b") + f.put(s3a.bucketRoot("b"), &filer_pb.Entry{Name: "b", IsDirectory: true}) + f.put(uploadsDir, &filer_pb.Entry{Name: "u1", IsDirectory: true, Extended: map[string][]byte{s3_constants.ExtMultipartObjectKey: []byte("d/a.bin")}}) + f.put(uploadsDir+"/u1", &filer_pb.Entry{ + Name: "0001.part", + Attributes: &filer_pb.FuseAttributes{FileSize: 11}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 11}}, + Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("5eb63bbbe01eeed093cb22bb8f5acdc3")}, + }) + f.put(uploadsDir+"/u1", &filer_pb.Entry{ + Name: "0001_old.part", + Attributes: &filer_pb.FuseAttributes{FileSize: 11}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,02637037d6", Size: 11}}, + Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("0f343b0931126a20f133d67c2b018a3b")}, + }) + complete := func() (*CompleteMultipartUploadResult, s3err.ErrorCode) { + input := &s3.CompleteMultipartUploadInput{Bucket: aws.String("b"), Key: aws.String("d/a.bin"), UploadId: aws.String("u1")} + parts := &CompleteMultipartUpload{Parts: []CompletedPart{{PartNumber: 1, ETag: `"5eb63bbbe01eeed093cb22bb8f5acdc3"`}}} + return s3a.completeMultipartUpload(httptest.NewRequest("POST", "/b/d/a.bin?uploadId=u1", nil), input, parts) + } + + if _, code := complete(); code == s3err.ErrNone { + t.Fatal("completion answered success with the object's directory missing") + } + if f.entries[s3a.bucketDir("b")+"/d"]["a.bin"] == nil { + t.Fatal("test setup: the failed commit did not store the object") + } + if f.entries[uploadsDir]["u1"] == nil { + t.Fatal("the upload directory was removed before the object was listed") + } + if deleteData, ok := f.deletedData["0001_old.part"]; !ok || !deleteData { + t.Errorf("unused part deleted = %v, with data = %v; want its data freed before the retry", ok, deleteData) + } + + f.mkdirFails = false + output, code := complete() + if code != s3err.ErrNone || output == nil { + t.Fatalf("retry code = %v, want success", s3err.GetAPIError(code).Code) + } + if !f.isDir(s3a.bucketDir("b"), "d") { + t.Fatal("the retry did not create the committed object's directory") + } + if f.entries[uploadsDir]["u1"] != nil { + t.Error("the upload directory survived the completed retry") + } +}