From 865a7bd9886a016680e09ab37fc254aae4229f02 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Fri, 20 Nov 2026 13:07:18 -0800 Subject: [PATCH] filer: commit an HTTP append on a non-owner through the entry's owner (#12849) * filer: commit an HTTP append on a non-owner through the entry's owner An HTTP append or offset write re-read the entry under its path lock and cluster lock and then committed with an unconditional upsert. The path lock is per process and the cluster lock is a lease, so with several filers on one store a write landing between the re-read and the upsert was overwritten although both requests were acknowledged. A filer that is not the entry's write owner now sends the commit to the owner as a CreateEntry conditioned on the entry it read (IF_ENTRY_EQUAL, absent when there was none), evaluated under the owner's path lock. The owner keeps committing locally under that same lock. A failed condition refuses the append as a changed entry; any other routed error keeps the uploaded chunks the stored entry references. Co-Authored-By: Claude Opus 5.5 * filer: test an HTTP append racing another filer's append Two filers on one store share a two-member ring. An append on the non-owner gets another filer's append injected at the store after each of its reads of the entry in turn; it must either keep both appends or be refused. Without the routed conditional commit, injections after the re-read are overwritten. Co-Authored-By: Claude Opus 5.5 * filer: keep the chunks of a forwarded append whose outcome is unknown The owner may have committed before its reply was lost, and with separate per-filer stores the local lookup may not see that commit yet, so deleting the chunks it does not find can strip a committed append. Co-Authored-By: Claude Opus 5.5 * filer: keep fsync appends on the local commit A per-request fsync is a local context mark that a forwarded CreateEntry cannot carry, so the owner would store the append without flushing. Storage-rule fsync is still applied on the owner. Co-Authored-By: Claude Opus 5.5 * filer: normalize the stored entry too when matching IF_ENTRY_EQUAL A store that keeps the entry as given (the JSON-backed ones) returns FileSize zero beside chunks, while the expected entry was normalized to the chunk extent, so an unchanged entry failed the match. Co-Authored-By: Claude Opus 5.5 * filer: carry a create's fsync request in CreateEntryRequest The per-request fsync is a context mark on the receiving filer, so a create forwarded to another filer lost it. CreateEntry now applies the request's fsync flag to its store write. Co-Authored-By: Claude Opus 5.5 * filer: route fsync appends to the owner with the fsync flag A fsync append on a non-owner committed locally without a condition, so it could still overwrite a write the owner committed after its re-read. Co-Authored-By: Claude Opus 5.5 * filer: test an offset write on a store that keeps FileSize as given Co-Authored-By: Claude Opus 5.5 * filer: start an append at the entry's full size A store that keeps the entry as given can return FileSize zero beside chunks, so the append chunks were placed at offset zero over the existing bytes. Co-Authored-By: Claude Opus 5.5 * filer: test an append on a store that keeps FileSize as given Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- other/java/client/src/main/proto/filer.proto | 2 + weed/pb/filer.proto | 2 + weed/pb/filer_pb/filer.pb.go | 16 +- weed/pb/filer_pb/filer_vtproto.pb.go | 33 ++ weed/server/filer_grpc_server.go | 3 + weed/server/filer_grpc_server_condition.go | 10 +- .../filer_grpc_server_condition_test.go | 22 + ..._server_handlers_write_append_race_test.go | 379 ++++++++++++++++++ .../filer_server_handlers_write_autochunk.go | 35 +- 9 files changed, 493 insertions(+), 9 deletions(-) create mode 100644 weed/server/filer_server_handlers_write_append_race_test.go diff --git a/other/java/client/src/main/proto/filer.proto b/other/java/client/src/main/proto/filer.proto index a72377096d..23e4848e9a 100644 --- a/other/java/client/src/main/proto/filer.proto +++ b/other/java/client/src/main/proto/filer.proto @@ -262,6 +262,8 @@ message CreateEntryRequest { // Set on a create a filer forwarded to the entry's ring owner, so the owner // applies it locally instead of forwarding again. Clients leave it unset. bool is_moved = 8; + // The store write must be durable before the reply, as for ?fsync=true. + bool fsync = 9; } // WriteCondition is the precondition the filer evaluates against the existing diff --git a/weed/pb/filer.proto b/weed/pb/filer.proto index 18486d3c7c..216fe5ebbf 100644 --- a/weed/pb/filer.proto +++ b/weed/pb/filer.proto @@ -262,6 +262,8 @@ message CreateEntryRequest { // Set on a create a filer forwarded to the entry's ring owner, so the owner // applies it locally instead of forwarding again. Clients leave it unset. bool is_moved = 8; + // The store write must be durable before the reply, as for ?fsync=true. + bool fsync = 9; } // WriteCondition is the precondition the filer evaluates against the existing diff --git a/weed/pb/filer_pb/filer.pb.go b/weed/pb/filer_pb/filer.pb.go index 6fafc60625..c3428a2d8e 100644 --- a/weed/pb/filer_pb/filer.pb.go +++ b/weed/pb/filer_pb/filer.pb.go @@ -1398,7 +1398,9 @@ type CreateEntryRequest struct { Condition *WriteCondition `protobuf:"bytes,7,opt,name=condition,proto3" json:"condition,omitempty"` // Set on a create a filer forwarded to the entry's ring owner, so the owner // applies it locally instead of forwarding again. Clients leave it unset. - IsMoved bool `protobuf:"varint,8,opt,name=is_moved,json=isMoved,proto3" json:"is_moved,omitempty"` + IsMoved bool `protobuf:"varint,8,opt,name=is_moved,json=isMoved,proto3" json:"is_moved,omitempty"` + // The store write must be durable before the reply, as for ?fsync=true. + Fsync bool `protobuf:"varint,9,opt,name=fsync,proto3" json:"fsync,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1489,6 +1491,13 @@ func (x *CreateEntryRequest) GetIsMoved() bool { return false } +func (x *CreateEntryRequest) GetFsync() bool { + if x != nil { + return x.Fsync + } + return false +} + // WriteCondition is the precondition the filer evaluates against the existing // entry before writing, under the per-path lock. A failed condition returns // FilerError PRECONDITION_FAILED. The client maps request semantics (e.g. RFC @@ -7492,7 +7501,7 @@ const file_filer_proto_rawDesc = "" + "\bctime_ns\x18\x14 \x01(\x05R\actimeNs\x12\x1b\n" + "\tcrtime_ns\x18\x15 \x01(\x05R\bcrtimeNs\x12\x14\n" + "\x05atime\x18\x16 \x01(\x03R\x05atime\x12\x19\n" + - "\batime_ns\x18\x17 \x01(\x05R\aatimeNs\"\xd5\x02\n" + + "\batime_ns\x18\x17 \x01(\x05R\aatimeNs\"\xeb\x02\n" + "\x12CreateEntryRequest\x12\x1c\n" + "\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" + "\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12\x15\n" + @@ -7503,7 +7512,8 @@ const file_filer_proto_rawDesc = "" + "signatures\x12=\n" + "\x1bskip_check_parent_directory\x18\x06 \x01(\bR\x18skipCheckParentDirectory\x126\n" + "\tcondition\x18\a \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x12\x19\n" + - "\bis_moved\x18\b \x01(\bR\aisMoved\"\x9e\x05\n" + + "\bis_moved\x18\b \x01(\bR\aisMoved\x12\x14\n" + + "\x05fsync\x18\t \x01(\bR\x05fsync\"\x9e\x05\n" + "\x0eWriteCondition\x129\n" + "\aclauses\x18\x01 \x03(\v2\x1f.filer_pb.WriteCondition.ClauseR\aclauses\x1a\xc9\x02\n" + "\x06Clause\x121\n" + diff --git a/weed/pb/filer_pb/filer_vtproto.pb.go b/weed/pb/filer_pb/filer_vtproto.pb.go index 9a3b40547c..341e816a60 100644 --- a/weed/pb/filer_pb/filer_vtproto.pb.go +++ b/weed/pb/filer_pb/filer_vtproto.pb.go @@ -1019,6 +1019,16 @@ func (m *CreateEntryRequest) MarshalToSizedBufferVT(dAtA []byte) (int, error) { i -= len(m.unknownFields) copy(dAtA[i:], m.unknownFields) } + if m.Fsync { + i-- + if m.Fsync { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x48 + } if m.IsMoved { i-- if m.IsMoved { @@ -7092,6 +7102,9 @@ func (m *CreateEntryRequest) SizeVT() (n int) { if m.IsMoved { n += 2 } + if m.Fsync { + n += 2 + } n += len(m.unknownFields) return n } @@ -12350,6 +12363,26 @@ func (m *CreateEntryRequest) UnmarshalVT(dAtA []byte) error { } } m.IsMoved = bool(v != 0) + case 9: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Fsync", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return protohelpers.ErrIntOverflow + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Fsync = bool(v != 0) default: iNdEx = preIndex skippy, err := protohelpers.Skip(dAtA[iNdEx:]) diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index 7bccd584fe..3e62acdd02 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -289,6 +289,9 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr existing = current } + if req.Fsync { + ctx = filer.WithSyncWrite(ctx) + } ctx, eventSink := filer.WithMetadataEventSink(ctx) createErr := fs.filer.CreateEntry(ctx, newEntry, existing, req.OExcl, req.IsFromOtherCluster, req.Signatures, req.SkipCheckParentDirectory, so.MaxFileNameLength) diff --git a/weed/server/filer_grpc_server_condition.go b/weed/server/filer_grpc_server_condition.go index 31442b18fb..093c1c957f 100644 --- a/weed/server/filer_grpc_server_condition.go +++ b/weed/server/filer_grpc_server_condition.go @@ -90,14 +90,16 @@ func clauseSatisfied(c *filer_pb.WriteCondition_Clause, current *filer.Entry) bo if !exists || c.ExpectedEntry == nil { return !exists && c.ExpectedEntry == nil } - // Compare both sides in serialized form on clones: chunks are matched - // by their fid only — the stored entry may carry the restored file_id - // while an expected one built from a metadata event does not. + // Compare both sides in serialized, normalized form on clones: chunks + // are matched by their fid only — the stored entry may carry the + // restored file_id while an expected one built from a metadata event + // does not — and a store that does not decode through FromPbEntry + // keeps the FileSize it was given. expected := proto.Clone(c.ExpectedEntry).(*filer_pb.Entry) filer_pb.BeforeEntrySerialization(expected.Chunks) actual := proto.Clone(current.ToProtoEntry()).(*filer_pb.Entry) filer_pb.BeforeEntrySerialization(actual.Chunks) - return proto.Equal(actual, filer.FromPbEntry("", expected).ToProtoEntry()) + return proto.Equal(filer.FromPbEntry("", actual).ToProtoEntry(), filer.FromPbEntry("", expected).ToProtoEntry()) default: // An unrecognized clause kind (e.g. from a newer client) must not be // treated as satisfied, which would silently bypass the guard. Fail diff --git a/weed/server/filer_grpc_server_condition_test.go b/weed/server/filer_grpc_server_condition_test.go index 548f153e93..5b775f73cd 100644 --- a/weed/server/filer_grpc_server_condition_test.go +++ b/weed/server/filer_grpc_server_condition_test.go @@ -230,6 +230,28 @@ func TestIfEntryEqualNormalizesExpected(t *testing.T) { } } +// A store that keeps the entry as given (JSON-backed stores) returns FileSize +// zero beside chunks; an expected entry read from it must still match it. +func TestIfEntryEqualUnnormalizedStored(t *testing.T) { + stored := &filer.Entry{ + FullPath: "/d/f", + Attr: filer.Attr{Mtime: time.Unix(42, 0)}, + Chunks: []*filer_pb.FileChunk{ + {Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 1, Cookie: 2}, Size: 4}, + }, + } + cond := one(&filer_pb.WriteCondition_Clause{ + Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, + ExpectedEntry: stored.ToProtoEntry(), + }) + if !writeConditionSatisfied(cond, stored) { + t.Error("an entry read from the store must equal the stored entry") + } + if stored.FileSize != 0 { + t.Fatalf("the check changed the stored entry's FileSize to %d", stored.FileSize) + } +} + // A stamp built from the metadata-log event carries chunks in serialized // form (file_id moved into fid), while the stored entry came through // FindEntry which restores file_id. The comparison must still match. diff --git a/weed/server/filer_server_handlers_write_append_race_test.go b/weed/server/filer_server_handlers_write_append_race_test.go new file mode 100644 index 0000000000..494edf79c3 --- /dev/null +++ b/weed/server/filer_server_handlers_write_append_race_test.go @@ -0,0 +1,379 @@ +package weed_server + +import ( + "bytes" + "context" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager" + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/operation" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// appendRaceFindHookStore runs a hook after each FindEntry returns, so a test +// can interleave another writer between a caller's read and its write. +type appendRaceFindHookStore struct { + *renameTestStore + hookMu sync.Mutex + hook func(p util.FullPath) +} + +func (s *appendRaceFindHookStore) FindEntry(ctx context.Context, p util.FullPath) (*filer.Entry, error) { + entry, err := s.renameTestStore.FindEntry(ctx, p) + s.hookMu.Lock() + hook := s.hook + s.hookMu.Unlock() + if hook != nil { + hook(p) + } + return entry, err +} + +func (s *appendRaceFindHookStore) setHook(hook func(p util.FullPath)) { + s.hookMu.Lock() + s.hook = hook + s.hookMu.Unlock() +} + +// appendRaceSyncStore records, per path, whether each entry write was asked +// to be durable before returning. +type appendRaceSyncStore struct { + *renameTestStore + mu sync.Mutex + synced map[util.FullPath][]bool +} + +func (s *appendRaceSyncStore) record(ctx context.Context, p util.FullPath) { + s.mu.Lock() + defer s.mu.Unlock() + s.synced[p] = append(s.synced[p], filer.SyncWrite(ctx)) +} + +func (s *appendRaceSyncStore) writes(p util.FullPath) []bool { + s.mu.Lock() + defer s.mu.Unlock() + return append([]bool(nil), s.synced[p]...) +} + +func (s *appendRaceSyncStore) InsertEntry(ctx context.Context, entry *filer.Entry) error { + s.record(ctx, entry.FullPath) + return s.renameTestStore.InsertEntry(ctx, entry) +} + +func (s *appendRaceSyncStore) UpdateEntry(ctx context.Context, entry *filer.Entry) error { + s.record(ctx, entry.FullPath) + return s.renameTestStore.UpdateEntry(ctx, entry) +} + +// newAppendRaceFilers starts two gRPC-serving filers on one store with the same +// two-member ring. Only the second filer's reads run the hook; ownerWrites +// records the first filer's entry writes. +func newAppendRaceFilers(t *testing.T) (owner, other *FilerServer, store *appendRaceFindHookStore, ownerWrites *appendRaceSyncStore) { + t.Helper() + inner := newRenameTestStore() + inner.entries["/"] = newDirectoryEntry("/", 1) + store = &appendRaceFindHookStore{renameTestStore: inner} + ownerWrites = &appendRaceSyncStore{renameTestStore: inner, synced: map[util.FullPath][]bool{}} + + newServer := func(hooked bool) (*FilerServer, net.Listener) { + f := newRenameTestFiler(t, inner) + if hooked { + f.Store = filer.NewFilerStoreWrapper(store) + } else { + f.Store = filer.NewFilerStoreWrapper(ownerWrites) + } + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + return &FilerServer{ + filer: f, + option: &FilerOption{SaveToFilerLimit: 64, MaxMB: 1}, + entryLockTable: util.NewLockTable[util.FullPath](), + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, lis + } + owner, ownerLis := newServer(false) + other, otherLis := newServer(true) + addr := func(lis net.Listener) pb.ServerAddress { + return pb.NewServerAddressWithGrpcPort(lis.Addr().String(), lis.Addr().(*net.TCPAddr).Port) + } + ring := []pb.ServerAddress{addr(ownerLis), addr(otherLis)} + for _, s := range []struct { + fs *FilerServer + lis net.Listener + }{{owner, ownerLis}, {other, otherLis}} { + self := addr(s.lis) + s.fs.option.Host = self + s.fs.filer.Dlm = lock_manager.NewDistributedLockManager(self) + s.fs.filer.Dlm.LockRing.SetSnapshot(ring, 1) + srv := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(srv, s.fs) + go srv.Serve(s.lis) + t.Cleanup(srv.Stop) + pb.InvalidateGrpcConnection(self.ToGrpcAddress()) + } + return owner, other, store, ownerWrites +} + +// ownerPath returns a file path whose writes the ring gives to owner. +func ownerPath(t *testing.T, owner, other *FilerServer) string { + t.Helper() + for i := 0; i < 4000; i++ { + p := fmt.Sprintf("/append-%d.txt", i) + if other.writeOwner(entryRouteKey(util.FullPath(p))) == owner.option.Host { + return p + } + } + t.Skip("no path owned by the first filer") + return "" +} + +// An HTTP append on a filer that does not own the entry must not overwrite an +// append another filer commits after this one read the entry: either both +// acknowledged appends are in the final entry, or this append is refused. +// The other append is injected at the store right after one of this filer's +// reads of the entry, each read in turn, with and without fsync. +func TestHttpAppendDoesNotOverwriteConcurrentAppend(t *testing.T) { + for _, fsync := range []bool{false, true} { + injected := 0 + for read := 1; read <= 8; read++ { + t.Run(fmt.Sprintf("fsync_%v/after_read_%d", fsync, read), func(t *testing.T) { + if httpAppendWithConcurrentAppend(t, read, fsync) { + injected++ + } + }) + } + if injected == 0 { + t.Fatalf("fsync=%v: the other filer's append was never injected: the race was not exercised", fsync) + } + } +} + +func httpAppendWithConcurrentAppend(t *testing.T, atRead int, fsync bool) bool { + ctx := context.Background() + if fsync { + ctx = filer.WithSyncWrite(ctx) + } + oldContent := []byte("old-") + appendA := []byte("A-") + appendB := []byte("B-") + + owner, fs, store, _ := newAppendRaceFilers(t) + filePath := ownerPath(t, owner, fs) + fileName := util.FullPath(filePath).Name() + if err := store.renameTestStore.InsertEntry(ctx, &filer.Entry{ + FullPath: util.FullPath(filePath), + Attr: filer.Attr{ + Mtime: time.Unix(1, 0), + Atime: time.Unix(1, 0), + Crtime: time.Unix(1, 0), + Mode: 0640, + FileSize: uint64(len(oldContent)), + }, + Content: append([]byte(nil), oldContent...), + }); err != nil { + t.Fatalf("insert inline entry: %v", err) + } + + so := &operation.StorageOption{} + r := httptest.NewRequest(http.MethodPut, filePath+"?op=append", bytes.NewReader(appendA)) + r.ContentLength = -1 + + fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks( + ctx, httptest.NewRecorder(), r, r.Body, 4, fileName, "", -1, so, + ) + if err != nil { + t.Fatalf("prepare append: %v", err) + } + + var mu sync.Mutex + reads := 0 + otherWrote := false + store.setHook(func(p util.FullPath) { + if p != util.FullPath(filePath) { + return + } + mu.Lock() + reads++ + hit := reads == atRead + mu.Unlock() + if !hit { + return + } + content := append(append([]byte(nil), oldContent...), appendB...) + if err := store.renameTestStore.UpdateEntry(ctx, &filer.Entry{ + FullPath: util.FullPath(filePath), + Attr: filer.Attr{ + Mtime: time.Unix(2, 0), + Atime: time.Unix(2, 0), + Crtime: time.Unix(1, 0), + Mode: 0640, + FileSize: uint64(len(content)), + }, + Content: content, + }); err != nil { + t.Errorf("the other filer's append: %v", err) + return + } + mu.Lock() + otherWrote = true + mu.Unlock() + }) + + _, saveErr, _ := fs.saveMetaData(ctx, r, fileName, "", so, 4, md5Hash.Sum(nil), fileChunks, chunkOffset, smallContent) + store.setHook(nil) + + mu.Lock() + wrote, sawReads := otherWrote, reads + mu.Unlock() + if !wrote { + t.Skipf("the append reads the entry %d times before its commit; no read %d", sawReads, atRead) + } + + final, err := owner.filer.FindEntry(ctx, util.FullPath(filePath)) + if err != nil { + t.Fatalf("find final entry: %v", err) + } + got := string(final.Content) + if saveErr != nil { + if got != string(oldContent)+string(appendB) { + t.Errorf("append refused (%v) but the entry is %q, want %q", saveErr, got, string(oldContent)+string(appendB)) + } + return true + } + if !strings.Contains(got, string(appendB)) || !strings.Contains(got, string(appendA)) { + t.Errorf("both appends were acknowledged but the entry is %q: the other filer's %q was overwritten", got, appendB) + } + return true +} + +// Without a concurrent writer, an append on a non-owner commits through the +// owner, keeping its fsync, and lands in full. +func TestHttpAppendOnNonOwnerCommitsThroughOwner(t *testing.T) { + for _, fsync := range []bool{false, true} { + t.Run(fmt.Sprintf("fsync_%v", fsync), func(t *testing.T) { + httpAppendOnNonOwner(t, fsync) + }) + } +} + +func httpAppendOnNonOwner(t *testing.T, fsync bool) { + ctx := context.Background() + if fsync { + ctx = filer.WithSyncWrite(ctx) + } + owner, fs, store, ownerWrites := newAppendRaceFilers(t) + filePath := ownerPath(t, owner, fs) + fileName := util.FullPath(filePath).Name() + if err := store.renameTestStore.InsertEntry(ctx, &filer.Entry{ + FullPath: util.FullPath(filePath), + Attr: filer.Attr{Mtime: time.Unix(1, 0), Atime: time.Unix(1, 0), Crtime: time.Unix(1, 0), Mode: 0640, FileSize: 4}, + Content: []byte("old-"), + }); err != nil { + t.Fatalf("insert inline entry: %v", err) + } + + so := &operation.StorageOption{} + r := httptest.NewRequest(http.MethodPut, filePath+"?op=append", bytes.NewReader([]byte("A-"))) + r.ContentLength = -1 + fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks( + ctx, httptest.NewRecorder(), r, r.Body, 4, fileName, "", -1, so, + ) + if err != nil { + t.Fatalf("prepare append: %v", err) + } + if _, saveErr, _ := fs.saveMetaData(ctx, r, fileName, "", so, 4, md5Hash.Sum(nil), fileChunks, chunkOffset, smallContent); saveErr != nil { + t.Fatalf("append: %v", saveErr) + } + final, err := owner.filer.FindEntry(ctx, util.FullPath(filePath)) + if err != nil { + t.Fatalf("find final entry: %v", err) + } + if got := string(final.Content); got != "old-A-" { + t.Fatalf("entry is %q, want %q", got, "old-A-") + } + if got := ownerWrites.writes(util.FullPath(filePath)); len(got) != 1 || got[0] != fsync { + t.Errorf("the owner's writes asked for sync %v, want [%v]", got, fsync) + } +} + +// A create that asks for fsync reaches the store as a sync write. +func TestCreateEntryFsyncReachesStore(t *testing.T) { + owner, _, _, ownerWrites := newAppendRaceFilers(t) + for _, fsync := range []bool{false, true} { + p := util.FullPath(fmt.Sprintf("/fsync-%v.txt", fsync)) + resp, err := owner.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{ + Directory: "/", + Entry: &filer_pb.Entry{Name: p.Name(), Attributes: &filer_pb.FuseAttributes{Mtime: 1, FileMode: 0640}}, + Fsync: fsync, + }) + if err != nil || resp.Error != "" { + t.Fatalf("create %s: %v %s", p, err, resp.GetError()) + } + if got := ownerWrites.writes(p); len(got) != 1 || got[0] != fsync { + t.Errorf("fsync=%v: the store writes asked for sync %v, want [%v]", fsync, got, fsync) + } + } +} + +// A store that keeps entries as given returns FileSize zero beside chunks; an +// uncontended append or offset write on a non-owner must still commit through +// the owner and land after the existing bytes. +func TestHttpWriteOnNonOwnerWithUnnormalizedEntry(t *testing.T) { + for _, tc := range []struct { + name, query string + offset int64 + }{ + {"offset write", "", 4}, + {"append", "?op=append", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + owner, fs, store, _ := newAppendRaceFilers(t) + filePath := ownerPath(t, owner, fs) + fileName := util.FullPath(filePath).Name() + if err := store.renameTestStore.InsertEntry(ctx, &filer.Entry{ + FullPath: util.FullPath(filePath), + Attr: filer.Attr{Mtime: time.Unix(1, 0), Atime: time.Unix(1, 0), Crtime: time.Unix(1, 0), Mode: 0640}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 4, ModifiedTsNs: 1}}, + }); err != nil { + t.Fatalf("insert chunked entry: %v", err) + } + + r := httptest.NewRequest(http.MethodPut, filePath+tc.query, nil) + fileChunks := []*filer_pb.FileChunk{{FileId: "3,02637037d6", Offset: tc.offset, Size: 2, ModifiedTsNs: 2}} + if _, saveErr, _ := fs.saveMetaData(ctx, r, fileName, "", &operation.StorageOption{}, 4, nil, fileChunks, tc.offset+2, nil); saveErr != nil { + t.Fatalf("write: %v", saveErr) + } + final, err := owner.filer.FindEntry(ctx, util.FullPath(filePath)) + if err != nil { + t.Fatalf("find final entry: %v", err) + } + if got := filer.TotalSize(final.GetChunks()); got != 6 { + t.Fatalf("entry covers %d bytes, want 6", got) + } + for _, chunk := range final.GetChunks() { + if chunk.FileId == "3,02637037d6" && chunk.Offset != 4 { + t.Fatalf("new chunk starts at %d, want 4", chunk.Offset) + } + } + if final.FileSize != 6 { + t.Fatalf("entry size is %d, want 6", final.FileSize) + } + }) + } +} diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index f198ecd7f4..b4d9923cf7 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/operation" + "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/storage/needle" "github.com/seaweedfs/seaweedfs/weed/util" @@ -423,6 +424,7 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa // New request chunks start at offset zero; append them after the // existing chunk-backed file. if isAppend { + entry.FileSize = entry.Size() for _, chunk := range fileChunks { chunk.Offset += int64(entry.FileSize) } @@ -532,12 +534,41 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa defer fs.entryLockTable.ReleaseLock(util.FullPath(path), pathLock) } - dbErr := fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, nil, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength) + var dbErr error + routed := false + if isAppend || isOffsetWrite { + routed, dbErr = fs.forwardToWriteOwner(ctx, entryRouteKey(util.FullPath(path)), func(owner pb.ServerAddress) error { + return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error { + dir, _ := entry.FullPath.DirAndName() + return filer_pb.CreateEntry(context.WithoutCancel(ctx), client, &filer_pb.CreateEntryRequest{ + Directory: dir, + Entry: entry.ToProtoEntry(), + IsMoved: true, + SkipCheckParentDirectory: skipCheckParentDirEntry(r), + Fsync: filer.SyncWrite(ctx), + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{ + Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, + ExpectedEntry: existingSnapshot, + }}}, + }) + }) + }) + } + if !routed { + dbErr = fs.filer.CreateEntry(context.WithoutCancel(ctx), entry, nil, false, false, nil, skipCheckParentDirEntry(r), so.MaxFileNameLength) + } if dbErr != nil { replyerr = dbErr filerResult.Error = dbErr.Error() glog.V(0).InfofCtx(ctx, "failing to write %s to filer server : %v", path, dbErr) - if inlineAppendConverted { + switch { + case routed && errors.Is(dbErr, filer_pb.ErrPreconditionFailed): + replyerr = fmt.Errorf("entry %s changed during append; retry the request", path) + case routed: + // The owner may have committed before the reply was lost, and a + // separate local store may not hold that commit yet. + uncommittedChunks = nil + case inlineAppendConverted: uncommittedChunks = fs.inlineAppendChunksNotReferenced(ctx, util.FullPath(path), mergedChunks) } } else {