mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge pull request #593 from seaweedfs/g2/attest-before-count
replication, master, volume: count a peer only with the master-recorded store
This commit is contained in:
commit
e3f0cbd08c
21 files changed
+1488
-673
No files matched your search
@@ -89,6 +89,7 @@ func TestClusterEvidenceService_GRPCRegistered(t *testing.T) {
|
||||
if _, err := h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatalf("product tick: %v", err)
|
||||
}
|
||||
waitAuthorityLine(t, h.Publisher(), "pvc-a") // the bind publishes asynchronously
|
||||
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"sort"
|
||||
@@ -171,6 +172,19 @@ func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, pl
|
||||
Message: fmt.Sprintf("observed %d of %d desired replicas", volume.ObservedReplicas, volume.DesiredReplicas),
|
||||
})
|
||||
}
|
||||
if h.attest != nil {
|
||||
// A condition only: the wait is a normal step of creating a volume,
|
||||
// not a degradation (the primary's own status says it serves nothing).
|
||||
if waiting, initial := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 {
|
||||
volume.Conditions = append(volume.Conditions, ops.ObservationCondition{
|
||||
Type: "ReplicaStoresAttested",
|
||||
Status: "false",
|
||||
Reason: ops.ReasonAwaitingReplicaAttestations,
|
||||
Severity: "info",
|
||||
Message: fmt.Sprintf("creating: waiting for replica attestations (%d of %d)", initial-waiting, initial),
|
||||
})
|
||||
}
|
||||
}
|
||||
if !hasLine || !line.Assigned {
|
||||
if volume.Status == ops.ObservationStatusOK {
|
||||
volume.Status = ops.ObservationStatusDegraded
|
||||
@@ -227,6 +241,9 @@ func (h *Host) observationReplicas(volumeID string, placement lifecycle.Placemen
|
||||
Role: "unknown",
|
||||
ReplicationRole: "unavailable",
|
||||
}
|
||||
if id, ok := h.AttestedStore(volumeID, replicaID); ok {
|
||||
replica.StoreAttested, replica.StoreID = true, hex.EncodeToString(id[:])
|
||||
}
|
||||
if hasLine && line.Assigned && replicaID == line.ReplicaID {
|
||||
replica.Role = "primary"
|
||||
replica.ReplicationRole = "primary"
|
||||
|
||||
@@ -477,11 +477,26 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
|
||||
lastEpoch uint64
|
||||
lastEV uint64
|
||||
sentAny bool
|
||||
lastInfo adapter.AssignmentInfo
|
||||
)
|
||||
// A change of the volume's store record re-sends the current fact: its
|
||||
// descriptors carry the recorded stores (the same generation; the
|
||||
// primary updates its peers' expected stores in place).
|
||||
var storesChanged <-chan struct{}
|
||||
if s.host.attest != nil {
|
||||
storesChanged = s.host.attest.watch(req.VolumeId)
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-storesChanged:
|
||||
storesChanged = s.host.attest.watch(req.VolumeId)
|
||||
if sentAny {
|
||||
if err := stream.Send(s.assignmentFact(lastInfo)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case info, ok := <-merged:
|
||||
if !ok {
|
||||
return nil
|
||||
@@ -515,6 +530,7 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co
|
||||
|
||||
lastEpoch = info.Epoch
|
||||
lastEV = info.EndpointVersion
|
||||
lastInfo = info
|
||||
sentAny = true
|
||||
fact := s.assignmentFact(info)
|
||||
if err := stream.Send(fact); err != nil {
|
||||
@@ -797,7 +813,13 @@ func (s *services) collectPeers(volumeID string, selfInfo adapter.AssignmentInfo
|
||||
if s.host.obs != nil {
|
||||
obsStore = s.host.obs.Store()
|
||||
}
|
||||
return resolvePeers(slots, selfInfo, volumeID, s.host.boot.Publisher, obsStore)
|
||||
peers := resolvePeers(slots, selfInfo, volumeID, s.host.boot.Publisher, obsStore)
|
||||
for _, p := range peers {
|
||||
if id, ok := s.host.AttestedStore(volumeID, p.ReplicaId); ok {
|
||||
p.StoreId = append([]byte(nil), id[:]...)
|
||||
}
|
||||
}
|
||||
return peers
|
||||
}
|
||||
|
||||
// peerLookup is the narrow read interface resolvePeers needs from
|
||||
@@ -1027,6 +1049,10 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme
|
||||
// durable authority facts preserved across master restart.
|
||||
fact.Peers = s.collectPeers(info.VolumeID, info)
|
||||
fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion
|
||||
if s.host.attest != nil {
|
||||
waiting, initial := s.host.attest.awaited(info.VolumeID, s.host.replicaSlotsFor(info.VolumeID))
|
||||
fact.ReplicaStoresAwaited, fact.ReplicaStoresInitial = uint32(waiting), uint32(initial)
|
||||
}
|
||||
return fact
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,12 @@ type attestedStores struct {
|
||||
Primary string `json:"primary"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Stores map[string]string `json:"stores"` // replica id -> store id (hex)
|
||||
// Initial is a new volume's replica set at its first bind; non-empty
|
||||
// while the volume is creating (waiting for its replicas' stores). The
|
||||
// wait itself follows the volume's current replicas (a replica replaced
|
||||
// meanwhile is not waited for); it is cleared, for good, the first time
|
||||
// every current replica has a recorded store.
|
||||
Initial []string `json:"initial,omitempty"`
|
||||
}
|
||||
|
||||
// storeAttestations is the master's record of which store each replica
|
||||
@@ -36,10 +42,12 @@ type storeAttestations struct {
|
||||
mu sync.Mutex
|
||||
path string // "" = memory only
|
||||
vols map[string]attestedStores
|
||||
// changed[vol] is closed (and dropped) when vol's record changes.
|
||||
changed map[string]chan struct{}
|
||||
}
|
||||
|
||||
func loadStoreAttestations(dir string) (*storeAttestations, error) {
|
||||
s := &storeAttestations{vols: map[string]attestedStores{}}
|
||||
s := &storeAttestations{vols: map[string]attestedStores{}, changed: map[string]chan struct{}{}}
|
||||
if dir == "" {
|
||||
return s, nil
|
||||
}
|
||||
@@ -79,6 +87,87 @@ func (s *storeAttestations) lookup(volumeID, replicaID string) (storage.StoreID,
|
||||
return id, !id.IsZero()
|
||||
}
|
||||
|
||||
// watch returns a channel closed at the next change of volumeID's record.
|
||||
func (s *storeAttestations) watch(volumeID string) <-chan struct{} {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
ch, ok := s.changed[volumeID]
|
||||
if !ok {
|
||||
ch = make(chan struct{})
|
||||
s.changed[volumeID] = ch
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
func (s *storeAttestations) notifyLocked(volumeID string) {
|
||||
if ch, ok := s.changed[volumeID]; ok {
|
||||
close(ch)
|
||||
delete(s.changed, volumeID)
|
||||
}
|
||||
}
|
||||
|
||||
// open records a new volume's initial replicas at its first bind, so its
|
||||
// primary serves nothing until each has an attested store. A volume that
|
||||
// already has a record (or an attestation) is left as it is: only a volume
|
||||
// the master binds for the first time waits.
|
||||
func (s *storeAttestations) open(volumeID string, replicas []string) error {
|
||||
if len(replicas) == 0 {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, had := s.vols[volumeID]; had {
|
||||
return nil
|
||||
}
|
||||
vols := make(map[string]attestedStores, len(s.vols)+1)
|
||||
for k, v := range s.vols {
|
||||
vols[k] = v
|
||||
}
|
||||
vols[volumeID] = attestedStores{Stores: map[string]string{}, Initial: append([]string(nil), replicas...)}
|
||||
if err := s.persist(vols); err != nil {
|
||||
return err
|
||||
}
|
||||
s.vols = vols
|
||||
s.notifyLocked(volumeID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// awaited reports, for a volume still creating, how many of its current
|
||||
// replicas have no recorded store yet and how many it has; 0, 0 once the
|
||||
// volume left creating (or never waited). When nothing is awaited any more
|
||||
// the creation wait is cleared durably, so a later replacement of a
|
||||
// replica never closes the volume again.
|
||||
func (s *storeAttestations) awaited(volumeID string, current []string) (waiting, replicas int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
v, had := s.vols[volumeID]
|
||||
if !had || len(v.Initial) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
for _, id := range current {
|
||||
if _, ok := v.Stores[id]; !ok {
|
||||
waiting++
|
||||
}
|
||||
}
|
||||
if waiting > 0 || len(current) == 0 {
|
||||
return waiting, len(current)
|
||||
}
|
||||
vols := make(map[string]attestedStores, len(s.vols))
|
||||
for k, x := range s.vols {
|
||||
vols[k] = x
|
||||
}
|
||||
v.Initial = nil
|
||||
vols[volumeID] = v
|
||||
if err := s.persist(vols); err != nil {
|
||||
// Not cleared: the volume keeps answering from its stores (nothing
|
||||
// awaited); the next call retries the write.
|
||||
return 0, len(current)
|
||||
}
|
||||
s.vols = vols
|
||||
s.notifyLocked(volumeID)
|
||||
return 0, len(current)
|
||||
}
|
||||
|
||||
// record merges att into the volume's record, in one write: each replica it
|
||||
// names gets that store as its reference; a replica it does not name keeps
|
||||
// its last one. An attestation from a lower epoch than the recorded one is
|
||||
@@ -111,6 +200,7 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error {
|
||||
next.Stores[id] = sid
|
||||
}
|
||||
}
|
||||
next.Initial = cur.Initial // cleared only by awaited
|
||||
if had && sameAttestation(cur, next) {
|
||||
return nil
|
||||
}
|
||||
@@ -123,11 +213,12 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error {
|
||||
return err
|
||||
}
|
||||
s.vols = vols
|
||||
s.notifyLocked(att.GetVolumeId())
|
||||
return nil
|
||||
}
|
||||
|
||||
func sameAttestation(a, b attestedStores) bool {
|
||||
if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) {
|
||||
if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) || len(a.Initial) != len(b.Initial) {
|
||||
return false
|
||||
}
|
||||
for k, v := range a.Stores {
|
||||
@@ -196,6 +287,19 @@ func (h *Host) ingestStoreAttestation(server string, att *control.StoreAttestati
|
||||
return h.attest.record(att)
|
||||
}
|
||||
|
||||
// openStoreRecord records the initial replicas of a volume the master binds
|
||||
// for the first time (no authority line yet): its primary serves nothing
|
||||
// until each has an attested store.
|
||||
func (h *Host) openStoreRecord(volumeID string) error {
|
||||
if h == nil || h.attest == nil {
|
||||
return nil
|
||||
}
|
||||
if _, bound := h.Publisher().VolumeAuthorityLine(volumeID); bound {
|
||||
return nil
|
||||
}
|
||||
return h.attest.open(volumeID, h.replicaSlotsFor(volumeID))
|
||||
}
|
||||
|
||||
// AttestedStore is the store the primary of volumeID last attested for
|
||||
// replicaID (see storeAttestations).
|
||||
func (h *Host) AttestedStore(volumeID, replicaID string) (storage.StoreID, bool) {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func factFor(h *Host, line authority.AuthorityBasis) (awaited, initial uint32, stores map[string][]byte) {
|
||||
fact := (&services{host: h}).assignmentFact(adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: line.ReplicaID,
|
||||
Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr})
|
||||
stores = map[string][]byte{}
|
||||
for _, p := range fact.GetPeers() {
|
||||
stores[p.GetReplicaId()] = p.GetStoreId()
|
||||
}
|
||||
return fact.GetReplicaStoresAwaited(), fact.GetReplicaStoresInitial(), stores
|
||||
}
|
||||
|
||||
// A new volume's first assignment waits for its replicas' attested stores:
|
||||
// the fact counts the initial replicas with no recorded store, and its
|
||||
// descriptors carry only stores the primary attested (never a replica's own
|
||||
// word). Each recorded attestation wakes the assignment stream, so the
|
||||
// primary receives the stores at the same generation; once every initial
|
||||
// replica has one, nothing is awaited, for good (a later rebuild does not
|
||||
// close the volume again; its replica just does not count).
|
||||
func TestNewVolumeAssignmentWaitsForReplicaAttestations(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
h, err := New(Config{AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0",
|
||||
ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 3}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() { closeTestMaster(t, h) })
|
||||
line := rf3Primary(t, h)
|
||||
if awaited, initial, stores := factFor(h, line); awaited != 3 || initial != 3 || len(stores["r2"]) != 0 || len(stores["r3"]) != 0 {
|
||||
t.Fatalf("new volume: awaited %d of %d, stores %x; want 3 of 3 and no store in any descriptor", awaited, initial, stores)
|
||||
}
|
||||
s1, s2, t1 := storeID(0x11), storeID(0x22), storeID(0x33)
|
||||
wake := h.attest.watch("vol-rf3")
|
||||
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-wake:
|
||||
default:
|
||||
t.Fatal("a recorded attestation did not wake the assignment stream")
|
||||
}
|
||||
if awaited, _, stores := factFor(h, line); awaited != 1 || !bytes.Equal(stores["r2"], s1[:]) || len(stores["r3"]) != 0 {
|
||||
t.Fatalf("after r1+r2 attested: awaited %d, stores %x; want 1 (r3) and r2=%x", awaited, stores, s1)
|
||||
}
|
||||
if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if awaited, _, stores := factFor(h, line); awaited != 0 || !bytes.Equal(stores["r3"], t1[:]) {
|
||||
t.Fatalf("all attested: awaited %d, stores %x; want 0 and r3=%x", awaited, stores, t1)
|
||||
}
|
||||
// r2 rebuilt (S2): it reconnects with a new store but the record (and the
|
||||
// descriptor) keeps S1 until the primary attests S2; the volume stays open.
|
||||
if _, _, stores := factFor(h, line); !bytes.Equal(stores["r2"], s1[:]) {
|
||||
t.Fatalf("r2 descriptor %x; want the attested %x", stores["r2"], s1)
|
||||
}
|
||||
if err := h.ingestStoreAttestation("node-b", attestation("vol-rf3", "r2", line.Epoch, map[string]storage.StoreID{"r2": s2})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if awaited, _, stores := factFor(h, line); awaited != 0 || !bytes.Equal(stores["r2"], s1[:]) {
|
||||
t.Fatalf("after r2's own claim: awaited %d, r2 %x; want 0 and %x", awaited, stores["r2"], s1)
|
||||
}
|
||||
reloaded, err := loadStoreAttestations(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waiting, initial := reloaded.awaited("vol-rf3", []string{"r1", "r2", "r3"}); waiting != 0 || initial != 0 {
|
||||
t.Fatalf("reloaded: %d of %d awaited; want the wait cleared", waiting, initial)
|
||||
}
|
||||
}
|
||||
|
||||
// A volume bound before the record existed (an upgrade) waits for nothing:
|
||||
// its frontend stays served; it is only not promoted until attested.
|
||||
func TestUpgradedVolumeAwaitsNoAttestation(t *testing.T) {
|
||||
s, err := loadStoreAttestations(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waiting, initial := s.awaited("v-old", []string{"r1", "r2"}); waiting != 0 || initial != 0 {
|
||||
t.Fatalf("no record: %d of %d", waiting, initial)
|
||||
}
|
||||
if err := s.open("v-new", []string{"r1", "r2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.open("v-new", []string{"r1", "r2", "r3"}); err != nil { // a second open changes nothing
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waiting, initial := s.awaited("v-new", []string{"r1", "r2"}); waiting != 2 || initial != 2 {
|
||||
t.Fatalf("new: %d of %d awaited; want 2 of 2", waiting, initial)
|
||||
}
|
||||
if err := s.record(attestation("v-old", "r1", 3, map[string]storage.StoreID{"r2": storeID(2)})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.open("v-old", []string{"r1", "r2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waiting, _ := s.awaited("v-old", []string{"r1", "r2"}); waiting != 0 {
|
||||
t.Fatalf("an attested volume opened again waits for %d", waiting)
|
||||
}
|
||||
}
|
||||
|
||||
// An initial replica replaced during the creation wait (a new replica id in
|
||||
// the placement) must not keep the volume waiting for the old id, which
|
||||
// never attests: the wait follows the volume's current replicas.
|
||||
func TestCreationWaitFollowsAReplacedInitialReplica(t *testing.T) {
|
||||
s, err := loadStoreAttestations(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.open("v", []string{"r1", "r2", "r3"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// r3 is replaced by r4 before it attests; the primary attests r1, r2, r4.
|
||||
if err := s.record(attestation("v", "r1", 1, map[string]storage.StoreID{"r1": storeID(1), "r2": storeID(2), "r4": storeID(4)})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if waiting, initial := s.awaited("v", []string{"r1", "r2", "r4"}); waiting != 0 {
|
||||
t.Fatalf("after r3 was replaced by r4 and r1, r2, r4 attested: %d of %d awaited; want 0", waiting, initial)
|
||||
}
|
||||
// The wait is over for good: a later replacement (r5, no store yet) does
|
||||
// not close the volume again; its replica just does not count.
|
||||
if waiting, _ := s.awaited("v", []string{"r1", "r2", "r5"}); waiting != 0 {
|
||||
t.Fatalf("a replacement after the wait ended re-opened it: %d awaited", waiting)
|
||||
}
|
||||
// Before r4 attests, the wait names r4, not r3.
|
||||
s2, _ := loadStoreAttestations(t.TempDir())
|
||||
_ = s2.open("v", []string{"r1", "r2", "r3"})
|
||||
_ = s2.record(attestation("v", "r1", 1, map[string]storage.StoreID{"r1": storeID(1), "r2": storeID(2)}))
|
||||
if waiting, initial := s2.awaited("v", []string{"r1", "r2", "r4"}); waiting != 1 || initial != 3 {
|
||||
t.Fatalf("r4 not yet attested: %d of %d; want 1 of 3", waiting, initial)
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,11 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
|
||||
// admitWorkspacePublication owns the last local boundary before an ordinary
|
||||
// Publisher mint. Guarded Move already owns workspaceMu in its RPC path.
|
||||
func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish func() error) error {
|
||||
// A volume's first bind records its initial replicas before the line
|
||||
// exists, so its primary is never served without the wait.
|
||||
if err := h.openStoreRecord(ask.VolumeID); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.lifecycle == nil {
|
||||
return publish()
|
||||
}
|
||||
|
||||
@@ -161,6 +161,9 @@ type Host struct {
|
||||
// even on a host that was healthy at its prior epoch; only a later
|
||||
// successful role call for the current role and epoch clears it.
|
||||
roleAdmissionFailed atomic.Value // string reason; "" = not failed
|
||||
// storesAwaited: the primary fact's (awaited<<32 | initial) replica
|
||||
// store count (ReplicaStoresAwaited).
|
||||
storesAwaited atomic.Uint64
|
||||
// RF1Only admission state, one unit under rf1Mu (field access only, no
|
||||
// calls): the highest refused epoch with its reason ("" = cleared), and the
|
||||
// highest epoch an RF1 fact was admitted at. A clear removes only the
|
||||
@@ -384,6 +387,11 @@ func (h *Host) SetReplicationVolume(rv *replication.ReplicationVolume) {
|
||||
// goroutine has visibility yet).
|
||||
func (h *Host) setReplicationLocked(rv replicaSetUpdater) {
|
||||
h.replication = rv
|
||||
// This host attests its peers' stores to the master: a peer counts only
|
||||
// while its store is the one the master recorded.
|
||||
if c, ok := rv.(storeRequirer); ok && c != nil {
|
||||
c.RequireAttestedStores()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Host) storeLocalReadinessReplayFact(fact *control.AssignmentFact) {
|
||||
@@ -692,6 +700,13 @@ type storeAttester interface {
|
||||
AttestedStores() map[string]storage.StoreID
|
||||
}
|
||||
|
||||
// storeRequirer is the replication slot's switch that makes peers count
|
||||
// only with the store the master recorded (replication.ReplicationVolume).
|
||||
type storeRequirer interface {
|
||||
RequireAttestedStores()
|
||||
}
|
||||
|
||||
|
||||
// storeAttestation is this node's attestation of its write-ACK set while it
|
||||
// holds the primary role (admitted, at its current epoch): its own store and
|
||||
// every Healthy peer's last barrier store. nil on a replica, before the
|
||||
@@ -926,6 +941,7 @@ func (h *Host) applyFact(fact *control.AssignmentFact) {
|
||||
}
|
||||
|
||||
h.recordSelfAssignment(fact)
|
||||
h.noteReplicaStores(fact)
|
||||
h.reportAssignmentEndpoints(fact)
|
||||
|
||||
// The recovery watchdog runs from the primary assignment, before any
|
||||
|
||||
@@ -107,7 +107,7 @@ func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection,
|
||||
p := v.projector.Projection()
|
||||
healthy := p.Mode == engine.ModeHealthy
|
||||
superseded := healthy && v.isSupersededLine(p.Epoch, p.EndpointVersion)
|
||||
if superseded || (healthy && v.supportingReplicaReady(p.Epoch, p.EndpointVersion)) || v.roleAdmissionFailed() {
|
||||
if superseded || (healthy && v.supportingReplicaReady(p.Epoch, p.EndpointVersion)) || v.roleAdmissionFailed() || v.replicaStoresAwaited() != "" {
|
||||
healthy = false
|
||||
}
|
||||
result := frontend.Projection{
|
||||
@@ -153,6 +153,20 @@ func (v *AdapterProjectionView) supportingReplicaReady(selfEpoch, selfEV uint64)
|
||||
other.GetEndpointVersion() == selfEV
|
||||
}
|
||||
|
||||
// replicaStoresAwaited: a new volume's primary serves nothing until the
|
||||
// master has recorded every initial replica's attested store (until then no
|
||||
// peer's ack can count); "" when nothing is awaited.
|
||||
func (v *AdapterProjectionView) replicaStoresAwaited() string {
|
||||
if v == nil || v.probe == nil {
|
||||
return ""
|
||||
}
|
||||
probe, ok := v.probe.(interface{ ReplicaStoresAwaited() string })
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return probe.ReplicaStoresAwaited()
|
||||
}
|
||||
|
||||
// roleAdmissionFailed is the G1 admission latch from the volume host: a role
|
||||
// call on its replica listener failed (floor not durable, or fence not
|
||||
// drained). Healthy is false until a later role call succeeds, even when the
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/memorywal"
|
||||
)
|
||||
|
||||
// A new volume is not exposed before its replicas' stores are attested:
|
||||
// while the master's fact awaits any initial replica's store, the primary's
|
||||
// projection is not Healthy, writes through the real backend refuse, and
|
||||
// status says "creating: waiting for replica attestations (n of N)". The
|
||||
// same-generation re-send with nothing awaited opens it.
|
||||
// requiringReplication is a replication slot that counts peers only with
|
||||
// recorded stores (as replication.ReplicationVolume does on a volume host).
|
||||
type requiringReplication struct{ *stubReplication }
|
||||
|
||||
func (requiringReplication) RequireAttestedStores() {}
|
||||
|
||||
func TestNewVolumePrimaryServesNothingBeforeReplicaAttestations(t *testing.T) {
|
||||
h, _, rep := newStubbedHost(t, "vol1", "rB", &orderingRecorder{})
|
||||
h.replicationMu.Lock()
|
||||
h.setReplicationLocked(requiringReplication{rep})
|
||||
h.replicationMu.Unlock()
|
||||
proj := &mutableProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 2, EndpointVersion: 1}}
|
||||
h.view = NewAdapterProjectionView(proj, "vol1", "rB", h)
|
||||
if err := h.SetSelfFence(&switchFencer{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := memorywal.NewStore(8, 4096)
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
backend := durable.NewStorageBackend(store, h.view, frontend.Identity{VolumeID: "vol1", ReplicaID: "rB", Epoch: 2, EndpointVersion: 1})
|
||||
backend.SetOperational(true, "replica stores wait")
|
||||
ctx := context.Background()
|
||||
|
||||
fact := selfFact(2)
|
||||
fact.ReplicaStoresAwaited, fact.ReplicaStoresInitial = 2, 3
|
||||
h.applyFixtureFact(fact)
|
||||
if h.view.Projection().Healthy {
|
||||
t.Fatal("a new volume's primary is Healthy before its replicas' stores are recorded")
|
||||
}
|
||||
if _, err := backend.Write(ctx, 0, []byte("early")); err == nil {
|
||||
t.Fatal("a write was served before the replicas' stores were recorded")
|
||||
}
|
||||
s := NewStatusServer(h.view).statusProjection()
|
||||
if s.FrontendPrimaryReady || !strings.Contains(s.NotReadyReason, "creating: waiting for replica attestations (1 of 3)") {
|
||||
t.Fatalf("status: ready=%t reason=%q", s.FrontendPrimaryReady, s.NotReadyReason)
|
||||
}
|
||||
|
||||
fact = selfFact(2) // the master's re-send once every store is recorded
|
||||
h.applyFixtureFact(fact)
|
||||
if !h.view.Projection().Healthy {
|
||||
t.Fatal("not Healthy once nothing is awaited")
|
||||
}
|
||||
if _, err := backend.Write(ctx, 0, []byte("open")); err != nil {
|
||||
t.Fatalf("write once nothing is awaited: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A host whose replication slot does not require recorded stores counts no
|
||||
// peer ack by store, so the wait does not apply to it: the fact's count
|
||||
// does not close its frontend.
|
||||
func TestReplicaStoresWaitOnlyWhereStoresAreRequired(t *testing.T) {
|
||||
h, _, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{})
|
||||
fact := selfFact(2)
|
||||
fact.ReplicaStoresAwaited, fact.ReplicaStoresInitial = 2, 2
|
||||
h.noteReplicaStores(fact)
|
||||
if reason := h.ReplicaStoresAwaited(); reason != "" {
|
||||
t.Fatalf("a host without a store-requiring slot waits: %q", reason)
|
||||
}
|
||||
}
|
||||
@@ -569,6 +569,8 @@ func (s *StatusServer) statusProjection() StatusProjection {
|
||||
}
|
||||
case backendReason != "":
|
||||
p.NotReadyReason = backendReason
|
||||
case s.view.replicaStoresAwaited() != "":
|
||||
p.NotReadyReason = s.view.replicaStoresAwaited()
|
||||
case nvmePending:
|
||||
p.NotReadyReason = "frontend target not listening yet"
|
||||
case !authorityReady:
|
||||
|
||||
@@ -26,6 +26,7 @@ package volume
|
||||
import (
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
@@ -108,6 +109,7 @@ func decodeReplicaTargets(f *control.AssignmentFact) ([]replication.ReplicaTarge
|
||||
ControlAddr: p.CtrlAddr,
|
||||
Epoch: p.Epoch,
|
||||
EndpointVersion: p.EndpointVersion,
|
||||
StoreID: storage.StoreIDFromBytes(p.StoreId),
|
||||
})
|
||||
}
|
||||
return out, f.PeerSetGeneration
|
||||
|
||||
@@ -1,6 +1,32 @@
|
||||
package volume
|
||||
|
||||
import control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
// noteReplicaStores keeps the primary fact's count of a new volume's initial
|
||||
// replicas whose store the master has not recorded yet.
|
||||
func (h *Host) noteReplicaStores(f *control.AssignmentFact) {
|
||||
h.storesAwaited.Store(uint64(f.GetReplicaStoresAwaited())<<32 | uint64(f.GetReplicaStoresInitial()))
|
||||
}
|
||||
|
||||
// ReplicaStoresAwaited is the reason a new volume's primary serves nothing
|
||||
// yet: "" once every initial replica's store is recorded (or the volume
|
||||
// never waited). It applies where the replication slot counts peers only
|
||||
// with recorded stores; a host without one counts no peer ack at all.
|
||||
func (h *Host) ReplicaStoresAwaited() string {
|
||||
if _, ok := h.getReplication().(storeRequirer); !ok {
|
||||
return ""
|
||||
}
|
||||
v := h.storesAwaited.Load()
|
||||
waiting, initial := v>>32, v&0xffffffff
|
||||
if waiting == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("creating: waiting for replica attestations (%d of %d)", initial-waiting, initial)
|
||||
}
|
||||
|
||||
// INV-WS-STARTUP-RETRY-001: remember the newest assignment observed for us,
|
||||
// including one whose local readiness admission subsequently refuses.
|
||||
|
||||
@@ -27,21 +27,24 @@ const (
|
||||
// The highest end of a fencing round is held only by a replica that is
|
||||
// not ready for primary: the volume waits for it (or for a ready one to
|
||||
// catch up from it).
|
||||
ReasonHighestEndNotReady = "highest_end_not_ready"
|
||||
ReasonDurableFrontierMissing = "durable_frontier_missing"
|
||||
ReasonCandidateFrontierBehind = "candidate_frontier_behind"
|
||||
ReasonStatusEndpointUnreachable = "status_endpoint_unreachable"
|
||||
ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed"
|
||||
ReasonCSIDriverNotRegistered = "csi_driver_not_registered"
|
||||
ReasonCSINodePodNotReady = "csi_node_pod_not_ready"
|
||||
ReasonImageMissingOnNode = "image_missing_on_node"
|
||||
ReasonISCSIPrereqMissing = "iscsi_prereq_missing"
|
||||
ReasonMultipathPrereqMissing = "multipath_prereq_missing"
|
||||
ReasonNodeReady = "node_ready"
|
||||
ReasonNodeNotReady = "node_not_ready"
|
||||
ReasonNodeSchedulingDisabled = "node_scheduling_disabled"
|
||||
ReasonGeneratedDeploymentMissing = "generated_deployment_missing"
|
||||
ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired"
|
||||
ReasonHighestEndNotReady = "highest_end_not_ready"
|
||||
ReasonDurableFrontierMissing = "durable_frontier_missing"
|
||||
ReasonCandidateFrontierBehind = "candidate_frontier_behind"
|
||||
ReasonStatusEndpointUnreachable = "status_endpoint_unreachable"
|
||||
ReasonCSINodeImagePullFailed = "csi_node_image_pull_failed"
|
||||
ReasonCSIDriverNotRegistered = "csi_driver_not_registered"
|
||||
ReasonCSINodePodNotReady = "csi_node_pod_not_ready"
|
||||
ReasonImageMissingOnNode = "image_missing_on_node"
|
||||
ReasonISCSIPrereqMissing = "iscsi_prereq_missing"
|
||||
ReasonMultipathPrereqMissing = "multipath_prereq_missing"
|
||||
ReasonNodeReady = "node_ready"
|
||||
ReasonNodeNotReady = "node_not_ready"
|
||||
ReasonNodeSchedulingDisabled = "node_scheduling_disabled"
|
||||
ReasonGeneratedDeploymentMissing = "generated_deployment_missing"
|
||||
ReasonObservedReplicasBelowDesired = "observed_replicas_below_desired"
|
||||
// A new volume serves nothing until the primary attested every initial
|
||||
// replica's store (creating: waiting for replica attestations).
|
||||
ReasonAwaitingReplicaAttestations = "awaiting_replica_attestations"
|
||||
ReasonLoopbackFrontendRejected = "loopback_frontend_rejected"
|
||||
ReasonStalePrimaryFenced = "stale_primary_fenced"
|
||||
ReasonWALIntegrityFault = "wal_integrity_fault"
|
||||
@@ -154,33 +157,37 @@ type VolumeEvidence struct {
|
||||
}
|
||||
|
||||
type ReplicaEvidence struct {
|
||||
ReplicaID string `json:"replica_id"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
KubernetesNode string `json:"kubernetes_node,omitempty"`
|
||||
PhysicalHost string `json:"physical_host,omitempty"`
|
||||
Observed bool `json:"observed"`
|
||||
Role string `json:"role,omitempty"`
|
||||
ReplicationRole string `json:"replication_role,omitempty"`
|
||||
DurableLatched bool `json:"durable_latched"`
|
||||
DurableFrontierKnown bool `json:"durable_frontier_known"`
|
||||
DurableFrontierLSN uint64 `json:"durable_frontier_lsn,omitempty"`
|
||||
CandidateReady bool `json:"candidate_ready"`
|
||||
CandidateReadyReason string `json:"candidate_ready_reason,omitempty"`
|
||||
Healthy bool `json:"healthy,omitempty"`
|
||||
FrontendPrimaryReady bool `json:"frontend_primary_ready,omitempty"`
|
||||
AckEligibilityKnown bool `json:"ack_eligibility_known,omitempty"`
|
||||
AckEligible bool `json:"ack_eligible,omitempty"`
|
||||
FrontendProtocol string `json:"frontend_protocol,omitempty"`
|
||||
FrontendTransport string `json:"frontend_transport,omitempty"`
|
||||
FrontendAddr string `json:"frontend_addr,omitempty"`
|
||||
FrontendNQN string `json:"frontend_nqn,omitempty"`
|
||||
FrontendNSID uint32 `json:"frontend_nsid,omitempty"`
|
||||
StatusAddr string `json:"status_addr,omitempty"`
|
||||
DataAddr string `json:"data_addr,omitempty"`
|
||||
CtrlAddr string `json:"ctrl_addr,omitempty"`
|
||||
StalePrimaryFenced bool `json:"stale_primary_fenced"`
|
||||
Conditions []ObservationCondition `json:"conditions,omitempty"`
|
||||
SupportBundlePath string `json:"support_bundle_path,omitempty"`
|
||||
ReplicaID string `json:"replica_id"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
KubernetesNode string `json:"kubernetes_node,omitempty"`
|
||||
PhysicalHost string `json:"physical_host,omitempty"`
|
||||
Observed bool `json:"observed"`
|
||||
Role string `json:"role,omitempty"`
|
||||
ReplicationRole string `json:"replication_role,omitempty"`
|
||||
DurableLatched bool `json:"durable_latched"`
|
||||
DurableFrontierKnown bool `json:"durable_frontier_known"`
|
||||
DurableFrontierLSN uint64 `json:"durable_frontier_lsn,omitempty"`
|
||||
CandidateReady bool `json:"candidate_ready"`
|
||||
CandidateReadyReason string `json:"candidate_ready_reason,omitempty"`
|
||||
Healthy bool `json:"healthy,omitempty"`
|
||||
FrontendPrimaryReady bool `json:"frontend_primary_ready,omitempty"`
|
||||
AckEligibilityKnown bool `json:"ack_eligibility_known,omitempty"`
|
||||
AckEligible bool `json:"ack_eligible,omitempty"`
|
||||
FrontendProtocol string `json:"frontend_protocol,omitempty"`
|
||||
FrontendTransport string `json:"frontend_transport,omitempty"`
|
||||
FrontendAddr string `json:"frontend_addr,omitempty"`
|
||||
FrontendNQN string `json:"frontend_nqn,omitempty"`
|
||||
FrontendNSID uint32 `json:"frontend_nsid,omitempty"`
|
||||
StatusAddr string `json:"status_addr,omitempty"`
|
||||
DataAddr string `json:"data_addr,omitempty"`
|
||||
CtrlAddr string `json:"ctrl_addr,omitempty"`
|
||||
StalePrimaryFenced bool `json:"stale_primary_fenced"`
|
||||
// StoreAttested: a primary attested this replica's store (store_id, hex).
|
||||
// A replica without one is never promoted automatically.
|
||||
StoreAttested bool `json:"store_attested"`
|
||||
StoreID string `json:"store_id,omitempty"`
|
||||
Conditions []ObservationCondition `json:"conditions,omitempty"`
|
||||
SupportBundlePath string `json:"support_bundle_path,omitempty"`
|
||||
}
|
||||
|
||||
type ClusterEvent struct {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package component
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func attestSync(t *testing.T, c *Cluster, lba uint32, fill byte) error {
|
||||
t.Helper()
|
||||
c.PrimaryWriteViaBackend(lba, bytes.Repeat([]byte{fill}, 4096))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
return c.Primary().Backend.Sync(ctx)
|
||||
}
|
||||
|
||||
// recordStores re-sends the primary's replica set at the same generation,
|
||||
// with the stores the master recorded (a missing entry: none recorded).
|
||||
func recordStores(t *testing.T, c *Cluster, stores map[string]storage.StoreID) {
|
||||
t.Helper()
|
||||
targets := make([]replication.ReplicaTarget, 0, c.ReplicaCount())
|
||||
for i := 0; i < c.ReplicaCount(); i++ {
|
||||
id := fmt.Sprintf("replica-%d", i)
|
||||
targets = append(targets, replication.ReplicaTarget{ReplicaID: id, DataAddr: c.Replica(i).Addr, ControlAddr: c.Replica(i).Addr,
|
||||
Epoch: 1, EndpointVersion: 1, StoreID: stores[id]})
|
||||
}
|
||||
if err := c.Primary().RepVol.UpdateReplicaSet(1, targets); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A replica whose store the master has not recorded (a rebuilt one)
|
||||
// answers, but its ack never completes a sync_quorum write: with the
|
||||
// recorded replica down, the flush fails; once the master's descriptor
|
||||
// names the replica's store, the same flush succeeds.
|
||||
func TestUnrecordedReplicaAckDoesNotCompleteAQuorumWrite(t *testing.T) {
|
||||
c := NewCluster(t, Walstore).WithReplicas(2).WithLiveShip().Start()
|
||||
rv := c.Primary().RepVol
|
||||
// fixture: a sync_all flush before stores are required, so both
|
||||
// replicas' barriers report their stores
|
||||
rv.SetDurabilityMode(replication.DurabilitySyncAll)
|
||||
if err := attestSync(t, c, 1, 0x11); err != nil {
|
||||
t.Fatalf("fixture: first flush: %v", err)
|
||||
}
|
||||
stores := rv.AttestedStores()
|
||||
if len(stores) != 2 {
|
||||
t.Fatalf("fixture: attested %v, want both replicas", stores)
|
||||
}
|
||||
rv.SetDurabilityMode(replication.DurabilitySyncQuorum)
|
||||
rv.RequireAttestedStores()
|
||||
recordStores(t, c, map[string]storage.StoreID{"replica-0": stores["replica-0"]}) // replica-1: not recorded
|
||||
c.Replica(0).Listener.StopHard() // the recorded replica is gone
|
||||
if err := attestSync(t, c, 2, 0x22); err == nil {
|
||||
t.Fatal("a quorum flush completed on the ack of a replica whose store the master never recorded")
|
||||
}
|
||||
recordStores(t, c, stores)
|
||||
if err := attestSync(t, c, 3, 0x33); err != nil {
|
||||
t.Fatalf("the flush after replica-1's store was recorded: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// CONVERGENCE, with no operator: a replica whose store the master does not
|
||||
// have (an upgraded volume: nothing recorded; a rebuilt replica: its old
|
||||
// store recorded) fails sync_all flushes, but the failure leaves it Healthy
|
||||
// with its barrier-learned store, so the primary's next attestation names
|
||||
// that store. The master records it and re-sends the descriptors; the next
|
||||
// flush counts it. The window is one attestation round (a heartbeat plus the
|
||||
// re-send); the rule is not relaxed during it.
|
||||
func TestUnrecordedReplicaConvergesThroughItsAttestation(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
recorded func(real storage.StoreID) map[string]storage.StoreID
|
||||
}{
|
||||
{"upgraded volume (no record)", func(storage.StoreID) map[string]storage.StoreID { return nil }},
|
||||
{"rebuilt replica (old store recorded)", func(storage.StoreID) map[string]storage.StoreID {
|
||||
return map[string]storage.StoreID{"replica-0": {9, 9}}
|
||||
}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
cl := NewCluster(t, Walstore).WithReplicas(1).WithLiveShip().Start()
|
||||
rv := cl.Primary().RepVol
|
||||
rv.SetDurabilityMode(replication.DurabilitySyncAll)
|
||||
real := storage.StoreIDOf(cl.Replica(0).Store)
|
||||
rv.RequireAttestedStores()
|
||||
recordStores(t, cl, c.recorded(real))
|
||||
if err := attestSync(t, cl, 1, 0x11); err == nil {
|
||||
t.Fatal("a sync_all flush counted a replica whose store the master does not have")
|
||||
}
|
||||
// What the primary attests in its next heartbeat:
|
||||
att := rv.AttestedStores()
|
||||
if att["replica-0"] != real {
|
||||
t.Fatalf("after the refused flush the primary attests %x, want the replica's store %x (an invalidated peer would never be attested)", att["replica-0"], real)
|
||||
}
|
||||
recordStores(t, cl, att) // the master records the attestation and re-sends
|
||||
if err := attestSync(t, cl, 2, 0x22); err != nil {
|
||||
t.Fatalf("the flush after the attestation was recorded: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@ type ReplicaTarget struct {
|
||||
ControlAddr string
|
||||
Epoch uint64
|
||||
EndpointVersion uint64
|
||||
// StoreID is the replica's store the master recorded. Where stores are
|
||||
// required, the peer counts toward write ACKs only while its barrier
|
||||
// reports this store; zero never matches.
|
||||
StoreID storage.StoreID
|
||||
}
|
||||
|
||||
// ReplicaState is the coarse peer health state. The state machine
|
||||
@@ -166,6 +170,11 @@ type ReplicaPeer struct {
|
||||
// cleared whenever the peer leaves Healthy: a store is attested only
|
||||
// by a barrier it answered while counting toward write ACKs.
|
||||
storeID storage.StoreID
|
||||
// requireAttest: the peer counts toward write ACKs only while its
|
||||
// barrier-reported store equals expected, the store the master recorded
|
||||
// for it (set by the volume when a host attests).
|
||||
requireAttest bool
|
||||
expected storage.StoreID
|
||||
// onHealthy lets the owning ReplicationVolume reopen a terminal work
|
||||
// queue only after recovery has returned this peer to Healthy.
|
||||
onHealthy func()
|
||||
@@ -239,6 +248,7 @@ func NewReplicaPeer(target ReplicaTarget, executor *transport.BlockExecutor) (*R
|
||||
lineage: lineage,
|
||||
state: ReplicaHealthy,
|
||||
cooldownCfg: DefaultPeerProbeCooldown(),
|
||||
expected: target.StoreID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -795,6 +805,35 @@ func (p *ReplicaPeer) AttestedStore() (storage.StoreID, bool) {
|
||||
return p.storeID, true
|
||||
}
|
||||
|
||||
// countsTowardAcks reports whether a write or barrier this peer answers
|
||||
// counts toward the volume's write ACKs: it is Healthy and, where stores
|
||||
// are required, its barrier-reported store is the one the master recorded
|
||||
// for it. A peer rebuilt onto a new store answers barriers (that is how its
|
||||
// store is learned) but does not count until the master records that store:
|
||||
// otherwise it could hold the only copy of an acknowledged write that no
|
||||
// promotion could verify.
|
||||
func (p *ReplicaPeer) countsTowardAcks() bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed || p.state != ReplicaHealthy {
|
||||
return false
|
||||
}
|
||||
return !p.requireAttest || (!p.storeID.IsZero() && p.expected == p.storeID)
|
||||
}
|
||||
|
||||
func (p *ReplicaPeer) setRequireAttest() {
|
||||
p.mu.Lock()
|
||||
p.requireAttest = true
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// setExpectedStore replaces the store the master recorded for this peer.
|
||||
func (p *ReplicaPeer) setExpectedStore(id storage.StoreID) {
|
||||
p.mu.Lock()
|
||||
p.expected = id
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
func (p *ReplicaPeer) setOnHealthy(fn func()) {
|
||||
p.mu.Lock()
|
||||
p.onHealthy = fn
|
||||
|
||||
@@ -62,3 +62,101 @@ func TestPeerAttestsTheStoreItsBarrierReported(t *testing.T) {
|
||||
t.Fatalf("after the next barrier: %x %t, want %x", got, ok, want)
|
||||
}
|
||||
}
|
||||
|
||||
func storeListener(t *testing.T, name string) (*storage.WALStore, *transport.ReplicaListener) {
|
||||
t.Helper()
|
||||
s, err := storage.CreateWALStore(filepath.Join(t.TempDir(), name), 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
l, err := transport.NewReplicaListener("127.0.0.1:0", s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Serve()
|
||||
t.Cleanup(func() { l.Stop() })
|
||||
return s, l
|
||||
}
|
||||
|
||||
// COUNT RULE: where stores are required, a Healthy peer counts toward write
|
||||
// ACKs only while its barrier reports the store the master's descriptor
|
||||
// names. An empty descriptor store never matches.
|
||||
func TestPeerCountsOnlyWithTheStoreTheMasterRecorded(t *testing.T) {
|
||||
s1, l := storeListener(t, "s1.wal")
|
||||
v := NewReplicationVolume("v", storage.NewBlockStore(64, 4096))
|
||||
t.Cleanup(func() { _ = v.Close() })
|
||||
target := ReplicaTarget{ReplicaID: "r2", DataAddr: l.Addr(), ControlAddr: l.Addr(), Epoch: 1, EndpointVersion: 1}
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peer := v.peers["r2"]
|
||||
if !peer.countsTowardAcks() {
|
||||
t.Fatal("without required stores a Healthy peer must count, as before")
|
||||
}
|
||||
v.RequireAttestedStores()
|
||||
if _, err := peer.Barrier(context.Background(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peer.countsTowardAcks() {
|
||||
t.Fatal("counted with no store recorded by the master (empty must never match)")
|
||||
}
|
||||
target.StoreID = storage.StoreID{9}
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peer.countsTowardAcks() {
|
||||
t.Fatal("counted while the descriptor names another store")
|
||||
}
|
||||
target.StoreID = s1.StoreID()
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil { // same generation: applied in place
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v.peers["r2"] != peer {
|
||||
t.Fatal("a store-only change recreated the peer")
|
||||
}
|
||||
if !peer.countsTowardAcks() {
|
||||
t.Fatal("does not count with the store the master recorded")
|
||||
}
|
||||
}
|
||||
|
||||
// GUARD: a wiped replica reconnects at the same generation with a new
|
||||
// store. Its barrier answers (that is how the store is learned), but the
|
||||
// peer's own word never changes the expected store: its acks do not count
|
||||
// until the master's descriptor names the new store.
|
||||
func TestWipedReplicaAtTheSameGenerationDoesNotCount(t *testing.T) {
|
||||
s1, _ := storeListener(t, "s1.wal")
|
||||
s2, wiped := storeListener(t, "s2.wal") // the same replica after its disk was wiped
|
||||
v := NewReplicationVolume("v", storage.NewBlockStore(64, 4096))
|
||||
t.Cleanup(func() { _ = v.Close() })
|
||||
v.RequireAttestedStores()
|
||||
target := ReplicaTarget{ReplicaID: "r2", DataAddr: wiped.Addr(), ControlAddr: wiped.Addr(), Epoch: 1, EndpointVersion: 1, StoreID: s1.StoreID()}
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peer := v.peers["r2"]
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := peer.Barrier(context.Background(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := peer.AttestedStore(); got != s2.StoreID() {
|
||||
t.Fatalf("barrier taught %x, want the wiped replica's new store %x", got, s2.StoreID())
|
||||
}
|
||||
if peer.countsTowardAcks() {
|
||||
t.Fatal("a wiped replica's ack counts at the same generation, on its own word")
|
||||
}
|
||||
}
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil { // a replay naming the old store
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peer.countsTowardAcks() {
|
||||
t.Fatal("a replay of the old descriptor made the wiped replica count")
|
||||
}
|
||||
target.StoreID = s2.StoreID()
|
||||
if err := v.UpdateReplicaSet(1, []ReplicaTarget{target}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !peer.countsTowardAcks() {
|
||||
t.Fatal("does not count once the master recorded the new store")
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ type peerWorkQueue struct {
|
||||
func newPeerWorkQueue(peer *ReplicaPeer, depth int) *peerWorkQueue {
|
||||
return newPeerWorkQueueWithOps(peer.Target().ReplicaID, depth, peerWorkQueueOps{
|
||||
ship: func(ctx context.Context, write LocalWrite) (bool, error) {
|
||||
eligible := peer.State() == ReplicaHealthy
|
||||
eligible := peer.countsTowardAcks()
|
||||
err := peer.ShipEntry(ctx, transport.RecoveryLineage{}, write.LBA, write.LSN, write.Data)
|
||||
return eligible, err
|
||||
},
|
||||
@@ -84,6 +84,11 @@ func newPeerWorkQueue(peer *ReplicaPeer, depth int) *peerWorkQueue {
|
||||
peer.Invalidate(err.Error())
|
||||
return ack.AchievedLSN, err
|
||||
}
|
||||
// The barrier taught the peer's store; it counts only while that
|
||||
// is the store the master recorded for it.
|
||||
if !peer.countsTowardAcks() {
|
||||
return ack.AchievedLSN, fmt.Errorf("%w: peer %s store is not the one the master recorded", ErrPeerNotInSync, peer.Target().ReplicaID)
|
||||
}
|
||||
return ack.AchievedLSN, nil
|
||||
},
|
||||
invalidate: peer.Invalidate,
|
||||
|
||||
@@ -93,6 +93,9 @@ type ReplicationVolume struct {
|
||||
updateMu sync.Mutex // serializes membership replacement with Close
|
||||
mu sync.Mutex // protects membership, lineage, and lifecycle snapshots
|
||||
peers map[string]*ReplicaPeer
|
||||
// requireAttest: peers count toward write ACKs only while their barrier
|
||||
// store is the one the master recorded (RequireAttestedStores).
|
||||
requireAttest bool
|
||||
executors map[string]*transport.BlockExecutor
|
||||
peerQueues map[string]*peerWorkQueue
|
||||
peerQueueDepth int
|
||||
@@ -407,6 +410,9 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic
|
||||
// peer ID set; `got` is the incoming set. Equal sets are the
|
||||
// normal replay case; unequal sets indicate a master-side
|
||||
// oddity worth a grep.
|
||||
// The master's store record for a peer may change without a new
|
||||
// generation (it records a rebuilt replica's store): apply it.
|
||||
v.applyExpectedStoresLocked(targets)
|
||||
had := peerIDSet(v.peers)
|
||||
got := targetIDSet(targets)
|
||||
if !stringSetEqual(had, got) {
|
||||
@@ -494,6 +500,9 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic
|
||||
peer.setOnHealthy(func() {
|
||||
v.resetTerminalPeerQueue(peer)
|
||||
})
|
||||
if v.requireAttest {
|
||||
peer.setRequireAttest()
|
||||
}
|
||||
if v.epochs != nil {
|
||||
peer.setReconcile(func(ctx context.Context) (bool, bool, string) { return v.reconcilePeer(ctx, peer) })
|
||||
executor.SetEpochTable(v.epochs)
|
||||
@@ -522,7 +531,8 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic
|
||||
addedPeers = append(addedPeers, peer)
|
||||
}
|
||||
|
||||
v.seedNewPeerLiveCursorsLocked(addedPeers)
|
||||
learn := v.seedNewPeerLiveCursorsLocked(addedPeers)
|
||||
v.applyExpectedStoresLocked(targets)
|
||||
|
||||
// Advance the monotonic guard only for real (non-zero) generations.
|
||||
if generation > 0 {
|
||||
@@ -530,9 +540,31 @@ func (v *ReplicationVolume) UpdateReplicaSet(generation uint64, targets []Replic
|
||||
}
|
||||
v.membershipUpdating = false
|
||||
v.mu.Unlock()
|
||||
v.learnPeerStores(learn)
|
||||
return nil
|
||||
}
|
||||
|
||||
// learnPeerStores runs a barrier at LSN 0 to each peer, in parallel and
|
||||
// without v.mu (only the UpdateReplicaSet call waits, at most one barrier
|
||||
// timeout): the answer carries the peer's store. A peer that does not answer
|
||||
// is degraded like any failed barrier; its store is learned at the barrier
|
||||
// that heals it.
|
||||
func (v *ReplicationVolume) learnPeerStores(peers []*ReplicaPeer) {
|
||||
var wg sync.WaitGroup
|
||||
for _, peer := range peers {
|
||||
wg.Add(1)
|
||||
go func(peer *ReplicaPeer) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), promotionSeedBarrierTimeout)
|
||||
defer cancel()
|
||||
if _, err := peer.Barrier(ctx, 0); err != nil {
|
||||
log.Printf("replication: volume %s store barrier peer=%s: %v", v.volumeID, peer.Target().ReplicaID, err)
|
||||
}
|
||||
}(peer)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (v *ReplicationVolume) closePeerQueueLocked(replicaID string) {
|
||||
if q := v.peerQueues[replicaID]; q != nil {
|
||||
q.closeAndWait()
|
||||
@@ -585,18 +617,28 @@ func (v *ReplicationVolume) replaceTerminalPeerQueueLocked(id string, old *peerW
|
||||
// cannot satisfy sync-quorum/sync-all write acknowledgement. A peer that
|
||||
// answers above the frontier holds a divergent old-epoch tail and is
|
||||
// degraded too (it needs a rebuild, never counts by length).
|
||||
func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) {
|
||||
//
|
||||
// It returns the peers whose store is still to be learned (a new volume
|
||||
// where stores are required): the caller runs learnPeerStores on them after
|
||||
// releasing v.mu.
|
||||
func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) []*ReplicaPeer {
|
||||
if len(peers) == 0 {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
frontier, err := v.store.Sync()
|
||||
if err != nil {
|
||||
log.Printf("replication: volume %s live cursor seed skipped: local sync failed: %v",
|
||||
v.volumeID, err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if frontier == 0 {
|
||||
return
|
||||
// Nothing to seed. Where stores are required, a barrier at 0 still
|
||||
// teaches the primary each new peer's store, so it can attest it
|
||||
// before any write (a new volume serves nothing until then).
|
||||
if v.requireAttest {
|
||||
return peers
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, peer := range peers {
|
||||
if peer == nil {
|
||||
@@ -640,6 +682,7 @@ func (v *ReplicationVolume) seedNewPeerLiveCursorsLocked(peers []*ReplicaPeer) {
|
||||
}
|
||||
peer.SeedLiveShipCursor(frontier, "assignment frontier barrier")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// peerIDSet extracts the set of peer IDs from the current peers map.
|
||||
@@ -1113,6 +1156,33 @@ func replicationDurationNanos(d time.Duration) uint64 {
|
||||
// when the store carries none).
|
||||
func (v *ReplicationVolume) LocalStoreID() storage.StoreID { return storage.StoreIDOf(v.store) }
|
||||
|
||||
// applyExpectedStoresLocked sets each kept peer's expected store from its
|
||||
// target, when the target names the peer's current lineage.
|
||||
func (v *ReplicationVolume) applyExpectedStoresLocked(targets []ReplicaTarget) {
|
||||
for _, t := range targets {
|
||||
p, ok := v.peers[t.ReplicaID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
cur := p.Target()
|
||||
if cur.Epoch == t.Epoch && cur.EndpointVersion == t.EndpointVersion && cur.DataAddr == t.DataAddr {
|
||||
p.setExpectedStore(t.StoreID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequireAttestedStores makes every peer count toward write ACKs only while
|
||||
// its barrier reports the store the master recorded for it (the target's
|
||||
// StoreID). A host that attests its stores to a master sets it.
|
||||
func (v *ReplicationVolume) RequireAttestedStores() {
|
||||
v.mu.Lock()
|
||||
defer v.mu.Unlock()
|
||||
v.requireAttest = true
|
||||
for _, p := range v.peers {
|
||||
p.setRequireAttest()
|
||||
}
|
||||
}
|
||||
|
||||
// AttestedStores is the primary's attestation of its write-ACK set: each
|
||||
// Healthy peer with the store its last barrier reported (replica id ->
|
||||
// store id). A peer that is not Healthy, or has not answered a barrier
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -243,6 +243,11 @@ message ReplicaDescriptor {
|
||||
uint64 endpoint_version = 3;
|
||||
string data_addr = 4;
|
||||
string ctrl_addr = 5;
|
||||
// store_id is the replica's store the master recorded (16 bytes; its
|
||||
// superblock UUID): the primary counts this peer's acks only while the
|
||||
// store the peer states in its replication session is this one. Empty
|
||||
// never matches.
|
||||
bytes store_id = 6;
|
||||
}
|
||||
|
||||
// AssignmentFact — master-minted AssignmentInfo fact carried to a
|
||||
@@ -296,6 +301,12 @@ message AssignmentFact {
|
||||
// The probed store's id (its superblock UUID, 16 bytes): the target
|
||||
// adopts a promotion only on that same store.
|
||||
bytes evidence_store_id = 14;
|
||||
// A new volume's initial replicas whose attested store the master has
|
||||
// not recorded yet (0: none awaited). While it is non-zero the primary
|
||||
// serves no frontend I/O: its peers' acks cannot count yet.
|
||||
uint32 replica_stores_awaited = 15;
|
||||
// The number of initial replicas (the N of "n of N" in its status).
|
||||
uint32 replica_stores_initial = 16;
|
||||
}
|
||||
|
||||
// PrimaryKind is how a line made its primary the primary.
|
||||
|
||||
@@ -9,6 +9,15 @@ type StoreID [16]byte
|
||||
// IsZero reports whether the id is unknown.
|
||||
func (id StoreID) IsZero() bool { return id == StoreID{} }
|
||||
|
||||
// StoreIDFromBytes decodes a wire store id; anything but 16 bytes is zero.
|
||||
func StoreIDFromBytes(b []byte) StoreID {
|
||||
var id StoreID
|
||||
if len(b) == len(id) {
|
||||
copy(id[:], b)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// storeIdentified is implemented by stores that carry a superblock UUID.
|
||||
type storeIdentified interface {
|
||||
StoreID() StoreID
|
||||
|
||||
Reference in new issue
Block a user