From 79ddcb49e6a3d8c1195bcaec1c631352a64602da Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Tue, 24 Nov 2026 20:13:39 -0800 Subject: [PATCH] filer: send a delete that misses locally to the write owner (#12967) * filer: record which peers share this filer's store Co-Authored-By: Claude Opus 5.5 * filer: send a delete that misses locally to the write owner Exclusive and conditional creates are stored on the path's write owner. With separate filer stores, a delete sent to another filer before it has replayed the create found nothing, reported success, and left the entry on the owner, from where it replicated back. Such a delete now goes to the owner, unless the owner runs on this filer's store. A forwarded delete is applied only by the filer its own ring names as the owner. Co-Authored-By: Claude Opus 5.5 * s3api: delete a directory marker on its write owner The marker is read on the key's write owner, but the delete went through the connected filer. When the marker still has children, the filer refuses the delete and the marker is demoted by a lookup and an update on that same client. A connected filer that has not caught up with the owner misses the marker there and reports success, so the owner keeps listing the key. Co-Authored-By: Claude Opus 5.5 * s3api: also delete a directory marker on its prior owner While a ring change is in its cooling-off window, the routed read can find the marker on the key's prior owner before it reaches the new one. The delete went only to the new owner, so a nonempty marker was demoted on a filer that did not have it, and the prior owner kept listing the key. Co-Authored-By: Claude Opus 5.5 * s3api: check a directory marker on the prior owner before deleting it there The prior owner's delete ran unchecked and through the failover walk. When the new owner held an empty marker and the prior owner already held the object without the slash, the delete removed that object's data. And when the prior owner could not be reached, another filer reported the delete done while the marker stayed on the prior owner. The prior owner's entry is now read on that filer and judged like the routed one before anything is deleted, and its delete runs on that filer only. A prior owner that cannot be read fails the delete for the client to retry, which lasts at most the ring's cooling-off window. Co-Authored-By: Claude Opus 5.5 * s3api: probe a marker's prior owner when its write owner misses A miss on the write owner returned success before the prior owner was checked, so an unreachable prior owner that still held the marker left it in place behind a reported delete. The miss now falls through to the prior-owner probe, which fails the delete when that filer cannot be read. Co-Authored-By: Claude Opus 5.5 * s3api: check the entry a marker delete removes on the filer it runs on The read that decides the delete can be answered by another filer than the delete: the owner write walk fails over when the owner's channel does not come up. Each delete now reads its filer's own entry first and leaves an entry holding uploaded data alone, as the routed read already does. Co-Authored-By: Claude Opus 5.5 * s3api: send no marker delete to a filer that misses the marker A filer that misses passes the delete on to the key's write owner, which applies it without the marker checks and may hold uploaded data under the key. The delete now runs only where the entry was checked; a miss on an entry the read found fails the delete for the client to retry. Co-Authored-By: Claude Opus 5.5 * s3api: leave the object without the slash alone when deleting its marker A marker delete removed the entry unless it carried chunks or remote data, so the object "dir" stored inline, or empty and known only by its promotion mark, went with a delete of "dir/". A plain file or a prefix object holds the key without the slash, as reads already treat it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/filer/meta_aggregator.go | 25 ++ weed/filer/meta_aggregator_watermark_test.go | 24 ++ weed/s3api/s3api_directory_marker.go | 111 +++++-- weed/s3api/s3api_directory_marker_test.go | 283 ++++++++++++++++++ weed/server/filer_grpc_server.go | 49 ++- .../filer_grpc_server_delete_route_test.go | 195 ++++++++++++ weed/server/filer_grpc_server_route.go | 36 +++ 7 files changed, 677 insertions(+), 46 deletions(-) create mode 100644 weed/s3api/s3api_directory_marker_test.go create mode 100644 weed/server/filer_grpc_server_delete_route_test.go diff --git a/weed/filer/meta_aggregator.go b/weed/filer/meta_aggregator.go index 5e7739776d..061f7ed21f 100644 --- a/weed/filer/meta_aggregator.go +++ b/weed/filer/meta_aggregator.go @@ -56,6 +56,9 @@ type MetaAggregator struct { // started failing to connect; see notePeerUnreachable. Guarded by // peerChansLock, so a removed peer's exiting loop cannot recreate it. peerUnreachableSinceNs map[pb.ServerAddress]int64 + // peerSharesStore marks followed peers whose store signature matched this + // filer's when their subscription last connected. Guarded by peerChansLock. + peerSharesStore map[pb.ServerAddress]bool // lowWatermarkTsNs and lowFlushWatermarkTsNs are the last minima signalled // on deliveryAdvanced and flushAdvanced, each closed and replaced when its // own minimum rises. Held readers park on the one that bounds them: @@ -102,6 +105,7 @@ func NewMetaAggregator(filer *Filer, self pb.ServerAddress, grpcDialOption grpc. peerResumeTsNs: make(map[pb.ServerAddress]int64), peerUnreachableSinceNs: make(map[pb.ServerAddress]int64), + peerSharesStore: make(map[pb.ServerAddress]bool), } t.peerSubscribeLoop = t.loopSubscribeToOneFiler // nil notifyFn: aggregated subscribers wake through the buffer's @@ -148,6 +152,7 @@ func (ma *MetaAggregator) OnPeerUpdate(update *master_pb.ClusterNodeUpdate, star delete(ma.peerChans, address) } delete(ma.peerUnreachableSinceNs, address) + delete(ma.peerSharesStore, address) // Only mark: dropping the watermarks at once would let subscribers // advance past a flapping peer's unflushed events (see peerRemovedAtNs). ma.markPeerWatermarkRemoved(address) @@ -204,6 +209,25 @@ func (ma *MetaAggregator) notePeerReachable(peer pb.ServerAddress, stopChan <-ch ma.initPeerWatermark(peer) } +// notePeerStore records whether peer runs on this filer's store. A subscription +// the master has removed meanwhile must not record it. +func (ma *MetaAggregator) notePeerStore(peer pb.ServerAddress, stopChan <-chan struct{}, sharesStore bool) { + ma.peerChansLock.Lock() + defer ma.peerChansLock.Unlock() + if ma.peerChans[peer] == stopChan { + ma.peerSharesStore[peer] = sharesStore + } +} + +// SharesStore reports whether peer is followed and runs on this filer's +// store, so an entry missing here is missing there too. A peer not yet +// connected reports false. +func (ma *MetaAggregator) SharesStore(peer pb.ServerAddress) bool { + ma.peerChansLock.Lock() + defer ma.peerChansLock.Unlock() + return ma.peerSharesStore[peer] +} + // initPeerWatermark adds the peer with a zero (unknown) watermark; a re-added // peer keeps its prior values and stops being considered removed. func (ma *MetaAggregator) initPeerWatermark(peer pb.ServerAddress) { @@ -616,6 +640,7 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress, return lastTsNs, fmt.Errorf("%w %s: %v", errPeerUnreachable, peer, err) } ma.notePeerReachable(peer, stopChan) + ma.notePeerStore(peer, stopChan, peerSignature == f.Signature) // when filer store is not shared by multiple filers if peerSignature != f.Signature { diff --git a/weed/filer/meta_aggregator_watermark_test.go b/weed/filer/meta_aggregator_watermark_test.go index 4a5ec547f0..3668444a07 100644 --- a/weed/filer/meta_aggregator_watermark_test.go +++ b/weed/filer/meta_aggregator_watermark_test.go @@ -17,6 +17,7 @@ func newTestAggregator() *MetaAggregator { peerResumeTsNs: make(map[pb.ServerAddress]int64), peerUnreachableSinceNs: make(map[pb.ServerAddress]int64), + peerSharesStore: make(map[pb.ServerAddress]bool), } ma.peerSubscribeLoop = ma.loopSubscribeToOneFiler return ma @@ -343,3 +344,26 @@ func TestLongUnreachablePeerIsReportedOnce(t *testing.T) { t.Fatal("an untracked peer was reported as newly marked") } } + +func TestSharesStoreFollowsTheConnectedSubscription(t *testing.T) { + ma := newTestAggregator() + ma.peerSubscribeLoop = func(_ *Filer, _, _ pb.ServerAddress, _ time.Time, _ chan struct{}) {} + shared, separate := pb.ServerAddress("filer-a:8888"), pb.ServerAddress("filer-b:8888") + ma.OnPeerUpdate(&master_pb.ClusterNodeUpdate{Address: string(shared), IsAdd: true}, time.Now()) + ma.OnPeerUpdate(&master_pb.ClusterNodeUpdate{Address: string(separate), IsAdd: true}, time.Now()) + if ma.SharesStore(shared) { + t.Fatal("a peer that has not connected yet must not count as sharing the store") + } + stopShared := ma.peerChans[shared] + ma.notePeerStore(shared, stopShared, true) + ma.notePeerStore(separate, ma.peerChans[separate], false) + if !ma.SharesStore(shared) || ma.SharesStore(separate) { + t.Fatalf("shared=%v separate=%v, want true false", ma.SharesStore(shared), ma.SharesStore(separate)) + } + + ma.OnPeerUpdate(&master_pb.ClusterNodeUpdate{Address: string(shared), IsAdd: false}, time.Now()) + ma.notePeerStore(shared, stopShared, true) + if ma.SharesStore(shared) { + t.Fatal("a removed peer, or its exiting subscription, must not keep the shared mark") + } +} diff --git a/weed/s3api/s3api_directory_marker.go b/weed/s3api/s3api_directory_marker.go index ec075da53c..81bfa63f58 100644 --- a/weed/s3api/s3api_directory_marker.go +++ b/weed/s3api/s3api_directory_marker.go @@ -6,9 +6,11 @@ import ( "strings" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/seaweedfs/seaweedfs/weed/util" ) // An explicit directory marker - the key "dir/" created by PutObject on a @@ -34,28 +36,45 @@ func (s3a *S3ApiServer) deleteDirectoryMarker(r *http.Request, bucket, object st entry, err := s3a.getObjectEntryRoutedByKey(bucket, trimmedObject) switch { case errors.Is(err, filer_pb.ErrNotFound): - return s3err.ErrNone // deleting a key that is not there is a success case err != nil: // The entry may be a file a child write promoted to a directory, whose data // belongs to the key without the trailing slash. Deleting without knowing // would destroy it, so fail and leave the retry to the client. glog.Errorf("deleteDirectoryMarker: cannot read %s/%s: %v", bucket, object, err) return s3err.ErrInternalError - case len(entry.GetChunks()) > 0 || entry.IsInRemoteOnly(): - // A promoted file, not a marker: "dir/" does not name its data. - glog.V(2).Infof("deleteDirectoryMarker: %s/%s holds uploaded data, leaving it alone", bucket, object) - return s3err.ErrNone - case s3a.isVersionFileKey(trimmedObject, entry.Extended): - return s3err.ErrAccessDenied + default: + if remove, code := s3a.checkDirectoryMarker(entry, bucket, object, governanceBypassAllowed); !remove { + return code + } } + found := err == nil - // The key is deleted the unversioned way, but Object Lock still covers it: the - // gateway lists it as an object and serves retention set on it. The lock that - // matters is the one on this entry, since that is what is removed -- looking the - // key up instead would answer with a version once the key has a history. - if err := s3a.enforceObjectLockOnEntry(entry, bucket, object, "", governanceBypassAllowed); err != nil { - glog.V(2).Infof("deleteDirectoryMarker: %s/%s is locked: %v", bucket, object, err) - return s3err.ErrAccessDenied + // During a ring change the key's prior owner may hold an entry the new owner + // has not received yet, so it is checked and deleted on that filer as well. + owner := s3a.routableWriteOwner(bucket, trimmedObject) + dir, name := util.FullPath(markerDir).DirAndName() + var priorOwner pb.ServerAddress + if prior := s3a.priorWriteOwner(bucket, trimmedObject); prior != "" && prior != owner { + probeCtx, cancel := s3a.routedProbeContext(prior) + priorEntry, priorErr := s3a.lookupEntryOnFiler(probeCtx, prior, dir, name) + cancel() + switch { + case errors.Is(priorErr, filer_pb.ErrNotFound): + case priorErr != nil: + glog.Errorf("deleteDirectoryMarker: cannot read %s/%s on prior owner %s: %v", bucket, object, prior, priorErr) + return s3err.ErrInternalError + default: + remove, code := s3a.checkDirectoryMarker(priorEntry, bucket, object, governanceBypassAllowed) + if code != s3err.ErrNone { + return code + } + if remove { + priorOwner = prior + } + } + } + if !found && priorOwner == "" { + return s3err.ErrNone // deleting a key that is not there is a success } // Drop a history an older build recorded for this key. Nothing writes one now, and @@ -103,11 +122,69 @@ func (s3a *S3ApiServer) deleteDirectoryMarker(r *http.Request, bucket, object st return s3err.ErrInternalError } - if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + // Each delete checks the entry of the filer it runs on, which a failover can + // make another filer than the one read above. A nonempty marker is demoted by + // a read and an update that must find it there too. A filer that misses is + // not sent the delete: it would pass it on to the key's write owner, which + // applies it without these checks. + refused := s3err.ErrNone + missed := false + deleteMarker := func(client filer_pb.SeaweedFilerClient) error { + resp, lookupErr := filer_pb.LookupEntry(r.Context(), client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name}) + switch { + case errors.Is(lookupErr, filer_pb.ErrNotFound): + missed = true + return nil + case lookupErr != nil: + return lookupErr + } + if remove, code := s3a.checkDirectoryMarker(resp.Entry, bucket, object, governanceBypassAllowed); !remove { + refused = code + return nil + } return s3a.deleteUnversionedObjectWithClient(r.Context(), client, bucket, object, false) - }); err != nil { + } + if err := s3a.withWriteOwnerFilerClient(owner, deleteMarker); err != nil { glog.Errorf("deleteDirectoryMarker: failed to delete %s/%s: %v", bucket, object, err) return s3err.ErrInternalError } - return s3err.ErrNone + if refused != s3err.ErrNone { + return refused + } + if priorOwner == "" { + if missed { + // The entry read above is on a filer this delete did not reach. + glog.Errorf("deleteDirectoryMarker: %s/%s is not on the filer the delete reached", bucket, object) + return s3err.ErrInternalError + } + return s3err.ErrNone + } + if err := pb.WithFilerClient(false, 0, priorOwner, s3a.option.GrpcDialOption, deleteMarker); err != nil { + glog.Errorf("deleteDirectoryMarker: failed to delete %s/%s on prior owner %s: %v", bucket, object, priorOwner, err) + return s3err.ErrInternalError + } + return refused +} + +// checkDirectoryMarker reports whether entry is a "/" marker the delete may +// remove, and otherwise the code the delete answers with. +func (s3a *S3ApiServer) checkDirectoryMarker(entry *filer_pb.Entry, bucket, object string, governanceBypassAllowed bool) (bool, s3err.ErrorCode) { + switch { + case !entry.IsDirectory || entry.IsPrefixObject() || len(entry.GetChunks()) > 0 || entry.IsInRemoteOnly(): + // The object "dir", or a file promoted to a directory: "dir/" does not name its data. + glog.V(2).Infof("deleteDirectoryMarker: %s/%s holds uploaded data, leaving it alone", bucket, object) + return false, s3err.ErrNone + case s3a.isVersionFileKey(strings.TrimSuffix(strings.TrimPrefix(object, "/"), "/"), entry.Extended): + return false, s3err.ErrAccessDenied + } + + // The key is deleted the unversioned way, but Object Lock still covers it: the + // gateway lists it as an object and serves retention set on it. The lock that + // matters is the one on this entry, since that is what is removed -- looking the + // key up instead would answer with a version once the key has a history. + if err := s3a.enforceObjectLockOnEntry(entry, bucket, object, "", governanceBypassAllowed); err != nil { + glog.V(2).Infof("deleteDirectoryMarker: %s/%s is locked: %v", bucket, object, err) + return false, s3err.ErrAccessDenied + } + return true, s3err.ErrNone } diff --git a/weed/s3api/s3api_directory_marker_test.go b/weed/s3api/s3api_directory_marker_test.go new file mode 100644 index 0000000000..cc8d696d8f --- /dev/null +++ b/weed/s3api/s3api_directory_marker_test.go @@ -0,0 +1,283 @@ +package s3api + +import ( + "context" + "net/http" + "net/http/httptest" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// markerFiler deletes and updates its own entries, refusing to delete a +// directory that still has children, as a filer does. +type markerFiler struct { + anonymousReadFiler + deletes int +} + +func (f *markerFiler) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.deletes++ + target := path.Join(req.Directory, req.Name) + for key := range f.entries { + if strings.HasPrefix(key, target+"/") { + return &filer_pb.DeleteEntryResponse{Error: filer.MsgFailDelNonEmptyFolder + " " + target}, nil + } + } + delete(f.entries, target) + return &filer_pb.DeleteEntryResponse{}, nil +} + +func (f *markerFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + target := path.Join(req.Directory, req.Entry.Name) + if f.entries[target] == nil { + return nil, status.Error(codes.NotFound, target) + } + f.entries[target] = proto.Clone(req.Entry).(*filer_pb.Entry) + return &filer_pb.UpdateEntryResponse{}, nil +} + +// A nonempty "dir/" marker that so far exists only on its write owner: the +// delete and the demotion that follows its refusal both have to run there, or +// the owner keeps listing the key after a reported success. +func TestDeleteNonEmptyMarkerDemotesOnTheOwner(t *testing.T) { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + connected := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + }}} + owner := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}}, + "/buckets/b/album/image.jpg": anonymousReadEntry(nil), + }}} + connectedAddr := startFakeFiler(t, connected) + ownerAddr := startFakeFiler(t, owner) + s3a := newPutTestServer(t, connectedAddr, ownerAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, ownerAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{ownerAddr}, 1) + require.Equal(t, connectedAddr, s3a.filerClient.GetCurrentFiler()) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrNone, s3a.deleteDirectoryMarker(r, "b", "album/")) + + owner.mu.Lock() + marker := owner.entries["/buckets/b/album"] + owner.mu.Unlock() + require.NotNil(t, marker, "the owner lost the directory its child lives in") + require.False(t, marker.IsDirectoryKeyObject(), "the owner still holds album/ as an object") + require.Contains(t, owner.entries, "/buckets/b/album/image.jpg") + require.Zero(t, connected.deletes, "the delete went to the connected filer, not the owner") +} + +// While a ring change is in its cooling-off window, the marker the read finds +// on the prior owner may not have reached the new owner yet. +func TestDeleteNonEmptyMarkerDemotesOnThePriorOwner(t *testing.T) { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + next := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + }}} + prior := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}}, + "/buckets/b/album/image.jpg": anonymousReadEntry(nil), + }}} + nextAddr := startFakeFiler(t, next) + priorAddr := startFakeFiler(t, prior) + s3a := newPutTestServer(t, nextAddr, priorAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, priorAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{priorAddr}, 1) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{nextAddr}, 2) + require.Equal(t, priorAddr, s3a.priorWriteOwner("b", "album")) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrNone, s3a.deleteDirectoryMarker(r, "b", "album/")) + + prior.mu.Lock() + marker := prior.entries["/buckets/b/album"] + prior.mu.Unlock() + require.NotNil(t, marker, "the prior owner lost the directory its child lives in") + require.False(t, marker.IsDirectoryKeyObject(), "the prior owner still holds album/ as an object") +} + +// The new owner's empty marker is the key "album/", but the prior owner may +// already hold "album" with uploaded data the new owner has not received. +func TestDeleteMarkerLeavesDataOnThePriorOwner(t *testing.T) { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + next := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}}, + }}} + prior := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", Attributes: &filer_pb.FuseAttributes{FileSize: 11}, + Chunks: []*filer_pb.FileChunk{{FileId: "1,0123456789", Size: 11}}}, + }}} + nextAddr := startFakeFiler(t, next) + priorAddr := startFakeFiler(t, prior) + s3a := newPutTestServer(t, nextAddr, priorAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, priorAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{priorAddr}, 1) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{nextAddr}, 2) + require.Equal(t, priorAddr, s3a.priorWriteOwner("b", "album")) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrNone, s3a.deleteDirectoryMarker(r, "b", "album/")) + + next.mu.Lock() + require.NotContains(t, next.entries, "/buckets/b/album", "the new owner kept the marker") + next.mu.Unlock() + prior.mu.Lock() + defer prior.mu.Unlock() + require.Contains(t, prior.entries, "/buckets/b/album", "album/ removed the object album on the prior owner") + require.Zero(t, prior.deletes) +} + +// A prior owner that cannot be reached may still hold the marker, whether or not +// the new owner has it yet, and another filer reporting the delete done would +// not remove it there. +func TestDeleteMarkerFailsWithoutThePriorOwner(t *testing.T) { + for _, ownerHasMarker := range []bool{true, false} { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + marker := &filer_pb.Entry{Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}} + connected := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, "/buckets/b/album": marker, + }}} + next := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + }}} + if ownerHasMarker { + next.entries["/buckets/b/album"] = marker + } + connectedAddr := startFakeFiler(t, connected) + nextAddr := startFakeFiler(t, next) + priorAddr := closedFilerAddress(t) + s3a := newPutTestServer(t, connectedAddr, nextAddr, priorAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, nextAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{priorAddr}, 1) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{nextAddr}, 2) + require.Equal(t, priorAddr, s3a.priorWriteOwner("b", "album")) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrInternalError, s3a.deleteDirectoryMarker(r, "b", "album/"), "owner has marker: %v", ownerHasMarker) + require.Zero(t, connected.deletes, "the prior owner's delete was reported done by another filer") + require.Zero(t, next.deletes, "the delete half finished before the prior owner was known") + } +} + +// The filer a delete reaches may hold another entry than the marker the read +// found, such as "album" with uploaded data, and "album/" does not name it. +func TestDeleteMarkerRechecksTheEntryItDeletes(t *testing.T) { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + owner := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}}, + }}} + lookups := 0 + owner.onLookup = func() { + if lookups++; lookups > 1 { + owner.entries["/buckets/b/album"] = &filer_pb.Entry{Name: "album", Attributes: &filer_pb.FuseAttributes{FileSize: 11}, + Chunks: []*filer_pb.FileChunk{{FileId: "1,0123456789", Size: 11}}} + } + } + ownerAddr := startFakeFiler(t, owner) + s3a := newPutTestServer(t, ownerAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, ownerAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{ownerAddr}, 1) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrNone, s3a.deleteDirectoryMarker(r, "b", "album/")) + + owner.mu.Lock() + defer owner.mu.Unlock() + require.Contains(t, owner.entries, "/buckets/b/album", "album/ removed the object album") + require.Zero(t, owner.deletes) +} + +// A delete the failover sends to a filer without the marker the read found +// would be passed on to the key's write owner, which applies it unchecked and +// may hold "album" with uploaded data. +func TestDeleteMarkerSendsNoDeleteToAFilerThatMisses(t *testing.T) { + bucketEntry := &filer_pb.Entry{Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + connected := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": bucketEntry, + "/buckets/b/album": {Name: "album", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/octet-stream"}}, + }}} + lookups := 0 + connected.onLookup = func() { + if lookups++; lookups > 1 { + delete(connected.entries, "/buckets/b/album") + } + } + connectedAddr := startFakeFiler(t, connected) + ownerAddr := closedFilerAddress(t) + s3a := newPutTestServer(t, connectedAddr, ownerAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, connectedAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{ownerAddr}, 1) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrInternalError, s3a.deleteDirectoryMarker(r, "b", "album/")) + require.Zero(t, connected.deletes, "a filer that missed the marker was sent the delete") +} + +// "album/" does not name the object "album", whose data may be inline rather +// than in chunks, or which may be empty and known only by the promotion mark. +func TestDeleteMarkerLeavesTheObjectWithoutTheSlash(t *testing.T) { + promoted := func(content []byte) *filer_pb.Entry { + e := &filer_pb.Entry{Name: "album", Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(content))}, Content: content} + e.MarkPrefixObject() + return e + } + for name, entry := range map[string]*filer_pb.Entry{ + "inline file": {Name: "album", Attributes: &filer_pb.FuseAttributes{FileSize: 5}, Content: []byte("hello")}, + "empty file": {Name: "album", Attributes: &filer_pb.FuseAttributes{}}, + "inline prefix object": promoted([]byte("hello")), + "empty prefix object": promoted(nil), + } { + t.Run(name, func(t *testing.T) { + owner := &markerFiler{anonymousReadFiler: anonymousReadFiler{entries: map[string]*filer_pb.Entry{ + "/buckets/b": {Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}, + "/buckets/b/album": entry, + }}} + ownerAddr := startFakeFiler(t, owner) + s3a := newPutTestServer(t, ownerAddr) + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set("b", &BucketConfig{Name: "b"}) + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, ownerAddr) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{ownerAddr}, 1) + + r := httptest.NewRequest(http.MethodDelete, "/b/album/", nil) + require.Equal(t, s3err.ErrNone, s3a.deleteDirectoryMarker(r, "b", "album/")) + owner.mu.Lock() + defer owner.mu.Unlock() + require.Contains(t, owner.entries, "/buckets/b/album", "album/ removed the object album") + require.Zero(t, owner.deletes) + }) + } +} diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index 3b7837e301..38f73d17c6 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "strconv" + "sync" "time" "github.com/seaweedfs/seaweedfs/weed/cluster" @@ -1347,34 +1348,13 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr // that the per-path lock below only makes atomic on this filer. Route it // to the entry's ring owner so one filer's lock arbitrates every writer // cluster-wide; is_moved bounds this to one hop. - if len(req.ExpectedExtended) > 0 { - if !req.IsMoved { - var ownerResp *filer_pb.DeleteEntryResponse - handled, forwardErr := fs.forwardToWriteOwner(ctx, entryRouteKey(fullpath), func(owner pb.ServerAddress) error { - if scopeKeepOnly(ctx) { - return status.Error(codes.PermissionDenied, "filer: scoped DeleteEntry cannot be forwarded to the write owner") - } - glog.V(2).InfofCtx(ctx, "DeleteEntry %s: forwarding to owner %s", fullpath, owner) - req.IsMoved = true - return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { - forwarded, e := client.DeleteEntry(ctx, req) - if e != nil { - return e - } - ownerResp = forwarded - return nil - }) - }) - if handled { - if forwardErr != nil { - return &filer_pb.DeleteEntryResponse{}, forwardErr - } - return ownerResp, nil - } - } else { - if err := fs.checkForwardedWrite(ctx, entryRouteKey(fullpath)); err != nil { - return &filer_pb.DeleteEntryResponse{}, err - } + if req.IsMoved { + if err := fs.checkForwardedWrite(ctx, entryRouteKey(fullpath)); err != nil { + return &filer_pb.DeleteEntryResponse{}, err + } + } else if len(req.ExpectedExtended) > 0 { + if ownerResp, handled, forwardErr := fs.forwardDeleteEntry(ctx, req, fullpath); handled { + return ownerResp, forwardErr } } @@ -1383,7 +1363,8 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr // path: the update would pass its precondition and then resurrect fids // that are already on the deletion queue. pathLock := fs.entryLockTable.AcquireLock("DeleteEntry", fullpath, util.ExclusiveLock) - defer fs.entryLockTable.ReleaseLock(fullpath, pathLock) + unlockPath := sync.OnceFunc(func() { fs.entryLockTable.ReleaseLock(fullpath, pathLock) }) + defer unlockPath() if err := fs.checkScopeWorm(ctx, string(fullpath)); err != nil { return &filer_pb.DeleteEntryResponse{}, err } @@ -1417,6 +1398,16 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr } ctx, eventSink := filer.WithMetadataEventSink(ctx) err = fs.filer.DeleteEntryMetaAndData(ctx, fullpath, req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures, deleteCutoff(req.IfNotModifiedAfter, req.IfNotModifiedAfterNs)) + // Exclusive and conditional creates land on the write owner, and a store of + // its own reaches this one only through replication: a miss here is not + // authoritative until the owner misses too. A scoped delete stays local, + // since the owner would apply it without the scope's checks. + if err == filer_pb.ErrNotFound && !req.IsMoved && !scopeKeepOnly(ctx) && fs.ownerKeepsOwnStore(entryRouteKey(fullpath)) { + unlockPath() + if ownerResp, handled, forwardErr := fs.forwardDeleteEntry(ctx, req, fullpath); handled { + return ownerResp, forwardErr + } + } resp = &filer_pb.DeleteEntryResponse{} if err != nil && err != filer_pb.ErrNotFound { resp.Error = err.Error() diff --git a/weed/server/filer_grpc_server_delete_route_test.go b/weed/server/filer_grpc_server_delete_route_test.go new file mode 100644 index 0000000000..d8f3c5d9e9 --- /dev/null +++ b/weed/server/filer_grpc_server_delete_route_test.go @@ -0,0 +1,195 @@ +package weed_server + +import ( + "context" + "net" + "os" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" +) + +// separateStores gives B a store of its own. Nothing replicates between the +// two, as if A had not yet replayed what B stored. +func separateStores(c *twoFilers) *renameTestStore { + storeB := newRenameTestStore() + storeB.entries["/"] = newDirectoryEntry("/", 1) + c.fsB.filer.Store = filer.NewFilerStoreWrapper(storeB) + return storeB +} + +// Creates that must be exclusive land on the write owner. An unlink or rmdir +// sent to another filer right after must delete them there, even though that +// filer's own store has not seen them yet. +func TestDeleteEntryMissReachesOwnerStore(t *testing.T) { + for _, tc := range []struct { + name string + req func(dir, name string) *filer_pb.CreateEntryRequest + }{ + {"exclusive file", func(dir, name string) *filer_pb.CreateEntryRequest { + return &filer_pb.CreateEntryRequest{Directory: dir, OExcl: true, Entry: &filer_pb.Entry{ + Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: 0644}, + }} + }}, + {"exclusive directory", func(dir, name string) *filer_pb.CreateEntryRequest { + return &filer_pb.CreateEntryRequest{Directory: dir, OExcl: true, Entry: &filer_pb.Entry{ + Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: uint32(os.ModeDir | 0755)}, + }} + }}, + {"create if not exists", func(dir, name string) *filer_pb.CreateEntryRequest { + return &filer_pb.CreateEntryRequest{Directory: dir, Entry: &filer_pb.Entry{ + Name: name, Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: 0644}, + }, Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}}}} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + c := newTwoFilers(t) + storeB := separateStores(c) + sharedWriteRing(c) + p := c.keyOwnedBy(t, c.addrB, c.addrB) + dir, name := p.DirAndName() + ctx := context.Background() + + if resp, err := c.fsA.CreateEntry(ctx, tc.req(dir, name)); err != nil || resp.GetError() != "" { + t.Fatalf("create via A: resp=%v err=%v", resp, err) + } + if _, err := storeB.FindEntry(ctx, p); err != nil { + t.Fatalf("the owner did not store the create: %v", err) + } + if _, err := c.store.FindEntry(ctx, p); err != filer_pb.ErrNotFound { + t.Fatalf("A's store must not have the entry yet: %v", err) + } + + req := &filer_pb.DeleteEntryRequest{Directory: dir, Name: name, IsDeleteData: true} + if resp, err := c.fsA.DeleteEntry(ctx, req); err != nil || resp.GetError() != "" { + t.Fatalf("delete via A: resp=%v err=%v", resp, err) + } + if _, err := storeB.FindEntry(ctx, p); err != filer_pb.ErrNotFound { + t.Fatalf("the owner kept the entry after a successful delete: %v", err) + } + }) + } +} + +// fakeOwner answers the signature read of A's aggregator and counts the +// deletes A forwards to it. +type fakeOwner struct { + filer_pb.UnimplementedSeaweedFilerServer + signature int32 + deletes atomic.Int32 +} + +func (o *fakeOwner) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + return &filer_pb.GetFilerConfigurationResponse{Signature: o.signature}, nil +} + +func (o *fakeOwner) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) { + if req.IsMoved { + o.deletes.Add(1) + } + return &filer_pb.DeleteEntryResponse{}, nil +} + +// On a store the owner shares, the miss is the owner's answer too, so a +// delete of an absent entry costs no extra hop. On a store of its own, the +// owner is asked. +func TestDeleteEntryMissAsksOwnerOnlyOnSeparateStore(t *testing.T) { + for _, tc := range []struct { + name string + sharesStore bool + forwards int32 + }{ + {"shared store", true, 0}, + {"separate store", false, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + fs, _ := createRouteServer(t) + fs.filer.Signature = 41 + owner := &fakeOwner{signature: 42} + if tc.sharesStore { + owner.signature = fs.filer.Signature + } + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + srv := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(srv, owner) + go func() { _ = srv.Serve(lis) }() + ownerAddr := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), lis.Addr().(*net.TCPAddr).Port) + t.Cleanup(func() { + srv.Stop() + pb.InvalidateGrpcConnection(ownerAddr.ToGrpcAddress()) + }) + setRing(fs, 0, []pb.ServerAddress{fs.option.Host, ownerAddr}) + + ma := filer.NewMetaAggregator(fs.filer, fs.option.Host, fs.grpcDialOption) + fs.filer.MetaAggregator = ma + t.Cleanup(ma.Shutdown) + ma.OnPeerUpdate(&master_pb.ClusterNodeUpdate{Address: string(ownerAddr), IsAdd: true}, time.Now()) + if tc.sharesStore { + deadline := time.Now().Add(10 * time.Second) + for !ma.SharesStore(ownerAddr) { + if time.Now().After(deadline) { + t.Fatal("the aggregator never read the owner's store signature") + } + time.Sleep(10 * time.Millisecond) + } + } + + name := peerOwnedName(t, fs) + resp, err := fs.DeleteEntry(context.Background(), &filer_pb.DeleteEntryRequest{Directory: "/test", Name: name}) + if err != nil || resp.GetError() != "" { + t.Fatalf("delete of an absent entry: resp=%v err=%v", resp, err) + } + if got := owner.deletes.Load(); got != tc.forwards { + t.Fatalf("owner received %d forwarded deletes, want %d", got, tc.forwards) + } + }) + } +} + +// A scoped delete is checked against this filer only, so it is never +// forwarded: the owner would apply it without the scope's checks. +func TestScopedDeleteEntryMissStaysLocal(t *testing.T) { + fs, _ := createRouteServer(t) + name := peerOwnedName(t, fs) + req := &filer_pb.DeleteEntryRequest{Directory: "/test", Name: name} + resp, err := fs.DeleteEntry(withScopeKeepOnly(context.Background()), req) + if err != nil || resp.GetError() != "" || req.IsMoved { + t.Fatalf("scoped delete of an absent entry: resp=%v err=%v forwarded=%v", resp, err, req.IsMoved) + } +} + +// While B's ring still gives the path to A, B refuses the delete A forwards +// rather than answer for a store the creates may not have reached. +func TestForwardedDeleteEntryRefusedByNonOwner(t *testing.T) { + slack := notWriteOwnerRetrySlack + notWriteOwnerRetrySlack = 200 * time.Millisecond + t.Cleanup(func() { notWriteOwnerRetrySlack = slack }) + + c := newTwoFilers(t) + storeB := separateStores(c) + setRing(c.fsA, 0, []pb.ServerAddress{c.addrA, c.addrB}) + setRing(c.fsB, time.Minute, []pb.ServerAddress{c.addrA}, []pb.ServerAddress{c.addrA, c.addrB}) + p := c.keyOwnedBy(t, c.addrB, c.addrA) + if err := storeB.InsertEntry(context.Background(), newFileEntry(string(p), 7)); err != nil { + t.Fatalf("seed B: %v", err) + } + + dir, name := p.DirAndName() + _, err := c.fsA.DeleteEntry(context.Background(), &filer_pb.DeleteEntryRequest{Directory: dir, Name: name}) + if !isNotWriteOwner(err) { + t.Fatalf("B applied or failed otherwise a delete its ring gives to A: %v", err) + } + if _, err := storeB.FindEntry(context.Background(), p); err != nil { + t.Fatalf("a refused forward deleted the entry: %v", err) + } +} diff --git a/weed/server/filer_grpc_server_route.go b/weed/server/filer_grpc_server_route.go index 437de8af27..a13a8b3a8a 100644 --- a/weed/server/filer_grpc_server_route.go +++ b/weed/server/filer_grpc_server_route.go @@ -9,6 +9,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/util" "google.golang.org/genproto/googleapis/rpc/errdetails" @@ -35,6 +36,41 @@ func (fs *FilerServer) writeOwner(key string) pb.ServerAddress { return owner } +// ownerKeepsOwnStore reports whether key's write owner is another filer that +// is not known to run on this filer's store. +func (fs *FilerServer) ownerKeepsOwnStore(key string) bool { + owner := fs.writeOwner(key) + if owner == "" { + return false + } + return fs.filer.MetaAggregator == nil || !fs.filer.MetaAggregator.SharesStore(owner) +} + +// forwardDeleteEntry sends the delete to its write owner. handled=false means +// this filer is the owner and applies it. +func (fs *FilerServer) forwardDeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest, fullpath util.FullPath) (*filer_pb.DeleteEntryResponse, bool, error) { + var ownerResp *filer_pb.DeleteEntryResponse + handled, err := fs.forwardToWriteOwner(ctx, entryRouteKey(fullpath), func(owner pb.ServerAddress) error { + if scopeKeepOnly(ctx) { + return status.Error(codes.PermissionDenied, "filer: scoped DeleteEntry cannot be forwarded to the write owner") + } + glog.V(2).InfofCtx(ctx, "DeleteEntry %s: forwarding to owner %s", fullpath, owner) + req.IsMoved = true + return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + forwarded, e := client.DeleteEntry(ctx, req) + if e != nil { + return e + } + ownerResp = forwarded + return nil + }) + }) + if err != nil { + return &filer_pb.DeleteEntryResponse{}, handled, err + } + return ownerResp, handled, nil +} + // forwardToWriteOwner sends the request to key's write owner so a single filer's // per-path lock arbitrates every writer of that key. handled=false means this // filer is the owner and the caller should apply the request locally.