diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim.go b/seaweed-block/core/frontend/chunkstore/layout/claim.go index 2275e6e6a9..5b82a88de8 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/claim.go +++ b/seaweed-block/core/frontend/chunkstore/layout/claim.go @@ -18,24 +18,26 @@ type LeaseWait interface { } // Claim is transition 1 as a pure step on HEAD: a holder granted epoch e > -// HEAD's epoch takes HEAD (epoch = e, holder = me) and voids any open -// session or cleaning (activity idle); the image and the snapshots are -// unchanged. A HEAD already claimed by me at e is a replay. A HEAD at e -// held by another server is ErrNotHolder; one above e is ErrStaleEpoch. +// HEAD's epoch takes HEAD (epoch = e, holder = me, and the claim id that +// identifies its local data) and voids any open session or cleaning +// (activity idle); the image and the snapshots are unchanged. A HEAD +// already claimed at e by this server with this claim id is a replay (a +// lost reply). A HEAD at e held by another server, or by this server with +// another claim id, is ErrNotHolder; one above e is ErrStaleEpoch. func (h Head) Claim(me HolderID) (next Head, changed bool, err error) { - if me.Epoch == 0 || me.Holder == "" { - return Head{}, false, errors.New("layout: Claim needs an epoch and a holder") + if me.Epoch == 0 || me.Holder == "" || me.ClaimID == "" { + return Head{}, false, errors.New("layout: Claim needs an epoch, a holder and a claim id") } switch { case me.Epoch < h.Epoch: return Head{}, false, fmt.Errorf("%w: HEAD epoch %d, caller %d", ErrStaleEpoch, h.Epoch, me.Epoch) - case me.Epoch == h.Epoch && h.Holder == me.Holder: + case h.heldBy(me): return h, false, nil case me.Epoch == h.Epoch: - return Head{}, false, fmt.Errorf("%w: epoch %d is held by %q", ErrNotHolder, h.Epoch, h.Holder) + return Head{}, false, fmt.Errorf("%w: epoch %d is held by %q with claim %q", ErrNotHolder, h.Epoch, h.Holder, h.ClaimID) } next = h.clone() - next.Epoch, next.Holder = me.Epoch, me.Holder + next.Epoch, next.Holder, next.ClaimID = me.Epoch, me.Holder, me.ClaimID next.Activity = Activity{Kind: ActIdle} return next, true, nil } diff --git a/seaweed-block/core/frontend/chunkstore/layout/claim_test.go b/seaweed-block/core/frontend/chunkstore/layout/claim_test.go index d3a6852710..791a38251b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/claim_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/claim_test.go @@ -6,7 +6,7 @@ import ( "testing" ) -var newer = HolderID{Epoch: 4, Holder: "srv-b"} +var newer = HolderID{Epoch: 4, Holder: "srv-b", ClaimID: "k-b"} // fakeLease records its calls; ended says whether old leases are over. type fakeLease struct { @@ -30,7 +30,7 @@ func TestClaim_Closure(t *testing.T) { for name, h := range map[string]Head{ "idle": idleHead(), "snap(s)": snapHead("s1"), - "clean(c)": {Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}}, + "clean(c)": {Gen: 7, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActClean, Session: "c1"}}, } { next, changed, err := h.Claim(newer) if err != nil || !changed || next.Epoch != 4 || next.Holder != "srv-b" || next.Activity != (Activity{Kind: ActIdle}) { @@ -51,8 +51,9 @@ func TestClaim_Closure(t *testing.T) { me HolderID want error }{ - "older epoch": {HolderID{Epoch: 2, Holder: "srv-b"}, ErrStaleEpoch}, - "same epoch, another server": {HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, + "older epoch": {HolderID{Epoch: 2, Holder: "srv-b", ClaimID: "k-b"}, ErrStaleEpoch}, + "same epoch, another server": {HolderID{Epoch: 3, Holder: "srv-b", ClaimID: "k-b"}, ErrNotHolder}, + "same epoch and server, another claim id": {HolderID{Epoch: 3, Holder: "srv-a", ClaimID: "k-other"}, ErrNotHolder}, } { if _, _, err := h.Claim(tc.me); !errors.Is(err, tc.want) { t.Errorf("%s: %v; want %v", name, err, tc.want) @@ -128,3 +129,23 @@ func TestRunClaim_InterruptAtEveryStep(t *testing.T) { } }) } + +// A claim writes its claim id into HEAD; a later claim at that epoch by +// the same server with another claim id (another process, fresh local +// data) is refused, and the same claim id again is a replay. +func TestClaim_WritesItsClaimID(t *testing.T) { + next, changed, err := idleHead().Claim(newer) + if err != nil || !changed || next.ClaimID != "k-b" { + t.Fatalf("Claim: %+v %t %v; want claim id k-b written", next, changed, err) + } + if _, changed, err := next.Claim(newer); err != nil || changed { + t.Fatalf("Claim again with the same claim id: %t %v; want a replay", changed, err) + } + other := HolderID{Epoch: newer.Epoch, Holder: newer.Holder, ClaimID: "k-b2"} + if _, _, err := next.Claim(other); !errors.Is(err, ErrNotHolder) { + t.Fatalf("Claim at the same epoch by the same server with another claim id: %v; want ErrNotHolder", err) + } + if _, _, err := next.Begin(other, "s"); !errors.Is(err, ErrNotHolder) { + t.Fatalf("Begin by the same server with another claim id: %v; want ErrNotHolder", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go index 79044c537a..8ca766435b 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit_test.go @@ -50,7 +50,7 @@ func TestCommit_Closure(t *testing.T) { if err != nil || !changed || next.Activity.Kind != ActIdle || *next.Current != rn || next.Position != 50 || next.Snapshots["hourly"].Root != rn { t.Fatalf("Commit: %+v %t %v", next, changed, err) } - if next.Snapshots["daily"].Dependents[0] != "t1" || len(next.Snapshots) != 2 { + if next.Snapshots["daily"].Dependents[0].Target != "t1" || len(next.Snapshots) != 2 { t.Fatalf("Commit changed other snapshots: %+v", next.Snapshots) } if h.Activity.Kind != ActSnap || h.Snapshots["hourly"].Root == rn { @@ -74,7 +74,7 @@ func TestCommit_Closure(t *testing.T) { }{ "idle": {idleHead(), me, "", ErrNoSession}, "other session": {snapHead("s2"), me, "", ErrNoSession}, - "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "s1"}}, me, "", ErrNoSession}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActClean, Session: "s1"}}, me, "", ErrNoSession}, "other epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, "", ErrNotHolder}, "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, "", ErrNotHolder}, "name taken": {h, me, "daily", ErrSnapshotExists}, @@ -96,7 +96,7 @@ func commitFixture(t *testing.T) (*memObjects, Head, CommitRequest) { prevRoot := prepared(t, f, prev, "s0") next := manifest(ref("v1", 0, "a"), ref("v1", 3, "b2"), ref("v1", 10004, "c"), ref("src", 7, "d")) prepared(t, f, next, "s1") - h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &prevRoot, Position: 40} return f, h, CommitRequest{Session: "s1", Prev: prev, Next: next, Position: 50, Snapshot: "hourly"} } @@ -182,7 +182,7 @@ func TestRunCommit_StaleBaseAndLookupFailure(t *testing.T) { f2 := newMemObjects(volRoot) next := manifest(ref("v1", 1, "x")) prepared(t, f2, next, "s1") - h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}} + h2 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: "s1"}} if got, err := runCommit(&memHead{h: &h2}, f2, CommitRequest{Session: "s1", Next: next, Position: 5}); err != nil || got.Current == nil { t.Fatalf("first commit: %+v %v", got, err) } @@ -244,7 +244,7 @@ func TestRunCommit_AfterAnEmptyPublishedRoot(t *testing.T) { } // Before any commit there is no current root: a non-empty previous // manifest is stale there too. - h0 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s9"}} + h0 := Head{Gen: 1, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: "s9"}} if _, err := runCommit(&memHead{h: &h0}, f, CommitRequest{Session: "s9", Prev: next, Next: next, Position: 3}); !errors.Is(err, ErrStaleBase) { t.Fatalf("a previous manifest before any commit: %v; want ErrStaleBase", err) } diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index fbf9a1b686..ffa9035721 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -31,19 +31,34 @@ type Activity struct { Session string `json:"session,omitempty"` } +// Dependent is a restore target that still names a snapshot's chunks: the +// target volume's name and id, and the root it was made from. A volume +// created again under the target's name, or a snapshot name reused for +// another root, matches no dependent. +type Dependent struct { + Target string + TargetID VolumeID + Root RootName +} + // Snapshot is one named snapshot: its root and the restore targets that -// still name its chunks. +// still name its chunks, ordered by target id. type Snapshot struct { Root RootName - Dependents []string + Dependents []Dependent } // Head is the decoded HEAD. Gen is the generation the store holds it at; -// it is not part of the encoding. +// it is not part of the encoding. VolumeID is the volume's id (its VOLUME +// record's); ClaimID is the id the current holder's claim wrote, which +// with the epoch identifies the holder's local data (the holder's name +// repeats across restarts and same-host moves). type Head struct { Gen uint64 + VolumeID VolumeID Epoch uint64 Holder string + ClaimID string Activity Activity Current *RootName // nil: no image committed yet Position uint64 @@ -51,8 +66,10 @@ type Head struct { } type headDoc struct { + VolumeID string `json:"volume_id"` Epoch uint64 `json:"epoch"` Holder string `json:"holder"` + ClaimID string `json:"claim_id,omitempty"` Activity Activity `json:"activity"` Current string `json:"current,omitempty"` Position uint64 `json:"position"` @@ -61,7 +78,13 @@ type headDoc struct { type snapDoc struct { Root string `json:"root"` - Dependents []string `json:"dependents,omitempty"` + Dependents []depDoc `json:"dependents,omitempty"` +} + +type depDoc struct { + Target string `json:"target"` + TargetID string `json:"target_id"` + Root string `json:"root"` } // validName refuses a string the JSON encoding would not keep byte for @@ -75,7 +98,10 @@ func validName(field, v string) error { } func (h Head) check() error { - for field, v := range map[string]string{"holder": h.Holder, "session": h.Activity.Session} { + if h.VolumeID.IsZero() { + return fmt.Errorf("%w: HEAD without a volume id", ErrMalformed) + } + for field, v := range map[string]string{"holder": h.Holder, "session": h.Activity.Session, "claim id": h.ClaimID} { if err := validName(field, v); err != nil { return err } @@ -95,6 +121,9 @@ func (h Head) check() error { if h.Epoch == 0 || h.Holder == "" { return fmt.Errorf("%w: HEAD without epoch or holder", ErrMalformed) } + if h.ClaimID == "" { + return fmt.Errorf("%w: HEAD holder %q without a claim id", ErrMalformed, h.Holder) + } if len(h.Snapshots) > MaxSnapshots { return fmt.Errorf("%w: %d snapshots, at most %d", ErrMalformed, len(h.Snapshots), MaxSnapshots) } @@ -106,14 +135,20 @@ func (h Head) check() error { return err } for i, d := range s.Dependents { - if err := validName("dependent", d); err != nil { + if err := validName("dependent", d.Target); err != nil { return err } - if err := checkOwner(d); err != nil { + if err := checkOwner(d.Target); err != nil { return err } - if i > 0 && s.Dependents[i-1] >= d { - return fmt.Errorf("%w: snapshot %q dependents not sorted and unique", ErrMalformed, n) + if d.TargetID.IsZero() { + return fmt.Errorf("%w: snapshot %q dependent %q without its volume id", ErrMalformed, n, d.Target) + } + if d.Root != s.Root { + return fmt.Errorf("%w: snapshot %q dependent %q records root %s, not the snapshot's %s", ErrMalformed, n, d.Target, d.Root, s.Root) + } + if i > 0 && bytes.Compare(s.Dependents[i-1].TargetID[:], d.TargetID[:]) >= 0 { + return fmt.Errorf("%w: snapshot %q dependents not ordered and unique by target id", ErrMalformed, n) } } } @@ -125,29 +160,43 @@ func (h Head) Encode() ([]byte, error) { if err := h.check(); err != nil { return nil, err } - d := headDoc{Epoch: h.Epoch, Holder: h.Holder, Activity: h.Activity, Position: h.Position} + d := headDoc{VolumeID: h.VolumeID.String(), Epoch: h.Epoch, Holder: h.Holder, ClaimID: h.ClaimID, Activity: h.Activity, Position: h.Position} if h.Current != nil { d.Current = h.Current.String() } if len(h.Snapshots) > 0 { d.Snapshots = map[string]snapDoc{} for n, s := range h.Snapshots { - d.Snapshots[n] = snapDoc{Root: s.Root.String(), Dependents: s.Dependents} + sd := snapDoc{Root: s.Root.String()} + for _, dep := range s.Dependents { + sd.Dependents = append(sd.Dependents, depDoc{Target: dep.Target, TargetID: dep.TargetID.String(), Root: dep.Root.String()}) + } + d.Snapshots[n] = sd } } return json.Marshal(d) } -// DecodeHead parses canonical HEAD bytes; unknown fields and non-canonical -// bytes are refused. -func DecodeHead(b []byte, gen uint64) (Head, error) { +// DecodeHead parses canonical HEAD bytes for the volume whose VOLUME +// record carries volume; unknown fields and non-canonical bytes are +// refused, and so is a HEAD of another volume id (ErrIdentity): one left +// by an interrupted delete, or created late by an old restore, under a +// name since given to another volume. Every reader of HEAD decodes here. +func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) { + if volume.IsZero() { + return Head{}, errors.New("layout: DecodeHead needs the volume's id from its VOLUME") + } var d headDoc dec := json.NewDecoder(bytes.NewReader(b)) dec.DisallowUnknownFields() if err := dec.Decode(&d); err != nil { return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err) } - h := Head{Gen: gen, Epoch: d.Epoch, Holder: d.Holder, Activity: d.Activity, Position: d.Position} + vid, err := ParseVolumeID(d.VolumeID) + if err != nil { + return Head{}, err + } + h := Head{Gen: gen, VolumeID: vid, Epoch: d.Epoch, Holder: d.Holder, ClaimID: d.ClaimID, Activity: d.Activity, Position: d.Position} if d.Current != "" { rn, err := ParseRootName(d.Current) if err != nil { @@ -162,7 +211,19 @@ func DecodeHead(b []byte, gen uint64) (Head, error) { if err != nil { return Head{}, err } - h.Snapshots[n] = Snapshot{Root: rn, Dependents: s.Dependents} + snap := Snapshot{Root: rn} + for _, dep := range s.Dependents { + tid, err := ParseVolumeID(dep.TargetID) + if err != nil { + return Head{}, err + } + drn, err := ParseRootName(dep.Root) + if err != nil { + return Head{}, err + } + snap.Dependents = append(snap.Dependents, Dependent{Target: dep.Target, TargetID: tid, Root: drn}) + } + h.Snapshots[n] = snap } } again, err := h.Encode() @@ -172,6 +233,9 @@ func DecodeHead(b []byte, gen uint64) (Head, error) { if !bytes.Equal(again, b) { return Head{}, fmt.Errorf("%w: HEAD bytes are not canonical", ErrMalformed) } + if h.VolumeID != volume { + return Head{}, fmt.Errorf("%w: HEAD carries volume id %s, VOLUME has %s", ErrIdentity, h.VolumeID, volume) + } return h, nil } @@ -183,14 +247,19 @@ var ( ErrNoSession = errors.New("layout: the session is not open") ) -// HolderID is the identity a transition acts as: the epoch of the line it was -// granted and its server. +// HolderID is the identity a transition acts as: the epoch of the line it +// was granted, its server, and the claim id its claim wrote into HEAD. The +// server's name repeats (a restart, a same-host move); a decision never +// rests on it alone. type HolderID struct { - Epoch uint64 - Holder string + Epoch uint64 + Holder string + ClaimID string } -func (h Head) heldBy(me HolderID) bool { return h.Epoch == me.Epoch && h.Holder == me.Holder } +func (h Head) heldBy(me HolderID) bool { + return h.Epoch == me.Epoch && h.Holder == me.Holder && h.ClaimID == me.ClaimID +} // Begin is transition 2: activity idle -> snap(session), by the holder at // HEAD's epoch. Begin of the session already open is a replay: it returns @@ -222,7 +291,7 @@ func (h Head) clone() Head { if h.Snapshots != nil { c.Snapshots = make(map[string]Snapshot, len(h.Snapshots)) for n, s := range h.Snapshots { - c.Snapshots[n] = Snapshot{Root: s.Root, Dependents: append([]string(nil), s.Dependents...)} + c.Snapshots[n] = Snapshot{Root: s.Root, Dependents: append([]Dependent(nil), s.Dependents...)} } } return c diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_test.go index 8f9653ca0d..b30da8d8f8 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_test.go @@ -1,38 +1,57 @@ package layout import ( + "bytes" "context" "errors" "fmt" + "reflect" + "sort" "strings" "sync" "testing" ) -var me = HolderID{Epoch: 3, Holder: "srv-a"} +var me = HolderID{Epoch: 3, Holder: "srv-a", ClaimID: "k-a"} func idleHead() Head { - return Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}} + return Head{Gen: 7, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}} +} + +// deps returns dependents of root for the named targets, in the order HEAD +// stores them (by target id). +func deps(root RootName, targets ...string) []Dependent { + var out []Dependent + for _, t := range targets { + out = append(out, Dependent{Target: t, TargetID: idFor(t), Root: root}) + } + sort.Slice(out, func(a, b int) bool { return bytes.Compare(out[a].TargetID[:], out[b].TargetID[:]) < 0 }) + return out } func TestHead_GoldenEncodingRoundTrip(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} - h := Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &rn, Position: 42, - Snapshots: map[string]Snapshot{"daily": {Root: rn, Dependents: []string{"t1", "t2"}}}} + ds := deps(rn, "t1", "t2") + h := Head{VolumeID: idFor("v1"), Epoch: 3, Holder: "srv-a", ClaimID: "k-a", Activity: Activity{Kind: ActSnap, Session: "s1"}, Current: &rn, Position: 42, + Snapshots: map[string]Snapshot{"daily": {Root: rn, Dependents: ds}}} b, err := h.Encode() if err != nil { t.Fatal(err) } - want := `{"epoch":3,"holder":"srv-a","activity":{"kind":"snap","session":"s1"},"current":"` + rn.String() + - `","position":42,"snapshots":{"daily":{"root":"` + rn.String() + `","dependents":["t1","t2"]}}}` + dep := func(d Dependent) string { + return `{"target":"` + d.Target + `","target_id":"` + d.TargetID.String() + `","root":"` + rn.String() + `"}` + } + want := `{"volume_id":"` + idFor("v1").String() + `","epoch":3,"holder":"srv-a","claim_id":"k-a","activity":{"kind":"snap","session":"s1"},"current":"` + rn.String() + + `","position":42,"snapshots":{"daily":{"root":"` + rn.String() + `","dependents":[` + dep(ds[0]) + `,` + dep(ds[1]) + `]}}}` if string(b) != want { t.Fatalf("encoding\n got %s\nwant %s", b, want) } - back, err := DecodeHead(b, 9) + back, err := DecodeHead(b, 9, idFor("v1")) if err != nil { t.Fatal(err) } - if back.Gen != 9 || back.Current == nil || *back.Current != rn || back.Snapshots["daily"].Root != rn { + if back.Gen != 9 || back.VolumeID != idFor("v1") || back.ClaimID != "k-a" || back.Current == nil || *back.Current != rn || + !reflect.DeepEqual(back.Snapshots["daily"].Dependents, ds) { t.Fatalf("decoded %+v", back) } if b2, _ := back.Encode(); string(b2) != want { @@ -42,20 +61,27 @@ func TestHead_GoldenEncodingRoundTrip(t *testing.T) { func TestHead_Refusals(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} + other := RootName{Hash: Sum([]byte("other"))} many := map[string]Snapshot{} for i := 0; i <= MaxSnapshots; i++ { many[fmt.Sprintf("s%03d", i)] = Snapshot{Root: rn} } + v := idFor("v1") + snap := func(ds []Dependent) map[string]Snapshot { return map[string]Snapshot{"n": {Root: rn, Dependents: ds}} } + ab := deps(rn, "a", "b") for name, h := range map[string]Head{ - "idle with a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle, Session: "s"}}, - "snap without a session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap}}, - "unknown activity": {Epoch: 1, Holder: "a", Activity: Activity{Kind: "open"}}, - "epoch zero": {Holder: "a", Activity: Activity{Kind: ActIdle}}, - "no holder": {Epoch: 1, Activity: Activity{Kind: ActIdle}}, - "dependents unsorted": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"b", "a"}}}}, - "dependent twice": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a", "a"}}}}, - "bad dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{"a/b"}}}}, - "too many snapshots": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: many}, + "no volume id": {Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}}, + "idle with a session": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle, Session: "s"}}, + "snap without a session": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActSnap}}, + "unknown activity": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: "open"}}, + "epoch zero": {VolumeID: v, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}}, + "no holder": {VolumeID: v, Epoch: 1, Activity: Activity{Kind: ActIdle}}, + "dependents unordered": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[1], ab[0]})}, + "dependent twice": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{ab[0], ab[0]})}, + "bad dependent name": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a/b", TargetID: idFor("x"), Root: rn}})}, + "dependent without id": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", Root: rn}})}, + "dependent of another root": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: snap([]Dependent{{Target: "a", TargetID: idFor("a"), Root: other}})}, + "too many snapshots": {VolumeID: v, Epoch: 1, Holder: "a", ClaimID: "k", Activity: Activity{Kind: ActIdle}, Snapshots: many}, } { if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { t.Errorf("%s: %v; want ErrMalformed", name, err) @@ -63,12 +89,14 @@ func TestHead_Refusals(t *testing.T) { } good, _ := idleHead().Encode() for name, b := range map[string]string{ - "unknown field": strings.Replace(string(good), `"position"`, `"extra":1,"position"`, 1), - "whitespace": strings.Replace(string(good), `,`, `, `, 1), - "bad root": strings.Replace(string(good), `"position"`, `"current":"xyz","position"`, 1), - "not json": "HEAD", + "unknown field": strings.Replace(string(good), `"position"`, `"extra":1,"position"`, 1), + "whitespace": strings.Replace(string(good), `,`, `, `, 1), + "bad root": strings.Replace(string(good), `"position"`, `"current":"xyz","position"`, 1), + "zero volume id": strings.Replace(string(good), idFor("v1").String(), strings.Repeat("0", 32), 1), + "short volume id": strings.Replace(string(good), idFor("v1").String(), "abc", 1), + "not json": "HEAD", } { - if _, err := DecodeHead([]byte(b), 1); !errors.Is(err, ErrMalformed) { + if _, err := DecodeHead([]byte(b), 1, idFor("v1")); !errors.Is(err, ErrMalformed) { t.Errorf("decode %s: %v; want ErrMalformed", name, err) } } @@ -95,7 +123,7 @@ func TestBegin_Closure(t *testing.T) { want error }{ "other session open": {next, me, ErrBusy}, - "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}}, me, ErrBusy}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActClean, Session: "c1"}}, me, ErrBusy}, "older caller epoch": {h, HolderID{Epoch: 2, Holder: "srv-a"}, ErrNotHolder}, "newer caller epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, @@ -137,7 +165,7 @@ func (m *memHead) ReadHead(context.Context) (Head, bool, error) { return Head{}, false, nil } b, _ := m.h.Encode() - h, err := DecodeHead(b, m.h.Gen) + h, err := DecodeHead(b, m.h.Gen, m.h.VolumeID) if m.afterRead != nil { f := m.afterRead m.afterRead = nil @@ -265,7 +293,7 @@ func snapHead(session string) Head { h.Activity = Activity{Kind: ActSnap, Session: session} h.Current = &rn h.Position = 40 - h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: []string{"t1"}}} + h.Snapshots = map[string]Snapshot{"daily": {Root: rn, Dependents: []Dependent{{Target: "t1", TargetID: idFor("t1"), Root: rn}}}} return h } @@ -275,7 +303,7 @@ func TestAbort_Closure(t *testing.T) { if err != nil || !changed || next.Activity != (Activity{Kind: ActIdle}) { t.Fatalf("Abort of the open session: %+v %t %v", next, changed, err) } - if *next.Current != *h.Current || next.Position != h.Position || len(next.Snapshots) != 1 || next.Snapshots["daily"].Dependents[0] != "t1" { + if *next.Current != *h.Current || next.Position != h.Position || len(next.Snapshots) != 1 || next.Snapshots["daily"].Dependents[0].Target != "t1" { t.Fatalf("Abort changed more than activity: %+v", next) } if h.Activity.Kind != ActSnap { @@ -290,7 +318,7 @@ func TestAbort_Closure(t *testing.T) { want error }{ "other session open": {snapHead("s2"), me, ErrNoSession}, - "cleaning": {Head{Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "s1"}}, me, ErrNoSession}, + "cleaning": {Head{Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActClean, Session: "s1"}}, me, ErrNoSession}, "other epoch": {h, HolderID{Epoch: 4, Holder: "srv-a"}, ErrNotHolder}, "other holder": {h, HolderID{Epoch: 3, Holder: "srv-b"}, ErrNotHolder}, } { @@ -364,13 +392,14 @@ func TestHead_RefusesInvalidUTF8(t *testing.T) { rn := RootName{Hash: Sum([]byte("r"))} bad := "a\xff" for name, h := range map[string]Head{ - "holder": {Epoch: 1, Holder: bad, Activity: Activity{Kind: ActIdle}}, - "session": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActSnap, Session: bad}}, - "snapshot": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, - "dependent": {Epoch: 1, Holder: "a", Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []string{bad}}}}, + "holder": {Epoch: 1, Holder: bad, ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}}, + "session": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActSnap, Session: bad}}, + "snapshot": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{bad: {Root: rn}}}, + "dependent": {Epoch: 1, Holder: "a", ClaimID: "k", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Snapshots: map[string]Snapshot{"n": {Root: rn, Dependents: []Dependent{{Target: bad, TargetID: idFor("x"), Root: rn}}}}}, + "claim id": {Epoch: 1, Holder: "a", ClaimID: bad, VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}}, } { - if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { - t.Errorf("%s %q: %v; want ErrMalformed", name, bad, err) + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) || !strings.Contains(err.Error(), "not valid UTF-8") { + t.Errorf("%s %q: %v; want the UTF-8 refusal", name, bad, err) } } h := idleHead() @@ -379,3 +408,32 @@ func TestHead_RefusesInvalidUTF8(t *testing.T) { t.Fatalf("Begin with an invalid UTF-8 session: %v, HEAD %+v; want refused, nothing written", err, st.h.Activity) } } + +// A HEAD is read only for the volume whose VOLUME carries its volume id: a +// HEAD left by an interrupted delete, or created late by an old restore, +// under a name since given to another volume, is refused (ErrIdentity). +func TestDecodeHead_RefusesAnotherVolumesHead(t *testing.T) { + b, err := idleHead().Encode() + if err != nil { + t.Fatal(err) + } + if _, err := DecodeHead(b, 1, idFor("v1")); err != nil { + t.Fatalf("HEAD of this volume: %v", err) + } + if _, err := DecodeHead(b, 1, idFor("v1 again")); !errors.Is(err, ErrIdentity) { + t.Fatalf("HEAD under a name now holding another volume: %v; want ErrIdentity", err) + } + if _, err := DecodeHead(b, 1, VolumeID{}); err == nil { + t.Fatal("DecodeHead without the volume's id accepted") + } +} + +// A HEAD naming a holder names its claim id too: a holder without one +// would fail closed only at its next claim. +func TestHead_HolderNeedsAClaimID(t *testing.T) { + h := idleHead() + h.ClaimID = "" + if _, err := h.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("HEAD with a holder and no claim id: %v; want ErrMalformed", err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/layout.go b/seaweed-block/core/frontend/chunkstore/layout/layout.go index c4b470dfff..91817ea5d8 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/layout.go +++ b/seaweed-block/core/frontend/chunkstore/layout/layout.go @@ -125,9 +125,12 @@ func (c ChunkName) Verify(data []byte) error { // Ref is one entry of a manifest: the chunk at an index, held in the pool // of Owner (the volume itself, or the source volume of a restore). +// OwnerID is that volume's id: a volume created again under Owner's name +// has another id and satisfies no reference to the old one. type Ref struct { - Owner string - Chunk ChunkName + Owner string + OwnerID VolumeID + Chunk ChunkName } // checkOwner enforces a plain path element, as volume ids are. @@ -145,7 +148,7 @@ type Segment struct { Chunks map[uint64]Ref // by chunk index } -var segMagic = []byte("SWBSEG\x01") +var segMagic = []byte("SWBSEG\x02") var rootMagic = []byte("SWBROOT\x01") // Encode returns the canonical bytes of s: entries in index order. It @@ -166,6 +169,9 @@ func (s Segment) Encode() ([]byte, error) { if err := checkOwner(r.Owner); err != nil { return nil, err } + if r.OwnerID.IsZero() { + return nil, fmt.Errorf("%w: chunk %d names owner %q without its volume id", ErrMalformed, i, r.Owner) + } idx = append(idx, i) } sort.Slice(idx, func(a, b int) bool { return idx[a] < idx[b] }) @@ -178,6 +184,7 @@ func (s Segment) Encode() ([]byte, error) { b.Write(binary.AppendUvarint(nil, i)) b.Write(binary.AppendUvarint(nil, uint64(len(r.Owner)))) b.WriteString(r.Owner) + b.Write(r.OwnerID[:]) b.Write(r.Chunk.Hash[:]) } return b.Bytes(), nil @@ -232,13 +239,15 @@ func DecodeSegment(b []byte) (Segment, error) { for k := uint64(0); k < n && r.err == nil; k++ { i := r.uvarint() owner := string(r.bytes(r.uvarint())) + var oid VolumeID + copy(oid[:], r.bytes(uint64(len(oid)))) var h Hash copy(h[:], r.bytes(uint64(len(h)))) if r.err == nil { if _, dup := s.Chunks[i]; dup { return Segment{}, fmt.Errorf("%w: chunk %d twice", ErrMalformed, i) } - s.Chunks[i] = Ref{Owner: owner, Chunk: ChunkName{Index: i, Hash: h}} + s.Chunks[i] = Ref{Owner: owner, OwnerID: oid, Chunk: ChunkName{Index: i, Hash: h}} } } if r.err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/layout_test.go b/seaweed-block/core/frontend/chunkstore/layout/layout_test.go index d3660a1ac4..b755a7d60a 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/layout_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/layout_test.go @@ -84,8 +84,16 @@ func TestParseChunkName_RoundTripAndRefusals(t *testing.T) { } } +// idFor is a fixed test volume id per volume name. +func idFor(name string) VolumeID { + var id VolumeID + h := Sum([]byte("volume " + name)) + copy(id[:], h[:]) + return id +} + func ref(owner string, idx uint64, data string) Ref { - return Ref{Owner: owner, Chunk: NameChunk(idx, []byte(data))} + return Ref{Owner: owner, OwnerID: idFor(owner), Chunk: NameChunk(idx, []byte(data))} } // goldenSegment is the encoding of shard 1 holding chunk 10000 ("abc", own) @@ -95,16 +103,20 @@ func goldenSegment(t *testing.T) []byte { h := mustHash(t, abcHash) h2 := Sum([]byte("x")) var b []byte - b = append(b, "SWBSEG\x01"...) + b = append(b, "SWBSEG\x02"...) b = binary.AppendUvarint(b, 1) // shard b = binary.AppendUvarint(b, 2) // entries b = binary.AppendUvarint(b, 10000) b = binary.AppendUvarint(b, 2) b = append(b, "v1"...) + v1 := idFor("v1") + b = append(b, v1[:]...) b = append(b, h[:]...) b = binary.AppendUvarint(b, 10001) b = binary.AppendUvarint(b, 3) b = append(b, "src"...) + src := idFor("src") + b = append(b, src[:]...) b = append(b, h2[:]...) return b } @@ -143,6 +155,7 @@ func TestSegment_EncodeRefusals(t *testing.T) { "owner empty": {Shard: 0, Chunks: map[uint64]Ref{1: ref("", 1, "a")}}, "owner with slash": {Shard: 0, Chunks: map[uint64]Ref{1: ref("a/b", 1, "a")}}, "owner dot-dot": {Shard: 0, Chunks: map[uint64]Ref{1: ref("..", 1, "a")}}, + "owner without id": {Shard: 0, Chunks: map[uint64]Ref{1: {Owner: "v1", Chunk: NameChunk(1, []byte("a"))}}}, } { if _, err := s.Encode(); !errors.Is(err, ErrMalformed) { t.Errorf("%s: %v; want ErrMalformed", name, err) @@ -154,13 +167,14 @@ func TestSegment_EncodeRefusals(t *testing.T) { // makes: the hostile inputs DecodeSegment must refuse. func segBytes(shard uint64, entries ...Ref) []byte { var b []byte - b = append(b, "SWBSEG\x01"...) + b = append(b, "SWBSEG\x02"...) b = binary.AppendUvarint(b, shard) b = binary.AppendUvarint(b, uint64(len(entries))) for _, r := range entries { b = binary.AppendUvarint(b, r.Chunk.Index) b = binary.AppendUvarint(b, uint64(len(r.Owner))) b = append(b, r.Owner...) + b = append(b, r.OwnerID[:]...) b = append(b, r.Chunk.Hash[:]...) } return b @@ -172,12 +186,12 @@ func TestDecodeSegment_RefusesNonCanonical(t *testing.T) { if _, err := DecodeSegment(good); err != nil { t.Fatalf("control: %v", err) } - nonMinimal := append([]byte("SWBSEG\x01"), 0x80, 0x00) // shard 0 in two bytes - nonMinimal = append(nonMinimal, segBytes(0, a, c)[len("SWBSEG\x01")+1:]...) - huge := append([]byte("SWBSEG\x01"), 0) + nonMinimal := append([]byte("SWBSEG\x02"), 0x80, 0x00) // shard 0 in two bytes + nonMinimal = append(nonMinimal, segBytes(0, a, c)[len("SWBSEG\x02")+1:]...) + huge := append([]byte("SWBSEG\x02"), 0) huge = binary.AppendUvarint(huge, ShardSize+1) for name, b := range map[string][]byte{ - "wrong magic": append([]byte("SWBSEG\x02"), good[7:]...), + "wrong magic": append([]byte("SWBSEG\x01"), good[7:]...), "unsorted": segBytes(0, c, a), "duplicate": segBytes(0, a, a), "empty": segBytes(0), @@ -334,7 +348,8 @@ func TestEncodings_RandomRoundTrip(t *testing.T) { i := uint64(rng.Int63n(100000)) var d [8]byte rng.Read(d[:]) - m[i] = Ref{Owner: owners[rng.Intn(len(owners))], Chunk: NameChunk(i, d[:])} + o := owners[rng.Intn(len(owners))] + m[i] = Ref{Owner: o, OwnerID: idFor(o), Chunk: NameChunk(i, d[:])} } root, segs, err := Build(m) if err != nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/read.go b/seaweed-block/core/frontend/chunkstore/layout/read.go index 8ed871c4cc..3fa7de05ff 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read.go @@ -14,6 +14,10 @@ var ErrMissing = errors.New("layout: object missing") // ErrCorrupt reports an object whose bytes do not match its name. var ErrCorrupt = errors.New("layout: object corrupt") +// ErrIdentity reports a reference to a volume whose VOLUME record carries +// another id: the volume was deleted and created again under the name. +var ErrIdentity = errors.New("layout: volume id does not match the reference") + // Fetch reads the whole object at p. A missing object is (nil, false, nil); // any other failure is an error. type Fetch func(ctx context.Context, p string) (data []byte, found bool, err error) @@ -24,6 +28,7 @@ type Fetch func(ctx context.Context, p string) (data []byte, found bool, err err type Reader struct { base, vol string fetch Fetch + ids map[string]VolumeID // VOLUME ids read so far, by volume name } // NewReader returns a Reader of vol under base. @@ -34,7 +39,29 @@ func NewReader(base, vol string, fetch Fetch) (*Reader, error) { if fetch == nil { return nil, errors.New("layout: reader needs a fetch") } - return &Reader{base: base, vol: vol, fetch: fetch}, nil + return &Reader{base: base, vol: vol, fetch: fetch, ids: map[string]VolumeID{}}, nil +} + +// VolumeID returns the id in the VOLUME record of the named volume, read +// once per Reader. A missing VOLUME is ErrMissing. +func (r *Reader) VolumeID(ctx context.Context, vol string) (VolumeID, error) { + if id, ok := r.ids[vol]; ok { + return id, nil + } + p := path.Join(r.base, vol, VolumeName) + b, ok, err := r.fetch(ctx, p) + if err != nil { + return VolumeID{}, fmt.Errorf("layout: read %s: %w", p, err) + } + if !ok { + return VolumeID{}, fmt.Errorf("%w: %s", ErrMissing, p) + } + v, err := DecodeVolume(b) + if err != nil { + return VolumeID{}, fmt.Errorf("%w: %s: %v", ErrCorrupt, p, err) + } + r.ids[vol] = v.ID + return v.ID, nil } // get fetches the object at rel under volume vol and checks its bytes hash @@ -120,8 +147,9 @@ func (img *Image) Resolve(ctx context.Context, index uint64) (ref Ref, zero bool } // Chunk resolves index and reads its bytes from the pool of the volume -// that owns it. A chunk the root names but the owner's pool lacks is -// ErrMissing. +// that owns it, after checking that volume's VOLUME id is the one the +// reference carries (ErrIdentity otherwise). A chunk the root names but the +// owner's pool lacks is ErrMissing. func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { ref, zero, err := img.Resolve(ctx, index) if err != nil { @@ -130,6 +158,13 @@ func (img *Image) Chunk(ctx context.Context, index uint64) (Chunk, error) { if zero { return Chunk{Zero: true}, nil } + id, err := img.r.VolumeID(ctx, ref.Owner) + if err != nil { + return Chunk{}, err + } + if id != ref.OwnerID { + return Chunk{}, fmt.Errorf("%w: chunk %d names %s id %s, VOLUME has %s", ErrIdentity, index, ref.Owner, ref.OwnerID, id) + } b, err := img.r.get(ctx, ref.Owner, ref.Chunk.Path(), ref.Chunk.Hash) if err != nil { return Chunk{}, err diff --git a/seaweed-block/core/frontend/chunkstore/layout/read_test.go b/seaweed-block/core/frontend/chunkstore/layout/read_test.go index b3bd1c94ee..67de891f2f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/read_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/read_test.go @@ -38,7 +38,9 @@ func readFixture(t *testing.T) (*objStore, RootName, map[uint64]Ref) { foreign := NameChunk(10002, []byte("src data")) put("t", own.Path(), []byte("own")) put("src", foreign.Path(), []byte("src data")) - m := map[uint64]Ref{3: {Owner: "t", Chunk: own}, 10002: {Owner: "src", Chunk: foreign}} + m := map[uint64]Ref{3: {Owner: "t", OwnerID: idFor("t"), Chunk: own}, 10002: {Owner: "src", OwnerID: idFor("src"), Chunk: foreign}} + putVolume(t, put, "t") + putVolume(t, put, "src") root, segs, err := Build(m) if err != nil { t.Fatal(err) @@ -212,7 +214,7 @@ func TestRead_FetchFailureAndCorruption(t *testing.T) { func TestRead_SegmentOfAnotherShardRefused(t *testing.T) { ctx := context.Background() s := &objStore{obj: map[string][]byte{}} - seg := Segment{Shard: 2, Chunks: map[uint64]Ref{20000: {Owner: "t", Chunk: NameChunk(20000, []byte("z"))}}} + seg := Segment{Shard: 2, Chunks: map[uint64]Ref{20000: {Owner: "t", OwnerID: idFor("t"), Chunk: NameChunk(20000, []byte("z"))}}} sn, sb, err := NameSegment(seg) if err != nil { t.Fatal(err) @@ -243,3 +245,48 @@ func TestNewReader_RefusesBadInput(t *testing.T) { t.Error("nil fetch accepted") } } + +// putVolume writes vol's VOLUME record with its test id. +func putVolume(t *testing.T, put func(vol, rel string, b []byte), vol string) { + t.Helper() + b, err := Volume{ID: idFor(vol), Name: vol, Format: VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + put(vol, VolumeName, b) +} + +// A foreign chunk is read only if its owner's VOLUME carries the id the +// reference names: a source deleted and created again under its name has +// another id (ErrIdentity); a source without VOLUME is ErrMissing. The +// chunk's bytes are never fetched in either case. +func TestRead_ForeignChunkNeedsTheOwnersVolumeID(t *testing.T) { + ctx := context.Background() + s, rn, m := readFixture(t) + b, err := Volume{ID: idFor("src again"), Name: "src", Format: VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + s.obj[path.Join(base, "src", VolumeName)] = b + img, err := newReader(t, s).Open(ctx, rn) + if err != nil { + t.Fatal(err) + } + s.asked = nil + if _, err := img.Chunk(ctx, 10002); !errors.Is(err, ErrIdentity) { + t.Fatalf("chunk of a re-created source: %v; want ErrIdentity", err) + } + for _, p := range s.asked { + if p == path.Join(base, "src", m[10002].Chunk.Path()) { + t.Fatal("the chunk was fetched from a source whose id does not match") + } + } + delete(s.obj, path.Join(base, "src", VolumeName)) + img, _ = newReader(t, s).Open(ctx, rn) + if _, err := img.Chunk(ctx, 10002); !errors.Is(err, ErrMissing) { + t.Fatalf("chunk of a source without VOLUME: %v; want ErrMissing", err) + } + if c, err := img.Chunk(ctx, 3); err != nil || c.Zero { + t.Fatalf("own chunk beside it: %+v %v", c, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove.go b/seaweed-block/core/frontend/chunkstore/layout/remove.go index d84751bf69..b943522fdf 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove.go @@ -100,6 +100,10 @@ func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkN for _, s := range h.Snapshots { roots[s.Root] = true } + own, err := r.VolumeID(ctx, r.vol) + if err != nil { + return nil, err + } live := map[ChunkName]bool{} for rn := range roots { img, err := r.Open(ctx, rn) @@ -114,7 +118,7 @@ func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkN continue } for _, ref := range seg.Chunks { - if ref.Owner == r.vol { + if ref.OwnerID == own { live[ref.Chunk] = true } } diff --git a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go index a48faa2145..75814f07c3 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/remove_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/remove_test.go @@ -28,11 +28,16 @@ func removeFixture(t *testing.T) (*memObjects, *Head, []ChunkName, []ChunkName) data[path.Join(volRoot, c.Path())] = []byte(d) orphans = append(orphans, c) } + vb, err := Volume{ID: idFor("v1"), Name: "v1", Format: VolumeFormat}.Encode() + if err != nil { + t.Fatal(err) + } + data[path.Join(volRoot, VolumeName)] = vb o := newMemObjects(volRoot) for p, b := range data { o.objs[p] = &memObject{data: b, meta: ObjectMeta{Session: "s0"}} } - h := &Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActClean, Session: "c1"}, Current: &curRoot, + h := &Head{Gen: 7, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActClean, Session: "c1"}, Current: &curRoot, Snapshots: map[string]Snapshot{"daily": {Root: oldRoot}}} live := []ChunkName{cur[0].Chunk, cur[3].Chunk, old[2].Chunk} return o, h, live, orphans @@ -180,13 +185,15 @@ func TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark(t *testing.T } } st := &memHead{h: h} + var hookErr error st.afterRead = func() { if err := EnsureObject(context.Background(), o, target.Path(), []byte("e"), "successor"); err != nil { - t.Fatal(err) + hookErr = err + return } // The successor's commit names the reused chunk; the old holder's // HEAD view (already taken) still shows its own cleaning. - next := manifest(Ref{Owner: "v1", Chunk: target}) + next := manifest(Ref{Owner: "v1", OwnerID: idFor("v1"), Chunk: target}) rn := writeImage(t, map[string][]byte{}, next, map[uint64][]byte{5: []byte("e")}) root, segs, _ := Build(next) _ = root @@ -200,6 +207,9 @@ func TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark(t *testing.T if _, err := removeShard0(t, st, o, "c1", orphans); err != nil { t.Fatal(err) } + if hookErr != nil { + t.Fatal(hookErr) + } if !inPool(o, target) { t.Fatalf("chunk %s, reused and committed by the successor after the remover's HEAD view, was removed", target) } @@ -367,3 +377,13 @@ func TestCleaningPass_InterruptAtEveryStep(t *testing.T) { } } } + +// The remover tells its own chunks by its VOLUME id: without a readable +// VOLUME it removes nothing. +func TestRemoveUnreachable_NeedsItsOwnVolumeID(t *testing.T) { + o, h, _, orphans := removeFixture(t) + delete(o.objs, path.Join(volRoot, VolumeName)) + if _, err := removeShard0(t, &memHead{h: h}, o, "c1", orphans); !errors.Is(err, ErrMissing) || len(o.writes) != 0 { + t.Fatalf("removal without VOLUME: %v, %d writes; want ErrMissing and none", err, len(o.writes)) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/session_test.go b/seaweed-block/core/frontend/chunkstore/layout/session_test.go index 129b7e48cb..8df5448731 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/session_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/session_test.go @@ -217,7 +217,7 @@ func sessionFixture(t *testing.T) (func() *memVolume, map[uint64][]byte, CommitR fresh := func() *memVolume { objs := map[string][]byte{} prevRoot := writeImage(t, objs, prev, prevData) - h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, + h := Head{Gen: 7, Epoch: 3, Holder: "srv-a", ClaimID: "k-a", VolumeID: idFor("v1"), Activity: Activity{Kind: ActIdle}, Current: &prevRoot, Position: 40, Snapshots: map[string]Snapshot{"daily": {Root: prevRoot}}} return &memVolume{head: &memHead{h: &h}, objects: objs, metas: map[string]ObjectMeta{}} } diff --git a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go index dcb7ee16b6..41d2159822 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/stale_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/stale_test.go @@ -28,8 +28,9 @@ func TestTransitions_RefuseAStaleHolder(t *testing.T) { "Claim": func(h Head, c HolderID) error { _, _, err := h.Claim(c); return err }, } callers := map[string]HolderID{ - "older epoch, same server": {Epoch: 2, Holder: "srv-a"}, - "same epoch, another server": {Epoch: 3, Holder: "srv-b"}, + "older epoch, same server": {Epoch: 2, Holder: "srv-a"}, + "same epoch, another server": {Epoch: 3, Holder: "srv-b"}, + "same epoch and server, another claim id": {Epoch: 3, Holder: "srv-a", ClaimID: "k-other"}, } for name, step := range steps { for who, c := range callers { @@ -64,8 +65,9 @@ func TestTransitions_RefuseAStaleHolder(t *testing.T) { // above) must be listed here, so a new one fails until it is covered. func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) { callers := map[string]HolderID{ - "older epoch, same server": {Epoch: me.Epoch - 1, Holder: me.Holder}, - "same epoch, another server": {Epoch: me.Epoch, Holder: "srv-b"}, + "older epoch, same server": {Epoch: me.Epoch - 1, Holder: me.Holder, ClaimID: me.ClaimID}, + "same epoch, another server": {Epoch: me.Epoch, Holder: "srv-b", ClaimID: me.ClaimID}, + "same epoch and server, another claim id": {Epoch: me.Epoch, Holder: me.Holder, ClaimID: "k-other"}, } for who, c := range callers { o, h, _, orphans := removeFixture(t) diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume.go b/seaweed-block/core/frontend/chunkstore/layout/volume.go new file mode 100644 index 0000000000..a15efbca4b --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/volume.go @@ -0,0 +1,105 @@ +package layout + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" +) + +// VolumeName is the entry, under the volume root, that holds the volume's +// identity: written once, never changed. +const VolumeName = "VOLUME" + +// VolumeID is a volume's identity: random, chosen when the volume is +// created. A volume's name is a path and can be created again after a +// delete; its id cannot, so a volume created again satisfies no reference +// to the old one. +type VolumeID [16]byte + +// NewVolumeID returns a random volume id. +func NewVolumeID() (VolumeID, error) { + var id VolumeID + if _, err := rand.Read(id[:]); err != nil { + return VolumeID{}, fmt.Errorf("layout: volume id: %w", err) + } + return id, nil +} + +func (id VolumeID) String() string { return hex.EncodeToString(id[:]) } + +// IsZero reports whether id is unset; the zero id names no volume. +func (id VolumeID) IsZero() bool { return id == VolumeID{} } + +// ParseVolumeID parses 32 lower-case hex digits; the zero id is refused. +func ParseVolumeID(s string) (VolumeID, error) { + var id VolumeID + if len(s) != 2*len(id) || s != string(bytes.ToLower([]byte(s))) { + return VolumeID{}, fmt.Errorf("%w: volume id %q is not 32 lower-case hex digits", ErrMalformed, s) + } + if _, err := hex.Decode(id[:], []byte(s)); err != nil { + return VolumeID{}, fmt.Errorf("%w: volume id %q: %v", ErrMalformed, s, err) + } + if id.IsZero() { + return VolumeID{}, fmt.Errorf("%w: zero volume id", ErrMalformed) + } + return id, nil +} + +// VolumeFormat is the layout format a VOLUME record declares. +const VolumeFormat = 1 + +// Volume is the VOLUME record: the volume's id, its name when created, and +// the layout format. +type Volume struct { + ID VolumeID + Name string + Format int +} + +type volumeDoc struct { + ID string `json:"id"` + Name string `json:"name"` + Format int `json:"format"` +} + +// Encode returns the record's canonical bytes. +func (v Volume) Encode() ([]byte, error) { + if v.ID.IsZero() { + return nil, fmt.Errorf("%w: VOLUME without an id", ErrMalformed) + } + if err := checkOwner(v.Name); err != nil { + return nil, err + } + if err := validName("volume name", v.Name); err != nil { + return nil, err + } + if v.Format != VolumeFormat { + return nil, fmt.Errorf("%w: VOLUME format %d, want %d", ErrMalformed, v.Format, VolumeFormat) + } + return json.Marshal(volumeDoc{ID: v.ID.String(), Name: v.Name, Format: v.Format}) +} + +// DecodeVolume parses canonical VOLUME bytes. +func DecodeVolume(b []byte) (Volume, error) { + var d volumeDoc + dec := json.NewDecoder(bytes.NewReader(b)) + dec.DisallowUnknownFields() + if err := dec.Decode(&d); err != nil { + return Volume{}, fmt.Errorf("%w: VOLUME: %v", ErrMalformed, err) + } + id, err := ParseVolumeID(d.ID) + if err != nil { + return Volume{}, err + } + v := Volume{ID: id, Name: d.Name, Format: d.Format} + again, err := v.Encode() + if err != nil { + return Volume{}, err + } + if !bytes.Equal(again, b) { + return Volume{}, fmt.Errorf("%w: VOLUME bytes are not canonical", ErrMalformed) + } + return v, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/layout/volume_test.go b/seaweed-block/core/frontend/chunkstore/layout/volume_test.go new file mode 100644 index 0000000000..08ac14c0a3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/volume_test.go @@ -0,0 +1,63 @@ +package layout + +import ( + "errors" + "strings" + "testing" +) + +func TestVolumeID_RandomAndParsed(t *testing.T) { + a, err := NewVolumeID() + if err != nil { + t.Fatal(err) + } + b, _ := NewVolumeID() + if a.IsZero() || a == b { + t.Fatalf("volume ids %s and %s: want two different non-zero ids", a, b) + } + back, err := ParseVolumeID(a.String()) + if err != nil || back != a { + t.Fatalf("round trip of %s: %s %v", a, back, err) + } + for _, bad := range []string{"", strings.Repeat("0", 32), strings.ToUpper(a.String()), a.String()[:31], a.String() + "0", strings.Repeat("g", 32)} { + if _, err := ParseVolumeID(bad); !errors.Is(err, ErrMalformed) { + t.Errorf("ParseVolumeID(%q): %v; want ErrMalformed", bad, err) + } + } +} + +func TestVolume_GoldenEncodingRoundTrip(t *testing.T) { + v := Volume{ID: idFor("v1"), Name: "v1", Format: VolumeFormat} + b, err := v.Encode() + if err != nil { + t.Fatal(err) + } + want := `{"id":"` + idFor("v1").String() + `","name":"v1","format":1}` + if string(b) != want { + t.Fatalf("encoding\n got %s\nwant %s", b, want) + } + back, err := DecodeVolume(b) + if err != nil || back != v { + t.Fatalf("decode: %+v %v", back, err) + } + for name, bad := range map[string]Volume{ + "zero id": {Name: "v1", Format: VolumeFormat}, + "name with path": {ID: idFor("v1"), Name: "a/b", Format: VolumeFormat}, + "invalid UTF-8": {ID: idFor("v1"), Name: "a\xff", Format: VolumeFormat}, + "other format": {ID: idFor("v1"), Name: "v1", Format: 2}, + } { + if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: %v; want ErrMalformed", name, err) + } + } + for name, raw := range map[string]string{ + "unknown field": strings.Replace(want, `"format"`, `"extra":1,"format"`, 1), + "whitespace": strings.Replace(want, `,`, `, `, 1), + "zero id": strings.Replace(want, idFor("v1").String(), strings.Repeat("0", 32), 1), + "not json": "VOLUME", + } { + if _, err := DecodeVolume([]byte(raw)); !errors.Is(err, ErrMalformed) { + t.Errorf("decode %s: %v; want ErrMalformed", name, err) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 51bd4eade8..b6e2d97c4f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -525,9 +525,9 @@ stateDiagram-v2 idle --> snap: Begin(s) snap --> idle: Abort(s) snap --> idle: Commit(s, root) - idle --> idle: Claim(e) - snap --> idle: Claim(e), s void - clean --> idle: Claim(e), c void + idle --> idle: Claim(e, claim id) + snap --> idle: Claim(e, claim id), s void + clean --> idle: Claim(e, claim id), c void idle --> clean: BeginClean(c) clean --> idle: EndClean(c) clean --> clean: RemoveUnreachable(shard) @@ -535,17 +535,17 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| idle | snap(s) | caller is the holder at HEAD's epoch (epoch and server); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | -| snap(s) | idle | holder at HEAD's epoch; activity is snap(s); over idle it succeeds without a write and means only that no activity remains | head.go `Head.Abort` | `INV-SNAPK-ABORT-001` | -| snap(s) | idle, current = root | holder at HEAD's epoch; activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001` | -| any | idle at epoch e | e above HEAD's epoch (the same epoch and server is a replay); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001` | -| idle | clean(c) | holder at HEAD's epoch; activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | -| clean(c) | idle | holder at HEAD's epoch; activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | -| clean(c) | clean(c), names removed | holder at HEAD's epoch with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | +| idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` | +| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains | head.go `Head.Abort` | `INV-SNAPK-ABORT-001` | +| snap(s) | idle, current = root | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); the previous manifest builds to HEAD's current root; the new own chunks, every segment and the root are present | commit.go `Head.Commit`, `RunCommit` | `INV-SNAPK-COMMIT-REACH-001`, `INV-SNAPK-TXN-INTERRUPT-001` | +| any | idle at epoch e, claim id k | e above HEAD's epoch (the same epoch, server and claim id is a replay; the same epoch and server with another claim id is refused); every older holder's lease has ended, checked after the read and before the update | claim.go `Head.Claim`, `RunClaim` (`LeaseWait.OldLeaseEnded`) | `INV-SNAPK-CLAIM-LEASE-001`, `INV-SNAPK-CLAIM-ID-001` | +| idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` | +| clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` | +| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` | ## Part B. Invariant ledger -344 rows: 273 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 329 new. +349 rows: 278 ACTIVE, 67 STUB, 4 ARCHIVED; 15 kept from the internal ledger, 334 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -1100,6 +1100,11 @@ Notes: | `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-ID-001` | HEAD is decoded only for the volume whose VOLUME carries its volume id; a HEAD of another id, left by an interrupted delete or an old restore under a reused name, is ErrIdentity; a holder without a claim id is malformed. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `DecodeHead`, `Head.check` | `TestDecodeHead_RefusesAnotherVolumesHead`, `TestHead_HolderNeedsAClaimID` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-REF-ID-001` | Every chunk reference in a segment carries its owner's volume id; a read checks it against the owner's VOLUME before fetching (another id is ErrIdentity), and the remover tells its own chunks by its VOLUME id. | Content-named layout | `core/frontend/chunkstore/layout` `layout.go` `Segment.Encode`; `read.go` `Image.Chunk`; `remove.go` | `TestSegment_EncodeRefusals`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`, `TestRemoveUnreachable_NeedsItsOwnVolumeID` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-DEP-ID-001` | Every dependent records the target's volume id and the root of the snapshot it depends on; a dependent without the id, or of another root, is refused. | M9 snapshots and dependents | `core/frontend/chunkstore/layout` `head.go` `Head.check` | `TestHead_Refusals`, `TestHead_GoldenEncodingRoundTrip` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-CLAIM-ID-001` | A holder is its epoch, its server and the claim id its claim wrote into HEAD; every transition refuses the same server at the same epoch with another claim id. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `heldBy`; `claim.go` `Head.Claim` | `TestClaim_WritesItsClaimID`, `TestTransitions_RefuseAStaleHolder`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-STALE-HOLDER-001` | Every transition refuses an older epoch of the same server, the same epoch held by another server, and the same epoch and server with another claim id, in idle, snap and clean; a new transition must be added to the table. | M9 every transition | `core/frontend/chunkstore/layout` `Head.heldBy` and each transition | `TestTransitions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE | Notes: