Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 f67d95f165 filer: fence lookups from the event stamp sequence
fencedFindEntry, behind LookupDirectoryEntry and LookupDirectoryEntries,
stamped its read fence from the raw wall clock under the shared path lock.
After a backwards clock step the fence fell below events the returned
entry already reflects, so a client versioning the entry by it could take
an older event as newer. Draw it from the event stamp sequence instead.

The fence registers nothing in flight, so it never caps flush or delivery
claims; it costs one short critical section on the stamp registry's mutex
per lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:18:07 -08:00
Chris LuandClaude Opus 5.5 5783cf91a0 filer: fence a remote-object cache commit from the event stamp sequence
CacheRemoteObjectToLocalCluster stamped its commit fence from the raw wall
clock under the path lock. After a backwards clock step that fence fell
below events the cached entry already reflects, the same as the old
CreateEntry and UpdateEntry fences. Take it from the event stamp sequence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:18:04 -08:00
Chris LuandClaude Opus 5.5 b4ea73b231 filer: fence CreateEntry and UpdateEntry from the event stamp sequence
Both stamped their pre-write fence from the raw wall clock, so after a
backwards clock step the fence could sit below events the acknowledged
state already reflects, including the previous write's event on the same
key. A mount that versions a no-op ack by that fence would then accept an
older event over it. Take the fence from the same sequence the events use,
so it lands above every earlier event and below the write's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:18:04 -08:00
Chris LuandClaude Opus 5.5 7a5d9b0ad2 filer: take the log fence without registering an in-flight stamp
LogFenceTsNs stamped and released at once, so each fence briefly sat in
the in-flight registry, where a concurrent claim could be capped below it,
and took the registry mutex twice. Draw the fence from the same sequence
under one lock acquisition without registering it. Lookups are about to
take one per read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:17:30 -08:00
Chris LuandClaude Opus 5.5 b62d6d1d4e filer: stamp ObjectTransaction's log_ts_ns from the meta-log clock
The wall clock can step back between two transactions on one key, or sit
below stamps already bumped past it, giving a later transaction a smaller
stamp than an earlier one or than its own event. Take the response stamp
from the same monotonic allocator the events use, released at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:58:56 -08:00
Chris LuandClaude Opus 5.5 c529121bb8 filer: return the commit's log position from ObjectTransaction
A committed transaction now stamps log_ts_ns under its lock_key lock after
its last mutation, the same wall-clock source CreateEntry and UpdateEntry
use. All mutations of one transaction sit between that stamp and the next
writer's, so one stamp orders the transaction against every other write
of the key. A refused or failed transaction leaves it 0, and a replayed
request returns the stamp recorded with its first outcome. A non-owner
forwards the owner's response unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:49:51 -08:00
Chris LuandClaude Opus 5.5 7b2f04bb3d filer: add log_ts_ns to ObjectTransactionResponse
CreateEntry and UpdateEntry return the filer log position stamped under
the path lock; a conditional write through ObjectTransaction had no such
field. Add it as field 4 so callers can order one key's commits the same
way regardless of which RPC applied them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:43:47 -08:00
9 changed files with 372 additions and 12 deletions

No files matched your search

+24 -4
View File
@@ -114,6 +114,23 @@ type metaLogInflight struct {
func (t *metaLogInflight) stamp() int64 {
t.Lock()
defer t.Unlock()
tsNs := t.nextLocked()
if t.stamped == nil {
t.stamped = make(map[int64]int)
}
t.stamped[tsNs]++
return tsNs
}
// fence draws from the same increasing sequence as stamp without registering
// an event: everything stamped before it is below it, everything after above.
func (t *metaLogInflight) fence() int64 {
t.Lock()
defer t.Unlock()
return t.nextLocked()
}
func (t *metaLogInflight) nextLocked() int64 {
floor := t.lastStampNs
if t.lastClaimNs > floor {
floor = t.lastClaimNs
@@ -123,10 +140,6 @@ func (t *metaLogInflight) stamp() int64 {
tsNs = floor + 1
}
t.lastStampNs = tsNs
if t.stamped == nil {
t.stamped = make(map[int64]int)
}
t.stamped[tsNs]++
return tsNs
}
@@ -256,6 +269,13 @@ func (f *Filer) ReleaseEntryCommitTsNs(tsNs int64) {
f.metaLogInflight.release(tsNs)
}
// LogFenceTsNs returns a stamp above every event stamped so far; every later
// event stamps above it, even after the wall clock steps back. It registers
// nothing in flight, so it never holds back a claim.
func (f *Filer) LogFenceTsNs() int64 {
return f.metaLogInflight.fence()
}
// stampOf returns the event's timestamp: the entry's in-flight stamp, or a
// fresh one for events with no newly stamped entry (deletes).
func (f *Filer) stampOf(newEntry *Entry) int64 {
+26
View File
@@ -135,6 +135,32 @@ func TestMetaLogInflightStampMonotonic(t *testing.T) {
inflight.done(ts2)
}
// A fence sits in the stamp sequence even after a wall-clock step backwards,
// and does not hold back claims since no event adopts it.
func TestMetaLogInflightFenceOrdersWithStamps(t *testing.T) {
var inflight metaLogInflight
ts1 := inflight.stamp()
inflight.Lock()
inflight.lastStampNs = ts1 + int64(time.Hour)
inflight.Unlock()
fence := inflight.fence()
if fence <= ts1+int64(time.Hour) {
t.Fatalf("fence %d not above stamp history %d", fence, ts1+int64(time.Hour))
}
ts2 := inflight.stamp()
if ts2 <= fence {
t.Fatalf("stamp %d not above the earlier fence %d", ts2, fence)
}
if inflight.inFlight(fence) {
t.Fatalf("fence %d registered as in flight", fence)
}
inflight.done(ts1)
inflight.done(ts2)
if got := inflight.minTsNs(); got != 0 {
t.Fatalf("registry not drained: floor=%d", got)
}
}
// TestSuppressedCreateReleasesParentDirectoryStamps pins the stamps of the
// parent directories a rename creates or promotes on the way to its target:
// the rename's covering event names the moved entry only, so a parent stamp
+3
View File
@@ -416,6 +416,9 @@ message ObjectTransactionResponse {
string error = 1;
FilerError error_code = 2;
optional int32 failed_mutation = 3; // index of the mutation that failed (its condition or its apply); unset when the request-level condition failed
// filer log position stamped under the lock after the last mutation
// committed; 0 when the transaction was refused or failed
int64 log_ts_ns = 4;
}
// PosixLockRange is one advisory byte-range lock. Owner identity is (sid, owner):
+15 -4
View File
@@ -1992,8 +1992,11 @@ type ObjectTransactionResponse struct {
Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"`
ErrorCode FilerError `protobuf:"varint,2,opt,name=error_code,json=errorCode,proto3,enum=filer_pb.FilerError" json:"error_code,omitempty"`
FailedMutation *int32 `protobuf:"varint,3,opt,name=failed_mutation,json=failedMutation,proto3,oneof" json:"failed_mutation,omitempty"` // index of the mutation that failed (its condition or its apply); unset when the request-level condition failed
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// filer log position stamped under the lock after the last mutation
// committed; 0 when the transaction was refused or failed
LogTsNs int64 `protobuf:"varint,4,opt,name=log_ts_ns,json=logTsNs,proto3" json:"log_ts_ns,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ObjectTransactionResponse) Reset() {
@@ -2047,6 +2050,13 @@ func (x *ObjectTransactionResponse) GetFailedMutation() int32 {
return 0
}
func (x *ObjectTransactionResponse) GetLogTsNs() int64 {
if x != nil {
return x.LogTsNs
}
return 0
}
// PosixLockRange is one advisory byte-range lock. Owner identity is (sid, owner):
// sid is the mount session, owner the FUSE lock owner within it, so owners from
// different mounts never alias. end is inclusive (max uint64 = to EOF); is_flock
@@ -7691,12 +7701,13 @@ const file_filer_proto_rawDesc = "" +
"request_id\x18\t \x01(\tR\trequestId\x12*\n" +
"\x11condition_alt_key\x18\n" +
" \x01(\tR\x0fconditionAltKey\x120\n" +
"\x14condition_prefer_alt\x18\v \x01(\bR\x12conditionPreferAlt\"\xa8\x01\n" +
"\x14condition_prefer_alt\x18\v \x01(\bR\x12conditionPreferAlt\"\xc4\x01\n" +
"\x19ObjectTransactionResponse\x12\x14\n" +
"\x05error\x18\x01 \x01(\tR\x05error\x123\n" +
"\n" +
"error_code\x18\x02 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\x12,\n" +
"\x0ffailed_mutation\x18\x03 \x01(\x05H\x00R\x0efailedMutation\x88\x01\x01B\x12\n" +
"\x0ffailed_mutation\x18\x03 \x01(\x05H\x00R\x0efailedMutation\x88\x01\x01\x12\x1a\n" +
"\tlog_ts_ns\x18\x04 \x01(\x03R\alogTsNsB\x12\n" +
"\x10_failed_mutation\"\xa1\x01\n" +
"\x0ePosixLockRange\x12\x14\n" +
"\x05start\x18\x01 \x01(\x04R\x05start\x12\x10\n" +
+27
View File
@@ -1768,6 +1768,11 @@ func (m *ObjectTransactionResponse) MarshalToSizedBufferVT(dAtA []byte) (int, er
i -= len(m.unknownFields)
copy(dAtA[i:], m.unknownFields)
}
if m.LogTsNs != 0 {
i = protohelpers.EncodeVarint(dAtA, i, uint64(m.LogTsNs))
i--
dAtA[i] = 0x20
}
if m.FailedMutation != nil {
i = protohelpers.EncodeVarint(dAtA, i, uint64(*m.FailedMutation))
i--
@@ -7481,6 +7486,9 @@ func (m *ObjectTransactionResponse) SizeVT() (n int) {
if m.FailedMutation != nil {
n += 1 + protohelpers.SizeOfVarint(uint64(*m.FailedMutation))
}
if m.LogTsNs != 0 {
n += 1 + protohelpers.SizeOfVarint(uint64(m.LogTsNs))
}
n += len(m.unknownFields)
return n
}
@@ -14654,6 +14662,25 @@ func (m *ObjectTransactionResponse) UnmarshalVT(dAtA []byte) error {
}
}
m.FailedMutation = &v
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field LogTsNs", wireType)
}
m.LogTsNs = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return protohelpers.ErrIntOverflow
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.LogTsNs |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := protohelpers.Skip(dAtA[iNdEx:])
+6 -3
View File
@@ -35,7 +35,7 @@ import (
// Any read whose result a client versions must go through here.
func (fs *FilerServer) fencedFindEntry(ctx context.Context, path util.FullPath) (entry *filer.Entry, logTsNs int64, err error) {
pathLock := fs.entryLockTable.AcquireLock("fencedFindEntry", path, util.SharedLock)
logTsNs = time.Now().UnixNano()
logTsNs = fs.filer.LogFenceTsNs()
entry, err = fs.filer.FindEntry(ctx, path)
fs.entryLockTable.ReleaseLock(path, pathLock)
return
@@ -280,7 +280,7 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
// Fence stamped under the lock: a no-op create returns no event, but the
// acknowledged state still reflects everything at or below this.
resp.LogTsNs = time.Now().UnixNano()
resp.LogTsNs = fs.filer.LogFenceTsNs()
resp.LogSignature = fs.filer.Signature
// Evaluate the optional precondition against the current entry while the
@@ -552,6 +552,9 @@ func (fs *FilerServer) ObjectTransaction(ctx context.Context, req *filer_pb.Obje
}
}
// Still under the lock: after every event this transaction logged, before
// the next writer of lock_key stamps its own.
resp.LogTsNs = fs.filer.LogFenceTsNs()
return resp, nil
}
@@ -1030,7 +1033,7 @@ func (fs *FilerServer) updateEntry(ctx context.Context, req *filer_pb.UpdateEntr
// Fence stamped under the lock: the no-change path below returns no event,
// but the acknowledged state still reflects everything at or below this.
logTsNs := time.Now().UnixNano()
logTsNs := fs.filer.LogFenceTsNs()
transactional := fs.filer.RefusesConflictingCommits(lockPath)
var entry *filer.Entry
@@ -927,6 +927,9 @@ func TestObjectTransactionForwardsToOwner(t *testing.T) {
if err != nil || resp.Error != "" {
t.Fatalf("forwarded txn failed: err=%v resp=%q", err, resp.Error)
}
if resp.LogTsNs == 0 {
t.Errorf("forwarded txn should carry the owner's log_ts_ns")
}
if string(ownerStore.entries["/buckets/b/obj"].Extended["X-Amz-Meta-k"]) != "v" {
t.Errorf("owner should have applied the forwarded mutation: %v", ownerStore.entries["/buckets/b/obj"].Extended)
}
@@ -1213,3 +1216,185 @@ func TestObjectTransactionConditionPreferAltHonorsNullIsLatest(t *testing.T) {
t.Fatal("mutation did not apply over a null-is-latest .versions")
}
}
// A committed transaction returns the log position stamped under its lock,
// ordered after an earlier write to the same path; a refused one returns 0.
func TestObjectTransactionLogTsNs(t *testing.T) {
now := time.Unix(1700000000, 0)
fs, _ := newTxnTestServer(t, map[string]*filer.Entry{
"/buckets/b/obj": {
Attr: filer.Attr{Inode: 1, Mtime: now, Crtime: now, Mode: 0644},
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("abc")},
},
})
ctx := context.Background()
upd, err := fs.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
Directory: "/buckets/b",
Entry: &filer_pb.Entry{
Name: "obj",
Attributes: &filer_pb.FuseAttributes{Mtime: now.Unix() + 5, FileMode: 0644, Inode: 1},
Extended: map[string][]byte{s3_constants.ExtETagKey: []byte("abc")},
},
})
if err != nil {
t.Fatalf("UpdateEntry: %v", err)
}
if upd.LogTsNs == 0 {
t.Fatal("UpdateEntry returned no log_ts_ns")
}
txn := func(etag, mutationEtag string) *filer_pb.ObjectTransactionRequest {
m := &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_PATCH_EXTENDED, Directory: "/buckets/b", Name: "obj",
SetExtended: map[string][]byte{"X-Amz-Meta-k": []byte("v")},
}
if mutationEtag != "" {
m.Condition = one(&filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{mutationEtag}})
}
return &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/b/obj",
Condition: one(&filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{etag}}),
Mutations: []*filer_pb.ObjectMutation{m},
}
}
resp, err := fs.ObjectTransaction(ctx, txn(`"abc"`, ""))
if err != nil || resp.Error != "" {
t.Fatalf("conditional txn: err=%v resp=%q", err, resp.GetError())
}
if resp.LogTsNs <= upd.LogTsNs {
t.Fatalf("txn log_ts_ns %d not after the preceding update's %d", resp.LogTsNs, upd.LogTsNs)
}
refused, err := fs.ObjectTransaction(ctx, txn(`"zzz"`, ""))
if err != nil {
t.Fatalf("refused txn: %v", err)
}
if refused.ErrorCode != filer_pb.FilerError_PRECONDITION_FAILED || refused.LogTsNs != 0 {
t.Fatalf("refused txn: code %v log_ts_ns %d, want PRECONDITION_FAILED and 0", refused.ErrorCode, refused.LogTsNs)
}
refused, err = fs.ObjectTransaction(ctx, txn(`"abc"`, `"zzz"`))
if err != nil {
t.Fatalf("refused mutation: %v", err)
}
if refused.FailedMutation == nil || refused.LogTsNs != 0 {
t.Fatalf("refused mutation: failed_mutation %v log_ts_ns %d, want set and 0", refused.FailedMutation, refused.LogTsNs)
}
}
// With the wall clock behind stamps already issued, each transaction's stamp
// still follows its own event and the previous transaction's stamp.
func TestObjectTransactionLogTsNsClockBehind(t *testing.T) {
now := time.Unix(1700000000, 0)
fs, store := newTxnTestServer(t, map[string]*filer.Entry{
"/buckets/b/obj": {Attr: filer.Attr{Inode: 1, Mtime: now, Crtime: now, Mode: 0644}},
})
prev := time.Now().Add(time.Hour).UnixNano()
fs.filer.LocalDeliveredThroughTsNs(prev)
for i := 0; i < 2; i++ {
resp, err := fs.ObjectTransaction(context.Background(), &filer_pb.ObjectTransactionRequest{
LockKey: "/buckets/b/obj",
Mutations: []*filer_pb.ObjectMutation{{
Type: filer_pb.ObjectMutation_PATCH_EXTENDED, Directory: "/buckets/b", Name: "obj",
SetExtended: map[string][]byte{"X-Amz-Meta-k": []byte(strconv.Itoa(i))},
}},
})
if err != nil || resp.Error != "" {
t.Fatalf("txn %d: err=%v resp=%q", i, err, resp.GetError())
}
event := store.entries["/buckets/b/obj"].CommitTsNs
if event <= prev || resp.LogTsNs <= event {
t.Fatalf("txn %d: previous %d, event %d, log_ts_ns %d; want increasing", i, prev, event, resp.LogTsNs)
}
prev = resp.LogTsNs
}
}
// stepMetaLogClockBack leaves the wall clock d behind the filer's log history,
// as after a backwards clock step: an issued claim ahead of now is a floor the
// log's stamps must stay above.
func stepMetaLogClockBack(f *filer.Filer, d time.Duration) int64 {
ahead := time.Now().Add(d).UnixNano()
f.LocalDeliveredThroughTsNs(ahead)
return ahead
}
// CreateEntry and UpdateEntry fence before their write: with the wall clock
// behind the log, each fence is above the previous write's event on the key
// and below its own.
func TestCreateUpdateEntryLogTsNsAcrossClockStep(t *testing.T) {
fs, _ := newTxnTestServer(t, nil)
entry := func(mtime int64) *filer_pb.Entry {
return &filer_pb.Entry{Name: "obj", Attributes: &filer_pb.FuseAttributes{Mtime: mtime, FileMode: 0644, Inode: 1}}
}
floor := stepMetaLogClockBack(fs.filer, time.Hour)
created, err := fs.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{Directory: "/buckets/bkt", Entry: entry(1700000000)})
if err != nil || created.Error != "" {
t.Fatalf("CreateEntry: err=%v resp=%q", err, created.GetError())
}
createEv := created.MetadataEvent
if createEv == nil {
t.Fatal("CreateEntry logged no event")
}
if created.LogTsNs <= floor || created.LogTsNs >= createEv.TsNs {
t.Fatalf("CreateEntry log_ts_ns %d not between the log floor %d and its event %d", created.LogTsNs, floor, createEv.TsNs)
}
stepMetaLogClockBack(fs.filer, 2*time.Hour)
updated, err := fs.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{Directory: "/buckets/bkt", Entry: entry(1700000005)})
if err != nil {
t.Fatalf("UpdateEntry: %v", err)
}
updateEv := updated.MetadataEvent
if updateEv == nil {
t.Fatal("UpdateEntry logged no event")
}
if updated.LogTsNs <= createEv.TsNs || updated.LogTsNs >= updateEv.TsNs {
t.Fatalf("UpdateEntry log_ts_ns %d not between the create's event %d and its own %d", updated.LogTsNs, createEv.TsNs, updateEv.TsNs)
}
}
// A lookup's fence covers every event the returned entry reflects, also with
// the wall clock behind the log, for found and missing entries alike.
func TestLookupFenceAcrossClockStep(t *testing.T) {
fs, _ := newTxnTestServer(t, nil)
stepMetaLogClockBack(fs.filer, time.Hour)
created, err := fs.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
Directory: "/buckets/bkt",
Entry: &filer_pb.Entry{Name: "obj", Attributes: &filer_pb.FuseAttributes{Mtime: 1700000000, FileMode: 0644, Inode: 1}},
})
if err != nil || created.Error != "" || created.MetadataEvent == nil {
t.Fatalf("CreateEntry: err=%v resp=%q event=%v", err, created.GetError(), created.GetMetadataEvent())
}
createTsNs := created.MetadataEvent.TsNs
found, err := fs.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/buckets/bkt", Name: "obj"})
if err != nil {
t.Fatalf("LookupDirectoryEntry: %v", err)
}
if found.LogTsNs < createTsNs {
t.Fatalf("lookup fence %d below the create event %d its entry reflects", found.LogTsNs, createTsNs)
}
missing, err := fs.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/buckets/bkt", Name: "gone"})
if err != filer_pb.ErrNotFound {
t.Fatalf("missing lookup: %v", err)
}
if missing.LogTsNs < createTsNs {
t.Fatalf("missing lookup fence %d below the latest event %d", missing.LogTsNs, createTsNs)
}
batch, err := fs.LookupDirectoryEntries(context.Background(), &filer_pb.LookupDirectoryEntriesRequest{
Requests: []*filer_pb.LookupDirectoryEntryRequest{{Directory: "/buckets/bkt", Name: "obj"}},
})
if err != nil || len(batch.Results) != 1 || !batch.Results[0].Found {
t.Fatalf("LookupDirectoryEntries: err=%v resp=%v", err, batch)
}
if batch.Results[0].LogTsNs < createTsNs {
t.Fatalf("batch lookup fence %d below the create event %d its entry reflects", batch.Results[0].LogTsNs, createTsNs)
}
}
+1 -1
View File
@@ -326,7 +326,7 @@ func (fs *FilerServer) doCacheRemoteObjectToLocalCluster(ctx context.Context, re
commitLock := fs.entryLockTable.AcquireLock("CacheRemoteObjectToLocalCluster", lockPath, util.ExclusiveLock)
defer fs.entryLockTable.ReleaseLock(lockPath, commitLock)
commitLogTsNs := time.Now().UnixNano()
commitLogTsNs := fs.filer.LogFenceTsNs()
current, err := fs.filer.FindEntry(ctx, lockPath)
if err != nil {
fs.filer.DeleteUncommittedChunks(ctx, chunks)
@@ -0,0 +1,85 @@
package weed_server
import (
"context"
"fmt"
"net"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// remoteCacheMaster assigns every chunk to one fake volume server.
type remoteCacheMaster struct {
reuseManifestMaster
volume pb.ServerAddress
grpcPort int
}
func (m *remoteCacheMaster) Assign(context.Context, *master_pb.AssignRequest) (*master_pb.AssignResponse, error) {
return &master_pb.AssignResponse{
Fid: fmt.Sprintf("1,%x%08x", m.next.Add(1), 0xc0de),
Count: 1,
Location: &master_pb.Location{Url: m.volume.ToHttpAddress(), PublicUrl: m.volume.ToHttpAddress(), GrpcPort: uint32(m.grpcPort)},
}, nil
}
// remoteCacheVolume accepts every remote fetch without storing anything.
type remoteCacheVolume struct {
volume_server_pb.UnimplementedVolumeServerServer
}
func (remoteCacheVolume) FetchAndWriteNeedle(context.Context, *volume_server_pb.FetchAndWriteNeedleRequest) (*volume_server_pb.FetchAndWriteNeedleResponse, error) {
return &volume_server_pb.FetchAndWriteNeedleResponse{ETag: "etag"}, nil
}
// With the wall clock behind the log, caching a remote object fences its
// commit above the log floor and below the commit's own event.
func TestCacheRemoteObjectLogTsNsAcrossClockStep(t *testing.T) {
fs, store, _ := newRemoteMountTestServer(t)
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
fs.grpcDialOption = dialOption
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
port := lis.Addr().(*net.TCPAddr).Port
volumeAddr := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), port)
volumeServer := grpc.NewServer()
volume_server_pb.RegisterVolumeServerServer(volumeServer, remoteCacheVolume{})
go volumeServer.Serve(lis)
t.Cleanup(volumeServer.Stop)
master := &remoteCacheMaster{volume: volumeAddr, grpcPort: port}
master.volumeHost = volumeAddr.ToHttpAddress()
masterAddr := startFakeMasterServerForLeaderLookup(t, master)
fs.filer.MasterClient = wdclient.NewMasterClient(dialOption, "test", cluster.FilerType, pb.ServerAddress("localhost:0"), "", "",
*pb.NewServiceDiscoveryFromMap(map[string]pb.ServerAddress{"master": masterAddr}))
masterCtx, cancelMaster := context.WithCancel(context.Background())
t.Cleanup(cancelMaster)
go fs.filer.MasterClient.KeepConnectedToMaster(masterCtx)
waitCtx, cancelWait := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelWait()
require.NotEmpty(t, fs.filer.MasterClient.GetMaster(waitCtx), "fake master did not become available")
obj := remoteOnlyFileEntry("/buckets/b/obj.bin")
store.entries[string(obj.FullPath)] = obj
floor := stepMetaLogClockBack(fs.filer, time.Hour)
resp, err := fs.CacheRemoteObjectToLocalCluster(context.Background(), &filer_pb.CacheRemoteObjectToLocalClusterRequest{
Directory: "/buckets/b", Name: "obj.bin",
})
require.NoError(t, err)
require.NotEmpty(t, resp.GetEntry().GetChunks(), "object was not cached")
require.NotNil(t, resp.MetadataEvent, "cache commit logged no event")
require.Greater(t, resp.LogTsNs, floor, "fence below the log floor")
require.Less(t, resp.LogTsNs, resp.MetadataEvent.TsNs, "fence not below the commit's event")
}