mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
filer: refuse a forwarded conditional write on a filer that is not its owner (#12857)
* filer: refuse a forwarded conditional write on a non-owner A filer applied any routed write a ring peer forwarded, even when its own ring named another filer as the write owner. While two filers' rings disagree (a cooling-off window closing at different times, or a filer that installed the ring without the prior snapshot), each could apply a conditional write of the same entry under its own path lock, and both callers saw success. The receiver now refuses such a forward with Unavailable carrying a NOT_WRITE_OWNER reason, so the sender can tell nothing was applied. Refusing rather than re-forwarding keeps the one-hop bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: re-route a forward the owner refused as not its own A refused forward applied nothing, and the two rings converge once a ring update reaches the lagging filer or a cooling-off window closes. The sender now routes the write again by its own ring, with backoff, until shortly after its latest window ends, and surfaces the refusal only after that. A write whose owner turns out to be this filer is applied locally. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: test forwarded conditional updates between two filers Two filers on one store, each serving gRPC with its own ring: while the receiver's ring names the sender as the owner, the forward is refused and the entry is untouched; once the receiver's cooling-off window closes, the sender's retried forward applies once and a second update with the same expectation fails its condition. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: keep retrying a refused forward through a new ring change The retry deadline was taken from the cooling-off window seen at the first refusal. A ring change arriving during the retries opens a new window, in which the two rings can still disagree, so the deadline is now recomputed after every refusal, capped at 15 s from the first one so a ring that keeps changing cannot hold a request indefinitely. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: surface a refused forward rather than apply it locally A caller can check the entry before routing: an HTTP append verifies its snapshot under its locks and then commits locally without a condition. Once a forward is refused, the retries wait, and if this filer's ring then names itself, a local apply would act on that stale check and could overwrite an entry replaced meanwhile. The refusal now surfaces in that case, and the caller retries the whole request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ebd90c3a45
commit
14631d530b
6 files changed
+470
-34
No files matched your search
@@ -231,7 +231,7 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
|
||||
return ownerResp, nil
|
||||
}
|
||||
} else if req.IsMoved && routed {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(entryRouteKey(util.NewFullPath(req.Directory, req.Entry.Name)))); err != nil {
|
||||
if err := fs.checkForwardedWrite(ctx, entryRouteKey(util.NewFullPath(req.Directory, req.Entry.Name))); err != nil {
|
||||
return &filer_pb.CreateEntryResponse{}, err
|
||||
}
|
||||
}
|
||||
@@ -347,10 +347,12 @@ func (fs *FilerServer) ObjectTransaction(ctx context.Context, req *filer_pb.Obje
|
||||
// Route-by-key: if this filer is not the ring owner of route_key, forward the
|
||||
// whole transaction to the owner so its per-path lock is the single
|
||||
// serialization point — even when the caller's ring view was stale. is_moved
|
||||
// bounds this to one hop: a forwarded transaction is applied locally, so two
|
||||
// filers that disagree on the owner during a ring change cannot loop.
|
||||
if req.RouteKey != "" {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(req.RouteKey)); err != nil {
|
||||
// bounds this to one hop: a forwarded transaction is applied only by the
|
||||
// owner in this filer's ring, and refused with a status the sender retries.
|
||||
if req.RouteKey != "" && req.IsMoved {
|
||||
if err := fs.checkForwardedWrite(ctx, req.RouteKey); isNotWriteOwner(err) {
|
||||
return &filer_pb.ObjectTransactionResponse{}, err
|
||||
} else if err != nil {
|
||||
return &filer_pb.ObjectTransactionResponse{Error: err.Error()}, nil
|
||||
}
|
||||
}
|
||||
@@ -954,7 +956,7 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
|
||||
return ownerResp, nil
|
||||
}
|
||||
} else if req.IsMoved && routed {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(entryRouteKey(util.FullPath(fullpath)))); err != nil {
|
||||
if err := fs.checkForwardedWrite(ctx, entryRouteKey(util.FullPath(fullpath))); err != nil {
|
||||
return &filer_pb.UpdateEntryResponse{}, err
|
||||
}
|
||||
}
|
||||
@@ -1205,7 +1207,7 @@ func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntr
|
||||
return ownerResp, nil
|
||||
}
|
||||
} else {
|
||||
if err := fs.checkMovedMarker(ctx, req.IsMoved, fs.writeOwner(entryRouteKey(fullpath))); err != nil {
|
||||
if err := fs.checkForwardedWrite(ctx, entryRouteKey(fullpath)); err != nil {
|
||||
return &filer_pb.DeleteEntryResponse{}, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +78,20 @@ func peerOwnedName(t *testing.T, fs *FilerServer) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// selfOwnedName returns a child name under /test whose entry the ring assigns
|
||||
// to this filer.
|
||||
func selfOwnedName(t *testing.T, fs *FilerServer) string {
|
||||
t.Helper()
|
||||
for i := 0; i < 4000; i++ {
|
||||
name := fmt.Sprintf("obj-%d", i)
|
||||
if fs.writeOwner(entryRouteKey(util.NewFullPath("/test", name))) == "" {
|
||||
return name
|
||||
}
|
||||
}
|
||||
t.Skip("no name owned by this filer")
|
||||
return ""
|
||||
}
|
||||
|
||||
func createReq(name string, oExcl bool) *filer_pb.CreateEntryRequest {
|
||||
return &filer_pb.CreateEntryRequest{
|
||||
Directory: "/test",
|
||||
@@ -128,11 +142,10 @@ func ringPeerCtx() context.Context {
|
||||
})
|
||||
}
|
||||
|
||||
// is_moved bounds forwarding to one hop: the owner applies it even if its own
|
||||
// ring view says someone else owns the key.
|
||||
// A forwarded create is applied by the owner without forwarding it again.
|
||||
func TestCreateEntryMovedAppliesLocally(t *testing.T) {
|
||||
fs, store := createRouteServer(t)
|
||||
name := peerOwnedName(t, fs)
|
||||
name := selfOwnedName(t, fs)
|
||||
|
||||
req := createReq(name, true)
|
||||
req.IsMoved = true
|
||||
@@ -145,6 +158,24 @@ func TestCreateEntryMovedAppliesLocally(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A filer whose own ring names a peer as the owner refuses a forwarded create
|
||||
// rather than check it under its own lock: the sender's ring disagrees with
|
||||
// this one, and the peer's lock may be arbitrating the same entry.
|
||||
func TestCreateEntryMovedRefusedByNonOwner(t *testing.T) {
|
||||
fs, store := createRouteServer(t)
|
||||
name := peerOwnedName(t, fs)
|
||||
|
||||
req := createReq(name, true)
|
||||
req.IsMoved = true
|
||||
_, err := fs.CreateEntry(ringPeerCtx(), req)
|
||||
if !isNotWriteOwner(err) {
|
||||
t.Fatalf("a forwarded create on a non-owner must be refused as not the write owner, got err=%v", err)
|
||||
}
|
||||
if _, found := store.entries[string(util.NewFullPath("/test", name))]; found {
|
||||
t.Fatal("a refused forward must not write locally")
|
||||
}
|
||||
}
|
||||
|
||||
// A caller can set is_moved, but without a ring member's connection it is not
|
||||
// trusted: on a non-owner the request is refused rather than evaluated under
|
||||
// the wrong lock or forwarded again, where it could cycle while rings disagree.
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// receivedUpdates counts the UpdateEntry requests a filer receives over gRPC,
|
||||
// and how many of them another filer forwarded (is_moved).
|
||||
type receivedUpdates struct {
|
||||
mu sync.Mutex
|
||||
updates, moved int
|
||||
}
|
||||
|
||||
func (c *receivedUpdates) intercept(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if r, ok := req.(*filer_pb.UpdateEntryRequest); ok {
|
||||
c.mu.Lock()
|
||||
c.updates++
|
||||
if r.IsMoved {
|
||||
c.moved++
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
|
||||
func (c *receivedUpdates) counts() (updates, moved int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.updates, c.moved
|
||||
}
|
||||
|
||||
// twoFilers is filers A and B on one shared store, each serving gRPC with its
|
||||
// own ring view, so either can forward a routed write to the other.
|
||||
type twoFilers struct {
|
||||
store *renameTestStore
|
||||
dial grpc.DialOption
|
||||
addrA, addrB pb.ServerAddress
|
||||
fsA, fsB *FilerServer
|
||||
callsA, callsB *receivedUpdates
|
||||
}
|
||||
|
||||
func newTwoFilers(t *testing.T) *twoFilers {
|
||||
t.Helper()
|
||||
c := &twoFilers{
|
||||
store: newRenameTestStore(),
|
||||
dial: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
callsA: &receivedUpdates{},
|
||||
callsB: &receivedUpdates{},
|
||||
}
|
||||
c.store.entries["/"] = newDirectoryEntry("/", 1)
|
||||
serve := func(calls *receivedUpdates) (*FilerServer, pb.ServerAddress) {
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
host := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), lis.Addr().(*net.TCPAddr).Port)
|
||||
f := newRenameTestFiler(t, c.store)
|
||||
f.Dlm = lock_manager.NewDistributedLockManager(host)
|
||||
fs := &FilerServer{
|
||||
filer: f,
|
||||
option: &FilerOption{Host: host},
|
||||
grpcDialOption: c.dial,
|
||||
entryLockTable: util.NewLockTable[util.FullPath](),
|
||||
}
|
||||
srv := grpc.NewServer(grpc.UnaryInterceptor(calls.intercept))
|
||||
filer_pb.RegisterSeaweedFilerServer(srv, fs)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(func() {
|
||||
srv.Stop()
|
||||
pb.InvalidateGrpcConnection(host.ToGrpcAddress())
|
||||
})
|
||||
return fs, host
|
||||
}
|
||||
c.fsA, c.addrA = serve(c.callsA)
|
||||
c.fsB, c.addrB = serve(c.callsB)
|
||||
return c
|
||||
}
|
||||
|
||||
// setRing gives fs a ring built from the given snapshots, oldest first. Inside
|
||||
// the cooling-off window of the last change a moved key keeps its prior owner.
|
||||
func setRing(fs *FilerServer, window time.Duration, snapshots ...[]pb.ServerAddress) {
|
||||
fs.filer.Dlm.LockRing = lock_manager.NewLockRing(window)
|
||||
for i, servers := range snapshots {
|
||||
fs.filer.Dlm.LockRing.SetSnapshot(slices.Clone(servers), int64(i+1))
|
||||
}
|
||||
}
|
||||
|
||||
// keyOwnedBy returns a test path whose write owner is ownerInA in A's ring and
|
||||
// ownerInB in B's.
|
||||
func (c *twoFilers) keyOwnedBy(t *testing.T, ownerInA, ownerInB pb.ServerAddress) util.FullPath {
|
||||
t.Helper()
|
||||
for i := 0; i < 4000; i++ {
|
||||
p := util.FullPath(fmt.Sprintf("/forward-%d", i))
|
||||
key := entryRouteKey(p)
|
||||
if c.fsA.filer.Dlm.LockRing.WriteOwner(key) == ownerInA && c.fsB.filer.Dlm.LockRing.WriteOwner(key) == ownerInB {
|
||||
return p
|
||||
}
|
||||
}
|
||||
t.Fatalf("no path that A's ring gives to %s and B's ring gives to %s", ownerInA, ownerInB)
|
||||
return ""
|
||||
}
|
||||
|
||||
// seed stores p with the extended attribute v=seed and returns it as read.
|
||||
func (c *twoFilers) seed(t *testing.T, p util.FullPath) *filer_pb.Entry {
|
||||
t.Helper()
|
||||
e := newFileEntry(string(p), 7)
|
||||
e.Extended = map[string][]byte{"v": []byte("seed")}
|
||||
if err := c.store.InsertEntry(context.Background(), e); err != nil {
|
||||
t.Fatalf("seed %s: %v", p, err)
|
||||
}
|
||||
return e.ToProtoEntry()
|
||||
}
|
||||
|
||||
// update sends addr an UpdateEntry that sets v to value only while v is still
|
||||
// expected's.
|
||||
func (c *twoFilers) update(addr pb.ServerAddress, p util.FullPath, expected *filer_pb.Entry, value string) error {
|
||||
dir, _ := p.DirAndName()
|
||||
next := proto.Clone(expected).(*filer_pb.Entry)
|
||||
next.Extended = map[string][]byte{"v": []byte(value)}
|
||||
return pb.WithFilerClient(false, 0, addr, c.dial, func(client filer_pb.SeaweedFilerClient) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
_, err := client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
|
||||
Directory: dir,
|
||||
Entry: next,
|
||||
ExpectedExtended: map[string][]byte{"v": expected.Extended["v"]},
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (c *twoFilers) stored(t *testing.T, p util.FullPath) string {
|
||||
t.Helper()
|
||||
e, err := c.store.FindEntry(context.Background(), p)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", p, err)
|
||||
}
|
||||
return string(e.Extended["v"])
|
||||
}
|
||||
|
||||
// A's ring names B as the write owner of the entry, while B, inside the
|
||||
// cooling-off window of the change from {A} to {A, B}, names A. B must refuse
|
||||
// A's forwarded conditional update rather than check it under its own lock,
|
||||
// which another writer routed by B's ring would not take. A's ring has no
|
||||
// window left to close, so A surfaces the refusal after its retries.
|
||||
func TestForwardedConditionalUpdateRefusedByNonOwner(t *testing.T) {
|
||||
slack := notWriteOwnerRetrySlack
|
||||
notWriteOwnerRetrySlack = 200 * time.Millisecond
|
||||
t.Cleanup(func() { notWriteOwnerRetrySlack = slack })
|
||||
|
||||
c := newTwoFilers(t)
|
||||
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)
|
||||
expected := c.seed(t, p)
|
||||
|
||||
err := c.update(c.addrA, p, expected, "via-A")
|
||||
if !isNotWriteOwner(err) {
|
||||
t.Fatalf("B applied or failed otherwise a forward its ring gives to A: %v", err)
|
||||
}
|
||||
if got := c.stored(t, p); got != "seed" {
|
||||
t.Fatalf("a refused forward changed the entry to %q", got)
|
||||
}
|
||||
ua, ma := c.callsA.counts()
|
||||
ub, mb := c.callsB.counts()
|
||||
if ua != 1 || ma != 0 || ub < 2 || mb != ub {
|
||||
t.Fatalf("updates received: A %d (forwarded %d), B %d (forwarded %d); want one on A, retried forwards on B", ua, ma, ub, mb)
|
||||
}
|
||||
}
|
||||
|
||||
// The same disagreement ends when B's window closes and B's ring names B too:
|
||||
// A keeps re-routing the refused forward, B applies it once, and a second
|
||||
// update with the same expectation fails its condition.
|
||||
func TestForwardedConditionalUpdateAppliedOnceRingsAgree(t *testing.T) {
|
||||
const window = time.Second
|
||||
c := newTwoFilers(t)
|
||||
setRing(c.fsA, window, []pb.ServerAddress{c.addrA, c.addrB})
|
||||
setRing(c.fsB, window, []pb.ServerAddress{c.addrA}, []pb.ServerAddress{c.addrA, c.addrB})
|
||||
p := c.keyOwnedBy(t, c.addrB, c.addrA)
|
||||
expected := c.seed(t, p)
|
||||
|
||||
if err := c.update(c.addrA, p, expected, "via-A"); err != nil {
|
||||
t.Fatalf("update via A once the rings agree: %v", err)
|
||||
}
|
||||
if got := c.stored(t, p); got != "via-A" {
|
||||
t.Fatalf("stored %q, want via-A", got)
|
||||
}
|
||||
if ub, mb := c.callsB.counts(); ub < 2 || mb != ub {
|
||||
t.Fatalf("B received %d updates (%d forwarded), want a refused forward before the applied one", ub, mb)
|
||||
}
|
||||
|
||||
err := c.update(c.addrB, p, expected, "via-B")
|
||||
if status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("the second update with the same expectation must fail its condition, got %v", err)
|
||||
}
|
||||
if got := c.stored(t, p); got != "via-A" {
|
||||
t.Fatalf("stored %q after the losing update, want via-A", got)
|
||||
}
|
||||
}
|
||||
@@ -856,12 +856,11 @@ func TestObjectTransactionRouteKeyOwnerAppliesLocally(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A forwarded transaction (is_moved over a ring member's connection) applies
|
||||
// locally even when the ring names a different owner: is_moved bounds
|
||||
// forwarding to a single hop, so two filers that disagree on the owner during
|
||||
// a ring change cannot loop. Without the marker this would attempt to dial
|
||||
// the bogus owner instead of applying.
|
||||
func TestObjectTransactionIsMovedSkipsForward(t *testing.T) {
|
||||
// A forwarded transaction (is_moved over a ring member's connection) on a
|
||||
// filer whose ring names a different owner is refused, neither applied under
|
||||
// this filer's lock nor forwarded again, so two filers that disagree on the
|
||||
// owner during a ring change can neither both apply it nor loop.
|
||||
func TestObjectTransactionIsMovedRefusedByNonOwner(t *testing.T) {
|
||||
self := pb.ServerAddress("localhost:1")
|
||||
other := pb.ServerAddress("localhost:2")
|
||||
fs, store := newTxnTestServer(t, map[string]*filer.Entry{
|
||||
@@ -869,7 +868,7 @@ func TestObjectTransactionIsMovedSkipsForward(t *testing.T) {
|
||||
})
|
||||
withRing(fs, self, other) // ring owner is "other", not self
|
||||
|
||||
resp, err := fs.ObjectTransaction(ringPeerCtx(), &filer_pb.ObjectTransactionRequest{
|
||||
_, err := fs.ObjectTransaction(ringPeerCtx(), &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: "/buckets/b/obj",
|
||||
RouteKey: "s3.object.write:/buckets/b/obj",
|
||||
IsMoved: true,
|
||||
@@ -878,18 +877,16 @@ func TestObjectTransactionIsMovedSkipsForward(t *testing.T) {
|
||||
SetExtended: map[string][]byte{"X-Amz-Meta-k": []byte("v")},
|
||||
}},
|
||||
})
|
||||
if err != nil || resp.Error != "" {
|
||||
t.Fatalf("txn failed: err=%v resp=%q", err, resp.Error)
|
||||
if !isNotWriteOwner(err) {
|
||||
t.Fatalf("a forwarded txn on a non-owner must be refused as not the write owner, got err=%v", err)
|
||||
}
|
||||
if string(store.entries["/buckets/b/obj"].Extended["X-Amz-Meta-k"]) != "v" {
|
||||
t.Errorf("forwarded txn should apply locally: %v", store.entries["/buckets/b/obj"].Extended)
|
||||
if _, set := store.entries["/buckets/b/obj"].Extended["X-Amz-Meta-k"]; set {
|
||||
t.Errorf("a refused txn must not apply: %v", store.entries["/buckets/b/obj"].Extended)
|
||||
}
|
||||
}
|
||||
|
||||
// End-to-end forward hop: a non-owner filer dials the ring owner and the owner
|
||||
// applies the transaction. The owner's own ring points back at the (bogus)
|
||||
// sender, so it would re-forward and fail to dial unless is_moved is set on the
|
||||
// forwarded request — making this also assert that one-hop bound over the wire.
|
||||
// applies the transaction.
|
||||
func TestObjectTransactionForwardsToOwner(t *testing.T) {
|
||||
owner, ownerStore := newTxnTestServer(t, map[string]*filer.Entry{
|
||||
"/buckets/b/obj": {FullPath: "/buckets/b/obj", Attr: filer.Attr{Inode: 1, Mode: 0644}},
|
||||
@@ -905,9 +902,7 @@ func TestObjectTransactionForwardsToOwner(t *testing.T) {
|
||||
ownerAddr := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), port)
|
||||
sender := pb.ServerAddress("127.0.0.1:1") // bogus: nothing listens here
|
||||
|
||||
// owner's ring points back at the sender; only is_moved keeps it from
|
||||
// re-forwarding to (and failing to dial) that bogus address.
|
||||
withRing(owner, ownerAddr, sender)
|
||||
withRing(owner, ownerAddr, ownerAddr)
|
||||
owner.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
|
||||
srv := grpc.NewServer()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
@@ -44,18 +45,56 @@ func (fs *FilerServer) writeOwner(key string) pb.ServerAddress {
|
||||
// already committed — and an owner unreachable from here may be partitioned
|
||||
// rather than down, still serving the key to everyone else. The ring hands the
|
||||
// key on when the cooling-off window closes, so the outage is bounded.
|
||||
//
|
||||
// An owner that refuses the forward as not its own applied nothing: the two
|
||||
// rings disagree. They converge once a ring update reaches the lagging filer or
|
||||
// a cooling-off window closes, so the forward is re-routed by this filer's ring
|
||||
// until shortly after its latest window ends, then the refusal surfaces. It
|
||||
// also surfaces once this filer's ring names itself: a caller may have checked
|
||||
// the entry before routing, and that check is stale after the wait.
|
||||
func (fs *FilerServer) forwardToWriteOwner(ctx context.Context, key string, send func(owner pb.ServerAddress) error) (handled bool, err error) {
|
||||
owner := fs.writeOwner(key)
|
||||
if owner == "" {
|
||||
return false, nil
|
||||
}
|
||||
if err := send(owner); err != nil {
|
||||
var firstRefusal time.Time
|
||||
for wait := notWriteOwnerRetryWait; ; wait = min(2*wait, 10*notWriteOwnerRetryWait) {
|
||||
owner := fs.writeOwner(key)
|
||||
if owner == "" {
|
||||
return err != nil, err
|
||||
}
|
||||
if err = send(owner); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
glog.V(1).InfofCtx(ctx, "route %s to owner %s: %v", key, owner, err)
|
||||
return true, err
|
||||
if !isNotWriteOwner(err) {
|
||||
return true, err
|
||||
}
|
||||
if firstRefusal.IsZero() {
|
||||
firstRefusal = time.Now()
|
||||
}
|
||||
deadline := firstRefusal.Add(notWriteOwnerRetrySlack)
|
||||
if end := fs.filer.Dlm.LockRing.PriorOwnerWindowEnd().Add(notWriteOwnerRetrySlack); end.After(deadline) {
|
||||
deadline = end
|
||||
}
|
||||
if limit := firstRefusal.Add(notWriteOwnerRetryLimit); deadline.After(limit) {
|
||||
deadline = limit
|
||||
}
|
||||
if time.Now().Add(wait).After(deadline) {
|
||||
return true, err
|
||||
}
|
||||
timer := time.NewTimer(wait)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return true, err
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
var (
|
||||
notWriteOwnerRetryWait = 50 * time.Millisecond
|
||||
notWriteOwnerRetrySlack = time.Second
|
||||
notWriteOwnerRetryLimit = 15 * time.Second
|
||||
)
|
||||
|
||||
// entryRouteKey is the ring key for an entry's writes. It shares the S3
|
||||
// gateway's namespace so an object's ObjectTransaction and its CreateEntry
|
||||
// resolve to the same owner, and land on that filer's one per-path lock.
|
||||
@@ -178,3 +217,46 @@ func (fs *FilerServer) checkMovedMarker(ctx context.Context, isMoved bool, owner
|
||||
}
|
||||
return status.Errorf(codes.PermissionDenied, "is_moved not sent by a ring member; the key's owner is %s", owner)
|
||||
}
|
||||
|
||||
// notWriteOwnerReason marks a forwarded write refused by a filer whose own ring
|
||||
// names another write owner for the key.
|
||||
const notWriteOwnerReason = "NOT_WRITE_OWNER"
|
||||
|
||||
// checkForwardedWrite admits a routed write that arrived with is_moved only on
|
||||
// the key's write owner in this filer's own ring. While two rings disagree, a
|
||||
// forward applied here would be checked under a second filer's lock, and
|
||||
// re-forwarding it could cycle, so it is refused. The refusal is Unavailable
|
||||
// with a NOT_WRITE_OWNER reason, telling the sender nothing was applied.
|
||||
func (fs *FilerServer) checkForwardedWrite(ctx context.Context, key string) error {
|
||||
owner := fs.writeOwner(key)
|
||||
if err := fs.checkMovedMarker(ctx, true, owner); err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return nil
|
||||
}
|
||||
return notWriteOwnerError(key, owner)
|
||||
}
|
||||
|
||||
func notWriteOwnerError(key string, owner pb.ServerAddress) error {
|
||||
st := status.Newf(codes.Unavailable, "not the write owner of %s: %s is", key, owner)
|
||||
withReason, err := st.WithDetails(&errdetails.ErrorInfo{Reason: notWriteOwnerReason, Domain: "seaweedfs"})
|
||||
if err != nil {
|
||||
return st.Err()
|
||||
}
|
||||
return withReason.Err()
|
||||
}
|
||||
|
||||
// isNotWriteOwner reports whether err is checkForwardedWrite's refusal.
|
||||
func isNotWriteOwner(err error) bool {
|
||||
st, ok := util.ServerStatus(err)
|
||||
if !ok || st.Code() != codes.Unavailable {
|
||||
return false
|
||||
}
|
||||
for _, d := range st.Details() {
|
||||
if info, ok := d.(*errdetails.ErrorInfo); ok && info.GetReason() == notWriteOwnerReason {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
@@ -106,3 +107,112 @@ func TestForwardToWriteOwnerNeverTriesASecondFiler(t *testing.T) {
|
||||
t.Fatalf("expected exactly the prior owner, tried %v", tried)
|
||||
}
|
||||
}
|
||||
|
||||
// windowlessRouteServer is routeTestServer with no cooling-off window, so a
|
||||
// ring change moves keys at once and the latest window has already closed.
|
||||
func windowlessRouteServer(host pb.ServerAddress, servers []pb.ServerAddress) *FilerServer {
|
||||
fs := routeTestServer(host)
|
||||
fs.filer.Dlm.LockRing = lock_manager.NewLockRing(0)
|
||||
fs.filer.Dlm.LockRing.SetSnapshot(servers, 1)
|
||||
return fs
|
||||
}
|
||||
|
||||
// A refused forward is not applied locally once this filer's ring names
|
||||
// itself: the caller checked the entry before routing, and the wait made that
|
||||
// check stale, so the refusal surfaces for the caller to retry.
|
||||
func TestForwardToWriteOwnerSurfacesARefusalOnceOwned(t *testing.T) {
|
||||
fs := windowlessRouteServer("f2:8888", routeSetA)
|
||||
ring := fs.filer.Dlm.LockRing
|
||||
|
||||
key := firstKey(t, func(key string) bool { return ring.GetPrimary(key) != "f2:8888" })
|
||||
var tried []pb.ServerAddress
|
||||
handled, err := fs.forwardToWriteOwner(context.Background(), key, func(owner pb.ServerAddress) error {
|
||||
tried = append(tried, owner)
|
||||
ring.SetSnapshot([]pb.ServerAddress{"f2:8888"}, 2)
|
||||
return notWriteOwnerError(key, "f2:8888")
|
||||
})
|
||||
if !handled || !isNotWriteOwner(err) {
|
||||
t.Fatalf("a refused forward must not fall back to a local apply, got handled=%v err=%v", handled, err)
|
||||
}
|
||||
if len(tried) != 1 {
|
||||
t.Fatalf("expected one forward before the ring named this filer, tried %v", tried)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardToWriteOwnerRetriesARefusal(t *testing.T) {
|
||||
fs := windowlessRouteServer("f9:8888", routeSetA)
|
||||
ring := fs.filer.Dlm.LockRing
|
||||
|
||||
key := firstKey(t, func(string) bool { return true })
|
||||
var tried []pb.ServerAddress
|
||||
handled, err := fs.forwardToWriteOwner(context.Background(), key, func(owner pb.ServerAddress) error {
|
||||
tried = append(tried, owner)
|
||||
if len(tried) < 3 {
|
||||
return notWriteOwnerError(key, "f9:8888")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !handled || err != nil {
|
||||
t.Fatalf("the owner accepting a retried forward must succeed, got handled=%v err=%v", handled, err)
|
||||
}
|
||||
if len(tried) != 3 || tried[0] != ring.GetPrimary(key) || tried[2] != ring.GetPrimary(key) {
|
||||
t.Fatalf("expected three forwards to %s, tried %v", ring.GetPrimary(key), tried)
|
||||
}
|
||||
}
|
||||
|
||||
// Rings that stay apart (a filer cut off from the master) must not hold the
|
||||
// write forever: the refusal surfaces once the retry budget is spent.
|
||||
func TestForwardToWriteOwnerSurfacesAPersistentRefusal(t *testing.T) {
|
||||
wait, slack := notWriteOwnerRetryWait, notWriteOwnerRetrySlack
|
||||
notWriteOwnerRetryWait, notWriteOwnerRetrySlack = 5*time.Millisecond, 100*time.Millisecond
|
||||
t.Cleanup(func() { notWriteOwnerRetryWait, notWriteOwnerRetrySlack = wait, slack })
|
||||
fs := windowlessRouteServer("f9:8888", routeSetA)
|
||||
|
||||
key := firstKey(t, func(string) bool { return true })
|
||||
tries := 0
|
||||
start := time.Now()
|
||||
handled, err := fs.forwardToWriteOwner(context.Background(), key, func(pb.ServerAddress) error {
|
||||
tries++
|
||||
return notWriteOwnerError(key, "f9:8888")
|
||||
})
|
||||
if !handled || !isNotWriteOwner(err) {
|
||||
t.Fatalf("a persistent refusal must surface, got handled=%v err=%v", handled, err)
|
||||
}
|
||||
if tries < 2 {
|
||||
t.Fatalf("expected the refusal to be retried, tried %d times", tries)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 2*time.Second {
|
||||
t.Fatalf("retries outlived their budget: %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// A ring change that arrives while a refused forward is being retried starts a
|
||||
// new cooling-off window, and the retries wait for that one too.
|
||||
func TestForwardToWriteOwnerWaitsOutANewWindow(t *testing.T) {
|
||||
wait, slack := notWriteOwnerRetryWait, notWriteOwnerRetrySlack
|
||||
notWriteOwnerRetryWait, notWriteOwnerRetrySlack = 5*time.Millisecond, 50*time.Millisecond
|
||||
t.Cleanup(func() { notWriteOwnerRetryWait, notWriteOwnerRetrySlack = wait, slack })
|
||||
const window = 100 * time.Millisecond
|
||||
fs := routeTestServer("f9:8888")
|
||||
ring := lock_manager.NewLockRing(window)
|
||||
ring.SetSnapshot(routeSetA, 1)
|
||||
fs.filer.Dlm.LockRing = ring
|
||||
time.Sleep(window + 10*time.Millisecond)
|
||||
|
||||
key := firstKey(t, func(string) bool { return true })
|
||||
tries := 0
|
||||
start := time.Now()
|
||||
handled, err := fs.forwardToWriteOwner(context.Background(), key, func(pb.ServerAddress) error {
|
||||
tries++
|
||||
if tries == 2 {
|
||||
ring.SetSnapshot(routeSetB, 2)
|
||||
}
|
||||
if time.Since(start) < window {
|
||||
return notWriteOwnerError(key, "f9:8888")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !handled || err != nil {
|
||||
t.Fatalf("a refusal must be retried through a window that opened during the retries, got handled=%v err=%v after %d tries", handled, err, tries)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user