mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Merge pull request #664 from seaweedfs/fix/refresh-live-after-fence
fix(volume): re-draw the live ship session above a completed fence
This commit is contained in:
commit
dfeab5fa45
5 files changed
+618
-41
No files matched your search
@@ -81,18 +81,8 @@ func (p *PeerCommandExecutor) SetOnSessionStart(fn adapter.OnSessionStart) {
|
||||
// session ID.
|
||||
func (p *PeerCommandExecutor) SetOnSessionClose(fn adapter.OnSessionClose) {
|
||||
p.inner.SetOnSessionClose(func(r adapter.SessionCloseResult) {
|
||||
if r.Success {
|
||||
if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, r.AchievedLSN, "recovery session completed"); err != nil {
|
||||
r.Success = false
|
||||
r.FailReason = err.Error()
|
||||
p.peer.Invalidate("live session refresh failed: " + err.Error())
|
||||
} else {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), healReconcileTimeout)
|
||||
p.peer.HealIfInSync(ctx, "recovery session completed")
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
// Failure path: the adapter feeds engine
|
||||
r = p.afterSessionClose(r)
|
||||
// Failure path (after the re-draw above): the adapter feeds engine
|
||||
// SessionClosedFailed which (per FailureKind) may emit
|
||||
// PublishDegraded; that lands at our PublishDegraded
|
||||
// override and calls peer.Invalidate. We do NOT
|
||||
@@ -104,11 +94,64 @@ func (p *PeerCommandExecutor) SetOnSessionClose(fn adapter.OnSessionClose) {
|
||||
})
|
||||
}
|
||||
|
||||
// SetOnFenceComplete delegates verbatim to the inner executor.
|
||||
// Fence completion does not directly drive peer state; it advances
|
||||
// engine Reachability.FencedEpoch which is the ack-gate for Healthy.
|
||||
// afterSessionClose re-draws the peer's live session above the closed
|
||||
// recovery session, whatever its outcome: a session the replica admitted
|
||||
// moved its held lineage even when its close failed (a lost final ack),
|
||||
// and a live frame below it would be refused as stale. A completed one
|
||||
// also advances the cursor and heals the peer when it is in sync.
|
||||
func (p *PeerCommandExecutor) afterSessionClose(r adapter.SessionCloseResult) adapter.SessionCloseResult {
|
||||
if !r.Success {
|
||||
if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, "recovery session failed"); err != nil {
|
||||
p.peer.Invalidate("live session refresh failed: " + err.Error())
|
||||
}
|
||||
return r
|
||||
}
|
||||
if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, r.AchievedLSN, "recovery session completed"); err != nil {
|
||||
r.Success = false
|
||||
r.FailReason = err.Error()
|
||||
p.peer.Invalidate("live session refresh failed: " + err.Error())
|
||||
return r
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), healReconcileTimeout)
|
||||
p.peer.HealIfInSync(ctx, "recovery session completed")
|
||||
cancel()
|
||||
return r
|
||||
}
|
||||
|
||||
// SetOnFenceComplete wraps the adapter-supplied callback so a completed
|
||||
// fence first re-draws the peer's live session above the fence's, then
|
||||
// lets the engine advance Reachability.FencedEpoch (the ack-gate for
|
||||
// Healthy). A fence mints its own session from the peer's one session
|
||||
// order, and the replica holds the fence's lineage once it acknowledges
|
||||
// it: the live session, drawn earlier, would be below it, and every later
|
||||
// barrier or ship on it refused as stale. The re-draw runs only once the
|
||||
// fence's exchange is over (this callback), so the replica never holds a
|
||||
// live lineage above an in-flight fence; and it runs on a failed fence too,
|
||||
// since the replica may have admitted the fence and only its reply was lost.
|
||||
func (p *PeerCommandExecutor) SetOnFenceComplete(fn adapter.OnFenceComplete) {
|
||||
p.inner.SetOnFenceComplete(fn)
|
||||
p.inner.SetOnFenceComplete(func(r adapter.FenceResult) {
|
||||
r = p.afterFence(r)
|
||||
if fn != nil {
|
||||
fn(r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// afterFence re-draws the peer's live session above the fence's session,
|
||||
// whatever the fence's outcome.
|
||||
func (p *PeerCommandExecutor) afterFence(r adapter.FenceResult) adapter.FenceResult {
|
||||
reason := "fence completed"
|
||||
if !r.Success {
|
||||
reason = "fence failed"
|
||||
}
|
||||
if err := p.peer.RefreshLiveShipSessionAfter(r.SessionID, 0, reason); err != nil {
|
||||
p.peer.Invalidate("live session refresh after fence failed: " + err.Error())
|
||||
if r.Success {
|
||||
r.Success = false
|
||||
r.FailReason = err.Error()
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// --- Wire-level command delegation (verbatim to inner) ---
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/transport"
|
||||
)
|
||||
|
||||
// replyDropProxy sits between the primary and a replica. In drop mode a
|
||||
// new connection forwards the primary's frames to the replica (which
|
||||
// admits and applies them) but discards the replica's replies: the
|
||||
// primary's exchange times out although the replica acted on every frame.
|
||||
type replyDropProxy struct {
|
||||
ln net.Listener
|
||||
upstream string
|
||||
drop atomic.Bool
|
||||
mu sync.Mutex
|
||||
conns []net.Conn
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func startReplyDropProxy(t *testing.T, addr, upstream string) *replyDropProxy {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &replyDropProxy{ln: ln, upstream: upstream}
|
||||
p.wg.Add(1)
|
||||
go func() {
|
||||
defer p.wg.Done()
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
u, err := net.Dial("tcp", upstream)
|
||||
if err != nil {
|
||||
_ = c.Close()
|
||||
continue
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.conns = append(p.conns, c, u)
|
||||
p.mu.Unlock()
|
||||
dropping := p.drop.Load()
|
||||
p.wg.Add(2)
|
||||
go func() { defer p.wg.Done(); _, _ = io.Copy(u, c); _ = u.Close() }()
|
||||
go func() {
|
||||
defer p.wg.Done()
|
||||
if dropping {
|
||||
// The replica acts on every frame; its replies are
|
||||
// discarded, so the sender times out waiting for them.
|
||||
_, _ = io.Copy(io.Discard, u)
|
||||
} else {
|
||||
_, _ = io.Copy(c, u)
|
||||
}
|
||||
_ = c.Close()
|
||||
_ = u.Close()
|
||||
}()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
_ = ln.Close()
|
||||
p.mu.Lock()
|
||||
for _, c := range p.conns {
|
||||
_ = c.Close()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
p.wg.Wait()
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
// fenceRig is a primary volume with one degraded peer r2 at epoch 2 and a
|
||||
// real replica listener, either at the primary's end or `behind` entries
|
||||
// short of it, optionally reached through a replyDropProxy.
|
||||
type fenceRig struct {
|
||||
peer *replication.ReplicaPeer
|
||||
exec *PeerCommandExecutor
|
||||
v *replication.ReplicationVolume
|
||||
primary, replica *storage.BlockStore
|
||||
proxy *replyDropProxy
|
||||
}
|
||||
|
||||
func newFenceRig(t *testing.T, behind int, proxied bool) *fenceRig {
|
||||
t.Helper()
|
||||
const blockSize, n = 4096, 4
|
||||
r := &fenceRig{primary: storage.NewBlockStore(64, blockSize), replica: storage.NewBlockStore(64, blockSize)}
|
||||
for i := 0; i < n; i++ {
|
||||
data := bytes.Repeat([]byte{byte(i + 1)}, blockSize)
|
||||
lsn, err := r.primary.Write(uint32(i), data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i < n-behind {
|
||||
if err := r.replica.ApplyEntry(uint32(i), data, lsn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
own, _ := transport.LoadEpochTable("", "vol1")
|
||||
_ = own.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}})
|
||||
theirs, _ := transport.LoadEpochTable("", "vol1")
|
||||
_ = theirs.Replace([]transport.EpochRow{{Epoch: 2, FirstLSN: 1}})
|
||||
|
||||
// Nothing listens yet: the seed barrier fails and the peer is degraded
|
||||
// (the rejoining replica is not up).
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := l.Addr().String()
|
||||
_ = l.Close()
|
||||
r.v = replication.NewReplicationVolume("vol1", r.primary)
|
||||
r.v.SetDurabilityMode(replication.DurabilitySyncQuorum)
|
||||
r.v.SetEpochTable(own)
|
||||
t.Cleanup(func() { _ = r.v.Close() })
|
||||
if err := r.v.ConfigurePeerLifecycleHook(func(p *replication.ReplicaPeer) { r.peer = p }, func(string) {}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.v.UpdateReplicaSet(1, []replication.ReplicaTarget{{ReplicaID: "r2", DataAddr: addr, ControlAddr: addr, Epoch: 2, EndpointVersion: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.peer == nil || r.peer.State() != replication.ReplicaDegraded {
|
||||
t.Fatalf("peer %v; want degraded after an unanswered seed barrier", r.peer)
|
||||
}
|
||||
listenAt := addr
|
||||
if proxied {
|
||||
listenAt = "127.0.0.1:0"
|
||||
}
|
||||
listener, err := transport.NewReplicaListener(listenAt, r.replica)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener.SetEpochTable(theirs)
|
||||
listener.Serve()
|
||||
if proxied {
|
||||
r.proxy = startReplyDropProxy(t, addr, listener.Addr())
|
||||
}
|
||||
// The primary's connection closes first, or Stop waits for it.
|
||||
t.Cleanup(func() { _ = r.v.Close(); listener.Stop() })
|
||||
r.exec = NewPeerCommandExecutor(r.peer)
|
||||
r.exec.SetOnSessionStart(func(adapter.SessionStartResult) {})
|
||||
return r
|
||||
}
|
||||
|
||||
// fencePeerRig is the caught-up rig, reached directly.
|
||||
func fencePeerRig(t *testing.T) (*replication.ReplicaPeer, *PeerCommandExecutor) {
|
||||
t.Helper()
|
||||
r := newFenceRig(t, 0, false)
|
||||
return r.peer, r.exec
|
||||
}
|
||||
|
||||
// fence runs a fence through the executor's registered callback and
|
||||
// returns its result.
|
||||
func (r *fenceRig) fence(t *testing.T) adapter.FenceResult {
|
||||
t.Helper()
|
||||
done := make(chan adapter.FenceResult, 1)
|
||||
r.exec.SetOnFenceComplete(func(res adapter.FenceResult) { done <- res })
|
||||
if err := r.exec.Fence("r2", r.exec.SessionIDs().Next(), 2, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case res := <-done:
|
||||
return res
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the fence did not complete")
|
||||
return adapter.FenceResult{}
|
||||
}
|
||||
}
|
||||
|
||||
// catchUp runs a catch-up from the replica's end to the primary's through
|
||||
// the executor's registered close callback and returns its result.
|
||||
func (r *fenceRig) catchUp(t *testing.T) adapter.SessionCloseResult {
|
||||
t.Helper()
|
||||
closed := make(chan adapter.SessionCloseResult, 1)
|
||||
r.exec.SetOnSessionClose(func(res adapter.SessionCloseResult) { closed <- res })
|
||||
end, _ := r.replica.Sync()
|
||||
_, _, head := r.primary.Boundaries()
|
||||
// The catch-up states the LSN it starts after: the replica's durable end.
|
||||
if err := r.exec.StartCatchUp("r2", r.exec.SessionIDs().Next(), 2, 1, end, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case res := <-closed:
|
||||
return res
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("the catch-up never closed")
|
||||
return adapter.SessionCloseResult{}
|
||||
}
|
||||
}
|
||||
|
||||
// requireLiveTraffic writes one more block on the primary and requires it
|
||||
// to be shipped and acknowledged on the live session (the replica's end
|
||||
// reaches its LSN).
|
||||
func (r *fenceRig) requireLiveTraffic(t *testing.T) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
data := bytes.Repeat([]byte{0x7C}, 4096)
|
||||
lsn, err := r.primary.Write(9, data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.v.Observe(ctx, 9, lsn, data); err != nil {
|
||||
t.Fatalf("live ship: %v", err)
|
||||
}
|
||||
if err := r.v.Sync(ctx, lsn); err != nil {
|
||||
t.Fatalf("live barrier: %v", err)
|
||||
}
|
||||
// The live session's frames were admitted and acknowledged: the
|
||||
// replica's durable end reached the write.
|
||||
if R, _, _ := r.replica.Boundaries(); R < lsn {
|
||||
t.Fatalf("the live write (LSN %d) was not acknowledged on the replica (end %d)", lsn, R)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A replica that is already at the primary's end (R = H) is fenced at the
|
||||
// peer's epoch with a session the fence mints (as the adapter's
|
||||
// FenceAtEpoch does, from the peer's one session order), above the live
|
||||
// session the peer drew at its creation. The replica then holds the
|
||||
// fence's lineage. The engine's healthy verdict sends its barrier on the
|
||||
// live session: it must be acknowledged and the peer healed, so the live
|
||||
// session must be re-drawn above the fence's once the fence completes.
|
||||
// Without that the replica refuses the barrier as stale, forever.
|
||||
func TestAFencedCaughtUpPeerIsHealedOnItsLiveSession(t *testing.T) {
|
||||
for _, fence := range []bool{true, false} {
|
||||
name := map[bool]string{true: "fenced first", false: "control: no fence"}[fence]
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := newFenceRig(t, 0, false)
|
||||
if fence {
|
||||
if res := r.fence(t); !res.Success {
|
||||
t.Fatalf("fence failed: %s", res.FailReason)
|
||||
}
|
||||
}
|
||||
r.exec.PublishHealthy("r2")
|
||||
if s := r.peer.State(); s != replication.ReplicaHealthy {
|
||||
t.Fatalf("peer %s after the healthy verdict; want healthy (its barrier on the live session must be acknowledged)", s)
|
||||
}
|
||||
r.requireLiveTraffic(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The order of the re-draw: the live session moves above the fence's only
|
||||
// once the fence's exchange is over. Moved before (here: the fence's
|
||||
// session drawn, the live one re-drawn above it, then the fence sent), the
|
||||
// replica holds the higher live lineage and refuses the fence.
|
||||
func TestTheLiveSessionMovesOnlyAfterTheFenceIsAcknowledged(t *testing.T) {
|
||||
peer, exec := fencePeerRig(t)
|
||||
done := make(chan adapter.FenceResult, 1)
|
||||
exec.SetOnFenceComplete(func(r adapter.FenceResult) { done <- r })
|
||||
sid := exec.SessionIDs().Next()
|
||||
if err := peer.RefreshLiveShipSessionAfter(sid, 0, "re-drawn too early"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exec.PublishHealthy("r2") // the replica now holds the live lineage above sid
|
||||
if s := peer.State(); s != replication.ReplicaHealthy {
|
||||
t.Fatalf("fixture: peer %s; want healthy on the re-drawn live session", s)
|
||||
}
|
||||
if err := exec.Fence("r2", sid, 2, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case r := <-done:
|
||||
if r.Success {
|
||||
t.Fatal("a fence below the replica's held live lineage was acknowledged; want it refused (which is why the re-draw waits for the fence's exchange)")
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the fence did not complete")
|
||||
}
|
||||
}
|
||||
|
||||
// The lost acknowledgement, through the executor's registered callbacks:
|
||||
// the replica admits a session (it holds that lineage from then on) and
|
||||
// acts on it, but its reply never reaches the primary, which sees the
|
||||
// exchange fail. The failure is forwarded to the engine's callback, and
|
||||
// the live session is re-drawn above the session all the same: the
|
||||
// healthy verdict that follows is acknowledged and live traffic lands.
|
||||
// Cases: a fence of a caught-up replica, and a catch-up of a behind one
|
||||
// whose close fails.
|
||||
func TestAnAdmittedSessionWhoseReplyIsLostStillMovesTheLiveSession(t *testing.T) {
|
||||
t.Run("fence", func(t *testing.T) {
|
||||
r := newFenceRig(t, 0, true)
|
||||
r.proxy.drop.Store(true)
|
||||
if res := r.fence(t); res.Success {
|
||||
t.Fatal("fixture: the fence succeeded; its reply was to be lost")
|
||||
}
|
||||
r.proxy.drop.Store(false)
|
||||
r.exec.PublishHealthy("r2")
|
||||
if s := r.peer.State(); s != replication.ReplicaHealthy {
|
||||
t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted fence", s)
|
||||
}
|
||||
r.requireLiveTraffic(t)
|
||||
})
|
||||
t.Run("recovery session", func(t *testing.T) {
|
||||
r := newFenceRig(t, 2, true)
|
||||
r.proxy.drop.Store(true)
|
||||
if res := r.catchUp(t); res.Success {
|
||||
t.Fatal("fixture: the catch-up closed successfully; its replies were to be lost")
|
||||
}
|
||||
r.proxy.drop.Store(false)
|
||||
r.exec.PublishHealthy("r2")
|
||||
if s := r.peer.State(); s != replication.ReplicaHealthy {
|
||||
t.Fatalf("peer %s after the healthy verdict; want healthy: the live session must be above the admitted recovery session", s)
|
||||
}
|
||||
r.requireLiveTraffic(t)
|
||||
})
|
||||
}
|
||||
|
||||
// The R < H control: a peer behind the primary is not healed by the
|
||||
// engine's healthy verdict while it lags; a catch-up through the
|
||||
// registered close callback brings it to the primary's end (every block
|
||||
// equal, nothing skipped or rewound), heals it, and live traffic then
|
||||
// lands on the re-drawn live session.
|
||||
func TestABehindPeerHealsOnlyThroughItsRecovery(t *testing.T) {
|
||||
r := newFenceRig(t, 2, false)
|
||||
r.exec.PublishHealthy("r2")
|
||||
if s := r.peer.State(); s == replication.ReplicaHealthy {
|
||||
t.Fatal("a peer two entries behind was healed by the healthy verdict")
|
||||
}
|
||||
if res := r.catchUp(t); !res.Success {
|
||||
t.Fatalf("the catch-up failed: %s", res.FailReason)
|
||||
}
|
||||
if s := r.peer.State(); s != replication.ReplicaHealthy {
|
||||
t.Fatalf("peer %s after a completed catch-up; want healthy", s)
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
want, _ := r.primary.Read(lba)
|
||||
if got, err := r.replica.Read(lba); err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("after the catch-up LBA %d differs from the primary (err %v)", lba, err)
|
||||
}
|
||||
}
|
||||
r.requireLiveTraffic(t)
|
||||
}
|
||||
|
||||
// sessionOrderSites counts every reference to the peer's session order in
|
||||
// the given files (the sessionIDs field, a SessionIDs() call, or a draw
|
||||
// from either), keyed by the enclosing function and, inside a type switch,
|
||||
// its case: "prepareQueuedCommands/FenceAtEpoch".
|
||||
func sessionOrderSites(files []*ast.File) map[string]int {
|
||||
sites := map[string]int{}
|
||||
isRef := func(n ast.Node) bool {
|
||||
switch x := n.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
return x.Sel.Name == "sessionIDs"
|
||||
case *ast.CallExpr:
|
||||
if sel, ok := x.Fun.(*ast.SelectorExpr); ok {
|
||||
return sel.Sel.Name == "SessionIDs"
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, f := range files {
|
||||
for _, decl := range f.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
continue
|
||||
}
|
||||
var walk func(n ast.Node, site string)
|
||||
walk = func(n ast.Node, site string) {
|
||||
ast.Inspect(n, func(m ast.Node) bool {
|
||||
if cc, ok := m.(*ast.CaseClause); ok && m != n {
|
||||
name := site
|
||||
for _, e := range cc.List {
|
||||
if sel, ok := e.(*ast.SelectorExpr); ok {
|
||||
name = fn.Name.Name + "/" + sel.Sel.Name
|
||||
}
|
||||
}
|
||||
for _, st := range cc.Body {
|
||||
walk(st, name)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if isRef(m) {
|
||||
sites[site]++
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
walk(fn.Body, fn.Name.Name)
|
||||
}
|
||||
}
|
||||
return sites
|
||||
}
|
||||
|
||||
// Every reference to the peer's session order in the adapter's production
|
||||
// source is a listed site: the constructor binds the executor's order, and
|
||||
// each command kind that draws a session is listed with what keeps the
|
||||
// live session above it (recovery sessions re-draw at their close and
|
||||
// fences at their completion, on any outcome, covered by the tests above;
|
||||
// a probe does not move the replica's held lineage). A helper that draws,
|
||||
// an alias of the order, or a draw outside these cases fails here until it
|
||||
// is classified.
|
||||
func TestEverySessionDrawIsFollowedByALiveRedraw(t *testing.T) {
|
||||
want := map[string]int{
|
||||
"NewVolumeReplicaAdapter": 3, // binds the executor's order (a.sessionIDs = src.SessionIDs())
|
||||
"prepareQueuedCommands/StartCatchUp": 1, // recovery session: afterSessionClose re-draws
|
||||
"prepareQueuedCommands/StartRebuild": 1, // recovery session: afterSessionClose re-draws
|
||||
"prepareQueuedCommands/StartRecovery": 1, // recovery session: afterSessionClose re-draws
|
||||
"prepareQueuedCommands/FenceAtEpoch": 1, // fence: afterFence re-draws
|
||||
"prepareQueuedCommands/ProbeReplica": 1, // non-moving: the replica validates a probe without taking its lineage
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
pkgs, err := parser.ParseDir(fset, filepath.Join("..", "..", "adapter"), func(fi fs.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var files []*ast.File
|
||||
for _, p := range pkgs {
|
||||
for _, f := range p.Files {
|
||||
files = append(files, f)
|
||||
}
|
||||
}
|
||||
got := sessionOrderSites(files)
|
||||
for site, n := range got {
|
||||
if want[site] != n {
|
||||
t.Errorf("%s references the session order %d time(s), listed %d: classify it (re-draw the live session after it, or declare it non-moving)", site, n, want[site])
|
||||
}
|
||||
}
|
||||
for site := range want {
|
||||
if got[site] == 0 {
|
||||
t.Errorf("listed site %s no longer references the session order; update the list", site)
|
||||
}
|
||||
}
|
||||
|
||||
// Negative controls: a helper that draws, an alias drawn from, and a
|
||||
// draw outside any case are each a site of their own.
|
||||
src := `package adapter
|
||||
func (a *A) helperDraw() uint64 { return a.sessionIDs.Next() }
|
||||
func (a *A) aliasDraw() uint64 { ids := a.sessionIDs; return ids.Next() }
|
||||
func (a *A) prepareQueuedCommands(cmds []any) {
|
||||
_ = a.sessionIDs.Next()
|
||||
for _, c := range cmds {
|
||||
switch c.(type) {
|
||||
case engine.FenceAtEpoch:
|
||||
_ = a.sessionIDs.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "control.go", src, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := sessionOrderSites([]*ast.File{f})
|
||||
if c["helperDraw"] != 1 || c["aliasDraw"] != 1 || c["prepareQueuedCommands"] != 1 || c["prepareQueuedCommands/FenceAtEpoch"] != 1 {
|
||||
t.Fatalf("the census missed or misattributed a control site: %v", c)
|
||||
}
|
||||
}
|
||||
@@ -266,8 +266,8 @@ func (p *ReplicaPeer) RefreshLiveShipSessionAfter(completedSessionID, achievedLS
|
||||
p.executor.InvalidateSession(p.target.ReplicaID, oldSessionID, reason)
|
||||
p.sessionID = newSessionID
|
||||
p.lineage = newLineage
|
||||
log.Printf("replication: peer %s refreshed live session old=%d new=%d after recovery=%d",
|
||||
p.target.ReplicaID, oldSessionID, newSessionID, completedSessionID)
|
||||
log.Printf("replication: peer %s refreshed live session old=%d new=%d after session=%d (%s)",
|
||||
p.target.ReplicaID, oldSessionID, newSessionID, completedSessionID, reason)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -178,12 +178,12 @@ func (r *ReplicaListener) raiseFloor(epoch uint64) error {
|
||||
// then, if the frame's epoch raises the floor, the durable raise before any
|
||||
// effect or ACK (G1). It runs inside the frame's counted section (G2), so a
|
||||
// fence waits for it.
|
||||
func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool {
|
||||
func (r *ReplicaListener) admitMutation(l RecoveryLineage) (bool, string) {
|
||||
r.mu.Lock()
|
||||
prev := r.activeLineage
|
||||
if !r.acceptMutationLineageLocked(l) {
|
||||
if why := r.mutationLineageRefusalLocked(l); why != "" {
|
||||
r.mu.Unlock()
|
||||
return false
|
||||
return false, why
|
||||
}
|
||||
if r.sessionFrames == nil {
|
||||
r.sessionFrames = make(map[uint64]int)
|
||||
@@ -199,14 +199,14 @@ func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool {
|
||||
r.mu.Unlock()
|
||||
r.endSessionFrame(l.SessionID)
|
||||
log.Printf("replica: refuse mutation at epoch %d: %v", l.Epoch, err)
|
||||
return false
|
||||
return false, "epoch floor not durable: " + err.Error()
|
||||
}
|
||||
r.mu.Lock()
|
||||
if prev.SessionID != l.SessionID {
|
||||
r.markSessionRetiringLocked(prev.SessionID)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
return true
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// NewReplicaListenerWithApplyHook creates a listener with the
|
||||
@@ -411,8 +411,11 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
var replyType byte
|
||||
var reply []byte
|
||||
var admittedSession uint64
|
||||
var refusal string // why the last admit refused (logged by its caller)
|
||||
admit := func(l RecoveryLineage) bool {
|
||||
if !r.admitMutation(l) {
|
||||
ok, why := r.admitMutation(l)
|
||||
if !ok {
|
||||
refusal = why
|
||||
return false
|
||||
}
|
||||
admittedSession = l.SessionID
|
||||
@@ -427,8 +430,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
return true
|
||||
}
|
||||
if !admit(lineage) {
|
||||
log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
|
||||
log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d: %s",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal)
|
||||
return true
|
||||
}
|
||||
// The lane ships history whose epochs arrive only at its
|
||||
@@ -469,8 +472,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
return true
|
||||
}
|
||||
if !admit(entry.Lineage) {
|
||||
log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d",
|
||||
entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion)
|
||||
log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d: %s",
|
||||
entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion, refusal)
|
||||
return true
|
||||
}
|
||||
// Live lane: the row first, then the entry, so an entry
|
||||
@@ -587,8 +590,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
return true
|
||||
}
|
||||
if !admit(lineage) {
|
||||
log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
|
||||
log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d: %s",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal)
|
||||
return true
|
||||
}
|
||||
// Rebuild blocks are BASE-lane bytes. They must not enter the
|
||||
@@ -611,8 +614,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
return true
|
||||
}
|
||||
if !admit(lineage) {
|
||||
log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
|
||||
log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d: %s",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal)
|
||||
return true
|
||||
}
|
||||
// Done (DESIGN 8.7): an empty rebuild begins here; the hint must
|
||||
@@ -679,8 +682,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) {
|
||||
return true
|
||||
}
|
||||
if !admit(lineage) {
|
||||
log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion)
|
||||
log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d: %s",
|
||||
lineage.SessionID, lineage.Epoch, lineage.EndpointVersion, refusal)
|
||||
return true
|
||||
}
|
||||
frontier, syncErr := r.store.Sync()
|
||||
@@ -1000,31 +1003,45 @@ func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool {
|
||||
}
|
||||
|
||||
func (r *ReplicaListener) acceptMutationLineageLocked(incoming RecoveryLineage) bool {
|
||||
return r.mutationLineageRefusalLocked(incoming) == ""
|
||||
}
|
||||
|
||||
// mutationLineageRefusalLocked admits incoming (taking it as the active
|
||||
// lineage when newer) and returns "", or returns why it is refused, one
|
||||
// reason per cause, for the caller's log line.
|
||||
func (r *ReplicaListener) mutationLineageRefusalLocked(incoming RecoveryLineage) string {
|
||||
if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 {
|
||||
return false
|
||||
return "incomplete lineage"
|
||||
}
|
||||
// G2: a primary applies no inbound replication, and no host applies
|
||||
// any below the epoch it has taken a role at. G1: a production listener
|
||||
// applies nothing before its role is known.
|
||||
if r.primary || incoming.Epoch < r.epochFloor || (r.requireRole && !r.assigned) {
|
||||
return false
|
||||
switch {
|
||||
case r.primary:
|
||||
return "this listener is a primary"
|
||||
case incoming.Epoch < r.epochFloor:
|
||||
return fmt.Sprintf("epoch below the floor %d", r.epochFloor)
|
||||
case r.requireRole && !r.assigned:
|
||||
return "no role assigned yet"
|
||||
}
|
||||
|
||||
active := r.activeLineage
|
||||
if active.SessionID == 0 {
|
||||
r.activeLineage = incoming
|
||||
return true
|
||||
return ""
|
||||
}
|
||||
|
||||
switch compareLineage(incoming, active) {
|
||||
case 1:
|
||||
r.activeLineage = incoming
|
||||
return true
|
||||
return ""
|
||||
case 0:
|
||||
return incoming.EffectiveFrontierHint() == active.EffectiveFrontierHint()
|
||||
if incoming.EffectiveFrontierHint() == active.EffectiveFrontierHint() {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("same lineage with another frontier hint (%d, held %d)", incoming.EffectiveFrontierHint(), active.EffectiveFrontierHint())
|
||||
default:
|
||||
return false
|
||||
return fmt.Sprintf("below the held lineage session=%d epoch=%d endpointVersion=%d", active.SessionID, active.Epoch, active.EndpointVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Each cause of a refused mutation lineage has its own reason, so a refusal
|
||||
// log line says which one it was: a primary listener, an epoch below the
|
||||
// floor, no role yet, a lineage below the held one, and the same lineage
|
||||
// with another frontier hint. An admitted lineage has none.
|
||||
func TestMutationRefusalNamesItsCause(t *testing.T) {
|
||||
held := RecoveryLineage{SessionID: 5, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
setup func(r *ReplicaListener)
|
||||
incoming RecoveryLineage
|
||||
want string
|
||||
}{
|
||||
{"primary", func(r *ReplicaListener) { r.primary = true }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "is a primary"},
|
||||
{"below the floor", func(r *ReplicaListener) { r.epochFloor = 3 }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "below the floor 3"},
|
||||
{"no role", func(r *ReplicaListener) { r.requireRole, r.assigned = true, false }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, "no role assigned"},
|
||||
{"below the held lineage", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 1, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, "below the held lineage session=5"},
|
||||
{"same lineage, another hint", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 5, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, "another frontier hint"},
|
||||
{"admitted", func(r *ReplicaListener) { r.activeLineage = held }, RecoveryLineage{SessionID: 6, Epoch: 2, EndpointVersion: 1, TargetLSN: 66}, ""},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
l, err := NewReplicaListener("127.0.0.1:0", storage.NewBlockStore(8, 4096))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Stop()
|
||||
l.mu.Lock()
|
||||
c.setup(l)
|
||||
why := l.mutationLineageRefusalLocked(c.incoming)
|
||||
l.mu.Unlock()
|
||||
if c.want == "" {
|
||||
if why != "" {
|
||||
t.Fatalf("refused %q; want admitted", why)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !strings.Contains(why, c.want) {
|
||||
t.Fatalf("reason %q; want it to name %q", why, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user