Merge branch 'main' into fix/929-nvme-connection-cancel

This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-01 23:09:22 -08:00
commit 45926a51f5
37 files changed
+3558 -1179

No files matched your search

+4 -1
View File
@@ -61,7 +61,10 @@ TestSnapshotLadderB1SnapshotQuery
TestSnapshotLadderC1FullRestore
TestSnapshotLadderC2IncrementalRestore
TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt
TestSnapshotLadderC3KilledHydrating
# A first write after the holder reports its frontend ready can be answered
# namespace-not-ready for longer than a host retries (#905, a v1.1 release
# gate); it runs and is reported on every job until the fix removes this.
TestSnapshotLadderC3KilledHydrating # nongating=#905
TestSnapshotLadderD1DeleteTheNewest
TestSnapshotLadderD2DeleteAMiddleOne
TestSnapshotLadderD3DeleteWhenContentRecurs
@@ -11,11 +11,15 @@ import (
"testing"
)
// The node registry (server id -> registered host) is static after start:
// the identity checks (the registered-host refusal beside the certificate
// identity) assume no one rewrites it while blockmaster serves. Its only
// writer is the cluster-spec import at start-up. This guard fails when a
// new non-test caller of RegisterNode or RemoveNode appears anywhere.
// The node registry (server id -> registered host) only ever loses entries
// after start: the identity checks (the registered-host refusal beside the
// certificate identity) assume no one adds or rebinds a server id while
// blockmaster serves. Its only adder is the cluster-spec import at start-up.
// Its one remover after start is the operator's host retire, which takes
// only a host that holds no volume: a retired id is then unregistered, so a
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
// only get stricter. This guard fails when any other non-test caller of
// RegisterNode or RemoveNode appears anywhere.
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
@@ -64,8 +68,8 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
t.Fatal(err)
}
sort.Strings(sites)
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode"}
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
if strings.Join(sites, ",") != strings.Join(want, ",") {
t.Fatalf("node registry writers = %v, want only %v: a writer after start breaks the static-registry assumption of the identity checks", sites, want)
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
}
}
@@ -507,9 +507,10 @@ var handoffPorts struct {
}
// handoffAddress returns a free loopback address in 10000-19999: below the
// kernel's ephemeral range (32768 and up on Linux), where an outgoing
// connection can take a port while a restarted daemon waits to bind it
// again, and below the 20000-49999 range startWorkspaceWeed draws from.
// kernel's ephemeral range (32768 and up on Linux; the range is cut at the
// host's own ephemeral low end when that is lower: handoffRange), where an
// outgoing connection can take a port while a restarted daemon waits to bind
// it again, and below the 20000-49999 range startWorkspaceWeed draws from.
func handoffAddress(t *testing.T) string {
t.Helper()
handoffPorts.Lock()
@@ -517,8 +518,13 @@ func handoffAddress(t *testing.T) string {
if handoffPorts.used == nil {
handoffPorts.used = map[int]bool{}
}
eph, _ := ephemeralPorts()
rlo, rhi, ok := handoffRange(eph)
if !ok {
t.Fatalf("no handoff port range below this host's ephemeral range (from %d)", eph)
}
for i := 0; i < 500; i++ {
lo, hi := testPortSpan(10000, 20000)
lo, hi := testPortSpan(rlo, rhi)
p := lo + rand.Intn(hi-lo)
if handoffPorts.used[p] || !claimHostPort(p) {
continue
@@ -260,15 +260,77 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
// f1Up starts the blockvolume of key and waits for its volume to be primary
// and its frontend ready.
//
// A harness-chosen port can be taken between handoffAddress's free check and
// the holder's bind. When the holder exits before adopting with "address
// already in use", its four ports are drawn again and it starts once more
// (startWithBindRetry). v1's ports are the harness's own and named in the
// cluster spec, so v1 is not retried.
func f1Up(t *testing.T, env *handoffEnv, key string) *daemon {
t.Helper()
var d *daemon
start := func(attempt int) error {
b := env.hosts[key]
name := "blockvolume-" + key
if attempt > 1 {
name = fmt.Sprintf("%s-attempt%d", name, attempt) // its own log: the first attempt's stays whole
}
d = env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
return f1WaitAdopted(d, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica),
[]string{b.data, b.ctrl, b.status, b.nvme})
}
fresh := func() {
b := env.hosts[key]
b.data, b.ctrl, b.status, b.nvme = handoffAddress(t), handoffAddress(t), handoffAddress(t), handoffAddress(t)
env.hosts[key] = b
}
var first, err error
if key == "v1" {
err = start(1)
} else {
first, err = startWithBindRetry(start, fresh)
}
if first != nil {
t.Logf("%s: started again on new ports after its first attempt lost a drawn port: %v", key, first)
}
if err != nil {
t.Fatal(err)
}
b := env.hosts[key]
d := env.h.start(t, "blockvolume-"+key, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica))
poll(t, 60*time.Second, key+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
return d
}
// f1WaitAdopted waits until d logs s. A holder that exits first because the
// bind of one of drawn (this attempt's own addresses) found it in use
// answers errBindTaken (wrapped, naming the address and the log's end);
// any other exit or the bound answers an error naming it.
func f1WaitAdopted(d *daemon, timeout time.Duration, s string, drawn []string) error {
end := time.Now().Add(timeout)
for {
if d.line(s) != "" {
return nil
}
select {
case <-d.done:
if d.line(s) != "" {
return nil
}
if data, err := os.ReadFile(d.log); err == nil {
if addr, ok := bindTakenOn(string(data), drawn); ok {
return fmt.Errorf("%s exited (%v) before logging %q: %w (%s; log %s); its log ends:\n%s", d.name, d.err, s, errBindTaken, addr, d.log, d.tail(40))
}
}
return fmt.Errorf("%s exited (%v) before logging %q; its log ends:\n%s", d.name, d.err, s, d.tail(40))
default:
}
if time.Now().After(end) {
return fmt.Errorf("%s did not log %q within %s; its log ends:\n%s", d.name, s, timeout, d.tail(40))
}
time.Sleep(100 * time.Millisecond)
}
}
// f1StartSources starts the N source volumes.
func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume {
t.Helper()
@@ -0,0 +1,143 @@
package main_test
import (
"errors"
"regexp"
"strings"
"testing"
)
// handoffRange is the range [lo, hi) a harness-chosen daemon port is drawn
// from: [10000, 20000), cut at the host's ephemeral range when that starts
// lower, so an outgoing connection's source port cannot take a port between
// the free check and the daemon's bind. ok is false when nothing is left.
func handoffRange(ephemeralLo int) (lo, hi int, ok bool) {
lo, hi = 10000, 20000
if ephemeralLo < hi {
hi = ephemeralLo
}
return lo, hi, hi > lo
}
// errBindTaken is a start that failed because one of the addresses the
// harness drew for it was taken before the daemon bound it.
var errBindTaken = errors.New("a harness-chosen port was taken before the daemon bound it")
// bindTakenRe is Go's net error for a listener whose bind found the address
// in use, ending its log line: "listen tcp <addr>: bind: address already in
// use". A dial, a quoted copy inside other text, or anything after it on the
// line does not match.
var bindTakenRe = regexp.MustCompile(`(?:^|[\s:])listen tcp (\S+): bind: address already in use$`)
// bindTakenOn reports the drawn address whose listener bind failed with
// EADDRINUSE in log, if any: only an exact listener-bind error, and only on
// one of drawn (this attempt's own addresses). Anything else is not a taken
// port, so the caller fails as it would without a retry.
func bindTakenOn(log string, drawn []string) (string, bool) {
for _, l := range strings.Split(log, "\n") {
m := bindTakenRe.FindStringSubmatch(strings.TrimRight(l, "\r"))
if m == nil {
continue
}
for _, a := range drawn {
if m[1] == a {
return a, true
}
}
}
return "", false
}
// startWithBindRetry starts a daemon and waits for it; when the start
// reports errBindTaken, it asks for fresh ports and starts once more. first
// is the first attempt's error when it was retried (kept for the report);
// err is the answer that stands. Any other answer, and a second
// errBindTaken, is returned as it is.
func startWithBindRetry(start func(attempt int) error, freshPorts func()) (first, err error) {
err = start(1)
if !errors.Is(err, errBindTaken) {
return nil, err
}
first = err
freshPorts()
return first, start(2)
}
func TestHandoffRangeStaysBelowTheEphemeralRange(t *testing.T) {
for _, c := range []struct {
eph, lo, hi int
ok bool
}{
{32768, 10000, 20000, true}, // the Linux default: the whole range
{20000, 10000, 20000, true},
{15000, 10000, 15000, true}, // a host whose ephemeral range starts low: cut there
{10001, 10000, 10001, true},
{10000, 10000, 10000, false}, // nothing left
{1024, 10000, 1024, false},
} {
lo, hi, ok := handoffRange(c.eph)
if lo != c.lo || hi != c.hi || ok != c.ok {
t.Fatalf("ephemeral from %d: [%d, %d) ok=%v; want [%d, %d) ok=%v", c.eph, lo, hi, ok, c.lo, c.hi, c.ok)
}
}
}
func TestBindTakenOnOnlyThisAttemptsListener(t *testing.T) {
drawn := []string{"127.0.0.1:11230", "127.0.0.1:11231", "127.0.0.1:11232", "127.0.0.1:11233"}
for _, c := range []struct {
name, log string
addr string
taken bool
}{
{"a drawn listener's bind", "2026/12/02 05:01:02 blockvolume: status listener: listen tcp 127.0.0.1:11230: bind: address already in use", "127.0.0.1:11230", true},
{"the bare net error", "listen tcp 127.0.0.1:11233: bind: address already in use", "127.0.0.1:11233", true},
{"a CRLF line", "listen tcp 127.0.0.1:11231: bind: address already in use\r", "127.0.0.1:11231", true},
{"another port", "listen tcp 127.0.0.1:11299: bind: address already in use", "", false},
{"another host, same port", "listen tcp 0.0.0.0:11230: bind: address already in use", "", false},
{"a dial", "dial tcp 127.0.0.1:11230: connect: address already in use", "", false},
{"quoted inside other text", `retry: err="listen tcp 127.0.0.1:11230: bind: address already in use"`, "", false},
{"more after it", "listen tcp 127.0.0.1:11230: bind: address already in use; retrying", "", false},
{"the words alone", "address already in use", "", false},
{"udp", "listen udp 127.0.0.1:11230: bind: address already in use", "", false},
{"nothing", "blockvolume: volume v2 adopted as PRIMARY at r2@1", "", false},
} {
addr, taken := bindTakenOn("first line\n"+c.log+"\nlast line", drawn)
if addr != c.addr || taken != c.taken {
t.Fatalf("%s: (%q, %v); want (%q, %v)", c.name, addr, taken, c.addr, c.taken)
}
}
}
func TestStartWithBindRetry(t *testing.T) {
other := errors.New("exited before logging adoption")
taken := func(n int) error { return errors.Join(errBindTaken, errors.New("attempt "+string(rune('0'+n)))) }
for _, c := range []struct {
name string
answers []error
first bool
want error
attempts []int
freshCnt int
}{
{"ok at once", []error{nil}, false, nil, []int{1}, 0},
{"another failure is not retried", []error{other}, false, other, []int{1}, 0},
{"a taken port, then ok", []error{taken(1), nil}, true, nil, []int{1, 2}, 1},
{"a taken port twice: the second answer stands", []error{taken(1), taken(2)}, true, errBindTaken, []int{1, 2}, 1},
{"a taken port, then another failure", []error{taken(1), other}, true, other, []int{1, 2}, 1},
} {
var attempts []int
fresh := 0
first, err := startWithBindRetry(func(a int) error { attempts = append(attempts, a); return c.answers[a-1] }, func() { fresh++ })
if (first != nil) != c.first || (c.first && !errors.Is(first, errBindTaken)) {
t.Fatalf("%s: first=%v", c.name, first)
}
if !errors.Is(err, c.want) || (c.want == nil && err != nil) || fresh != c.freshCnt || len(attempts) != len(c.attempts) {
t.Fatalf("%s: err=%v attempts=%v fresh=%d", c.name, err, attempts, fresh)
}
for i, a := range c.attempts {
if attempts[i] != a {
t.Fatalf("%s: attempts %v, want %v", c.name, attempts, c.attempts)
}
}
}
}
@@ -0,0 +1,114 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// clusterLifecycleDial opens the master's lifecycle service; a test
// replaces it.
var clusterLifecycleDial = func(addr string) (control.LifecycleServiceClient, func() error, error) {
conn, err := link.DialMasterFromEnv(addr)
if err != nil {
return nil, nil, err
}
return control.NewLifecycleServiceClient(conn), conn.Close, nil
}
// runCluster is "sw-block cluster finalize-format|retire-host".
func runCluster(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprintln(stderr, "sw-block: expected subcommand cluster finalize-format|retire-host")
return ops.VolumeStatusExitInvalid
}
switch args[0] {
case "finalize-format":
return runClusterFinalizeFormat(args[1:], stdout, stderr)
case "retire-host":
return runClusterRetireHost(args[1:], stdout, stderr)
}
fmt.Fprintf(stderr, "sw-block: unknown subcommand cluster %q\n", args[0])
return ops.VolumeStatusExitInvalid
}
// runClusterFinalizeFormat raises the cluster's format level to 1. Going
// back to v1.0.x works only before it: afterwards a v1.0.x master or holder
// refuses the store (an expected refusal, not damage). The master refuses
// it while any registered host does not read level 1, naming each one.
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s]")
return ops.VolumeStatusExitInvalid
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", err)
return ops.VolumeStatusExitUnhealthy
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
resp, err := c.FinalizeFormat(ctx, &control.FinalizeFormatRequest{Level: 1}, grpc.WaitForReady(false))
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", status.Convert(err).Message())
return clusterExit(err)
}
if resp.GetAlready() {
fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel())
return ops.VolumeStatusExitOK
}
fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel())
return ops.VolumeStatusExitOK
}
// runClusterRetireHost removes a registered host from the node inventory.
// The master refuses it while the host holds a lease or an assignment.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
server := fs.String("server", "", "the server id to retire (required)")
confirm := fs.String("confirm", "", "the same server id again (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s]")
return ops.VolumeStatusExitInvalid
}
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", err)
return ops.VolumeStatusExitUnhealthy
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", status.Convert(err).Message())
return clusterExit(err)
}
fmt.Fprintf(stdout, "host %s retired\n", *server)
return ops.VolumeStatusExitOK
}
// clusterExit maps a master error to the CLI's exit codes: a malformed
// request is 2 (as a usage error); a refusal or an unreachable master is 1.
func clusterExit(err error) int {
if status.Code(err) == codes.InvalidArgument {
return ops.VolumeStatusExitInvalid
}
return ops.VolumeStatusExitUnhealthy
}
@@ -0,0 +1,94 @@
package main
import (
"bytes"
"context"
"strings"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type fakeClusterMaster struct {
control.LifecycleServiceClient
finalize func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error)
retire func(*control.RetireHostRequest) (*control.RetireHostResponse, error)
}
func (f *fakeClusterMaster) FinalizeFormat(_ context.Context, r *control.FinalizeFormatRequest, _ ...grpc.CallOption) (*control.FinalizeFormatResponse, error) {
return f.finalize(r)
}
func (f *fakeClusterMaster) RetireHost(_ context.Context, r *control.RetireHostRequest, _ ...grpc.CallOption) (*control.RetireHostResponse, error) {
return f.retire(r)
}
func withClusterMaster(t *testing.T, f *fakeClusterMaster) {
t.Helper()
saved := clusterLifecycleDial
t.Cleanup(func() { clusterLifecycleDial = saved })
clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) {
return f, func() error { return nil }, nil
}
}
// finalize-format asks level 1; a refusal names the old hosts and exits 1,
// a finalize and an already-finalized cluster exit 0, a malformed command 2.
func TestClusterFinalizeFormat(t *testing.T) {
refuse := true
f := &fakeClusterMaster{finalize: func(r *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
if r.GetLevel() != 1 {
t.Errorf("finalize asked level %d", r.GetLevel())
}
if refuse {
return nil, status.Error(codes.FailedPrecondition, "format finalize refused: registered hosts do not read format level 1: node-b (no report)")
}
return &control.FinalizeFormatResponse{FormatLevel: 1}, nil
}}
withClusterMaster(t, f)
var out, errOut bytes.Buffer
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "node-b (no report)") {
t.Fatalf("refused finalize: exit %d, stderr %q", code, errOut.String())
}
refuse = false
out.Reset()
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "format level 1 finalized") {
t.Fatalf("finalize: exit %d, stdout %q", code, out.String())
}
f.finalize = func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return &control.FinalizeFormatResponse{FormatLevel: 1, Already: true}, nil
}
out.Reset()
if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "already finalized") {
t.Fatalf("already finalized: exit %d, stdout %q", code, out.String())
}
if code := run([]string{"cluster", "finalize-format"}, &out, &errOut); code != 2 {
t.Fatalf("finalize without --master: exit %d, want 2", code)
}
}
// retire-host sends the server id and its confirm; a refusal exits 1.
func TestClusterRetireHost(t *testing.T) {
var got *control.RetireHostRequest
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
got = r
if r.GetServerId() == "busy" {
return nil, status.Error(codes.FailedPrecondition, `retire refused: host "busy" holds a lease or an assignment for volumes v1; move them first`)
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
withClusterMaster(t, f)
var out, errOut bytes.Buffer
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") {
t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 2 {
t.Fatalf("retire without --confirm: exit %d, want 2", code)
}
}
+3
View File
@@ -102,6 +102,9 @@ func run(args []string, stdout, stderr io.Writer) int {
if args[0] == "shell" {
return runShell(args[1:], os.Stdin, stdout, stderr)
}
if args[0] == "cluster" {
return runCluster(args[1:], stdout, stderr)
}
if args[0] != "ops" {
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
usage(stderr)
+13
View File
@@ -185,6 +185,16 @@ type Publisher struct {
leaseMu sync.Mutex
leaseViews map[string]*leaseView
// formatLevel is the cluster's format level (workspace_lease_v100.go):
// 0 keeps v1.0's master semantics (a current lease horizon, version-1
// records), 1 is v1.1's. Written under mu and leaseMu, read under
// either.
formatLevel uint32
// Level 0's horizon extender (workspace_lease_v100.go).
leaseClosing bool // guarded by mu and leaseMu
extWG sync.WaitGroup // admitted extenders
extendFailures map[string]int // guarded by mu
// testAfterIssuePublish, when set by a test, runs under mu right after
// an issued move's lease view is published.
testAfterIssuePublish func(volume string)
@@ -259,6 +269,8 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher {
workspaceNow: time.Now,
workspaceTTL: 30 * time.Second,
leaseViews: map[string]*leaseView{},
formatLevel: 1,
extendFailures: map[string]int{},
}
for _, opt := range opts {
if opt != nil {
@@ -713,6 +725,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
if issuedWorkspace != nil {
record.Workspace = cloneWorkspace(issuedWorkspace)
}
record.EnvelopeVersion = p.envelopeVersionLocked()
if err := p.store.Put(record); err != nil {
// State mutation hasn't happened yet; nothing to
// unwind. Just report the failure.
@@ -39,6 +39,11 @@ import (
// lease time gates serving and forced moves; it never erases the last authored
// line. Only Publisher can mint its replacement.
type DurableRecord struct {
// EnvelopeVersion is the envelope version the store writes the record
// in (0: storeEnvelopeVersion). Not part of the body or its checksum: a
// master at format level 0 writes version 1, the one a v1.0.x master
// reads.
EnvelopeVersion int `json:"-"`
VolumeID string
ReplicaID string
Epoch uint64
@@ -150,8 +155,12 @@ func computeChecksum(r DurableRecord) string {
// encodeEnvelope serializes a record + checksum into the on-disk
// JSON envelope format.
func encodeEnvelope(r DurableRecord) ([]byte, error) {
version := r.EnvelopeVersion
if version == 0 {
version = storeEnvelopeVersion
}
env := storeEnvelope{
Version: storeEnvelopeVersion,
Version: version,
Body: r,
Checksum: computeChecksum(r),
}
+7 -1
View File
@@ -336,7 +336,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking {
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
}
if p.deadlineValidity(p.leaseDeadlineLocked(volume), s.Lease.MaxClockSkewNS, p.workspaceNow()) == 0 {
if p.ackValidityLocked(volume, s.Lease) == 0 {
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
}
s.Ack = &ack
@@ -405,6 +405,7 @@ func (p *Publisher) persistWorkspaceTimedLocked(volume string, s *WorkspaceState
i := line.info
record := DurableRecord{VolumeID: volume, ReplicaID: i.ReplicaID, Epoch: i.Epoch, EndpointVersion: i.EndpointVersion, DataAddr: i.DataAddr, CtrlAddr: i.CtrlAddr,
WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s), Incarnation: i.Incarnation}
record.EnvelopeVersion = p.envelopeVersionLocked()
start := time.Now()
err = p.store.Put(record)
write = time.Since(start)
@@ -482,6 +483,11 @@ func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease
skew := p.workspaceSkew(lease)
deadline := p.leaseDeadlineLocked(volume)
lostUntil = deadline.Add(skew).UnixNano()
if p.formatLevel == 0 {
// Level 0 keeps v1.0's barrier: the later of the persisted horizon
// and the deadline, each plus skew.
return p.forcedMoveBarrierV100Locked(lease, deadline, skew, now)
}
if now.Before(deadline.Add(skew)) {
return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
}
@@ -17,12 +17,17 @@ func TestDeletionReservationGuardSites(t *testing.T) {
"applyWithWorkspaceMove": true, "MoveWorkspace": true,
"RenewWorkspaceLease": true, "firstWorkspaceGrant": true,
"regrantWorkspaceLease": true,
// Format level 0's horizon extender rechecks the reservation.
"extendWorkspaceLease": true,
}
boundSites := map[string]bool{
"publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true,
"RenewWorkspaceLease": true, "regrantWorkspaceLease": true,
// Reply-only copies never increase published validity.
"WorkspaceLeaseReply": true,
"WorkspaceLeaseReply": true, "ackValidityLocked": true,
// Format level 0 (v1.0's semantics): the clamped grant and the
// horizon extender, which raises the persisted horizon only.
"renewV100Locked": true, "extendWorkspaceLease": true,
// Copies the persisted lease into the leaf view under mu -> leaseMu.
"deriveLeaseLocked": true,
// Positive lease construction and publication, or a plain clone.
@@ -0,0 +1,200 @@
package authority
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
// level0Publisher is a publisher at format level 0 over store, joining its
// extenders on cleanup before the store closes.
func level0Publisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher {
t.Helper()
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now), WithWorkspaceMaxClockSkew(4*time.Second), WithFormatLevel(0))
t.Cleanup(p.CloseWorkspaceExtenders)
return p
}
// awaitHorizon waits (bounded) until v's persisted horizon is want: an
// admitted extender writes it in the background.
func awaitHorizon(t *testing.T, p *Publisher, v string, want time.Time) {
t.Helper()
for end := time.Now().Add(5 * time.Second); time.Now().Before(end); time.Sleep(5 * time.Millisecond) {
if st := p.WorkspaceState(v); st != nil && st.Lease != nil && st.Lease.ExpiresAtNS == want.UnixNano() {
return
}
}
st := p.WorkspaceState(v)
t.Fatalf("the horizon of %s stayed %d, want %d", v, st.Lease.ExpiresAtNS, want.UnixNano())
}
// recordVersion is the envelope version of v's record on disk.
func recordVersion(t *testing.T, dir, v string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join(dir, v+".v3auth.json"))
if err != nil {
t.Fatal(err)
}
switch {
case bytes.HasPrefix(b, []byte(`{"v":1,`)):
return "1"
case bytes.HasPrefix(b, []byte(`{"v":2,`)):
return "2"
}
return string(b[:min(len(b), 12)])
}
// At format level 0 the master's records are v1.0's (envelope version 1);
// after the finalize they are version 2 (FormatGateMaster: the one durable
// step; a v1.0.x master reads version 1 only).
func TestRecordEnvelopeVersionFollowsTheFormatLevel(t *testing.T) {
disk, dir := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
bindAndGrant(t, p, "v", "r")
if got := recordVersion(t, dir, "v"); got != "1" {
t.Fatalf("level 0 wrote record envelope version %s, want 1", got)
}
p.FinalizeFormatLevel()
if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
if got := recordVersion(t, dir, "v"); got != "2" {
t.Fatalf("level 1 wrote record envelope version %s, want 2", got)
}
}
// At format level 0 a renewal keeps the persisted horizon current (v1.0's
// extender writes trigger + 1.5 TTL once the horizon is less than 1.25 TTL
// ahead) and a grant never passes it; at level 1 a renewal writes nothing
// (FormatGateMaster level0_no_horizon: without it a v1.0.x master started
// on the store trusts a stale horizon).
func TestALevel0RenewalKeepsTheHorizonCurrent(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
bindAndGrant(t, p, "v", "r") // t=0: horizon 45
if h := p.WorkspaceState("v").Lease.ExpiresAtNS; h != c.sec(45).UnixNano() {
t.Fatalf("first grant's horizon %d, want t=45", h)
}
c.at(10) // horizon 45 < 10 + 37.5: an extension to 10 + 45 = 55
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || l.ExpiresAtNS != c.sec(40).UnixNano() {
t.Fatalf("renewal at t=10: %+v %v, want the grant t=40", l, err)
}
awaitHorizon(t, p, "v", c.sec(55))
// Level 1: the same renewal writes nothing.
disk1, _ := newTempStore(t)
c1 := newTestClock()
p1 := newLeasePublisher(t, disk1, 30*time.Second, c1)
bindAndGrant(t, p1, "v", "r")
c1.at(10)
if _, err := p1.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
p1.CloseWorkspaceExtenders()
if h := p1.WorkspaceState("v").Lease.ExpiresAtNS; h != c1.sec(45).UnixNano() {
t.Fatalf("level 1: a renewal changed the persisted lease to t=%v", time.Unix(0, h).Sub(c1.sec(0)))
}
}
// At format level 0 a grant is clamped to the persisted horizon.
func TestALevel0GrantIsClampedToTheHorizon(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
p.CloseWorkspaceExtenders() // no extension: the horizon stays t=45
bindAndGrant(t, p, "v", "r")
c.at(20)
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || l.ExpiresAtNS != c.sec(45).UnixNano() {
t.Fatalf("renewal at t=20 with horizon t=45: %+v %v, want the grant clamped to t=45", l, err)
}
}
// At format level 0 the forced-move barrier is v1.0's (the later of the
// horizon and the deadline, plus skew); after the finalize it is the
// deadline plus skew, and the deadline covers the last level-0 grant
// (condition 3: a forced move right after the finalize still waits for it).
func TestTheForcedBarrierFollowsTheFormatLevel(t *testing.T) {
disk, _ := newTempStore(t)
c := newTestClock()
p := level0Publisher(t, disk, 30*time.Second, c)
p.CloseWorkspaceExtenders() // horizon stays t=45
bindAndGrant(t, p, "v", "r") // deadline t=30, horizon t=45, skew 4
c.at(40)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("level 0: a forced move admitted at t=40, before the horizon t=45 plus skew")
}
c.at(48.9)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("level 0: a forced move admitted at t=48.9, before t=49")
}
p.FinalizeFormatLevel()
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err != nil {
t.Fatalf("level 1 at t=48.9, past the deadline t=30 plus skew: %v", err)
}
// The last level-0 grant at t=20 (deadline t=50): right after the
// finalize a forced move still waits for t=54. The first renewal at
// t=20 is clamped to the horizon t=45 and admits an extension to t=65;
// once it is written, the renewal at t=20 grants t=50.
disk2, _ := newTempStore(t)
c2 := newTestClock()
p2 := level0Publisher(t, disk2, 30*time.Second, c2)
bindAndGrant(t, p2, "v", "r")
c2.at(20)
if l, err := p2.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil || l.ExpiresAtNS != c2.sec(45).UnixNano() {
t.Fatalf("renewal at t=20 under horizon t=45: %+v %v, want t=45", l, err)
}
awaitHorizon(t, p2, "v", c2.sec(65))
if l, err := p2.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil || l.ExpiresAtNS != c2.sec(50).UnixNano() {
t.Fatalf("renewal at t=20 under horizon t=65: %+v %v, want t=50", l, err)
}
p2.FinalizeFormatLevel()
c2.at(53.9)
if err := p2.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err == nil {
t.Fatal("after the finalize a forced move was admitted before the last level-0 grant (t=50) plus skew")
}
c2.at(54)
if err := p2.WorkspaceForcedMoveAdmitted(context.Background(), "v", "f", "r", 1); err != nil {
t.Fatalf("after the finalize at t=54 (level 0 would wait for the horizon t=65 plus skew): %v", err)
}
}
// A clamped level-0 grant raises the deadline with this process's monotonic
// reading, so the level-1 barrier after a finalize (with no renewal after
// it) cannot be moved by a wall-clock step.
func TestAClampedLevel0GrantKeepsTheMonotonicReading(t *testing.T) {
disk, _ := newTempStore(t)
base := time.Now() // monotonic
var offset atomic.Int64
clock := func() time.Time { return base.Add(time.Duration(offset.Load())) }
p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, clock), WithWorkspaceMaxClockSkew(4*time.Second), WithFormatLevel(0))
p.CloseWorkspaceExtenders() // no extension: the horizon stays first grant + 45 s
bindAndGrant(t, p, "v", "r")
offset.Store(int64(20 * time.Second))
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil {
t.Fatal(err)
}
if want := base.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
t.Fatalf("renewal at +20 s: grant %d, want the horizon %d (clamped)", l.ExpiresAtNS, want)
}
p.FinalizeFormatLevel()
p.mu.Lock()
d := p.leaseDeadlineLocked("v")
p.mu.Unlock()
if !strings.Contains(d.String(), "m=") {
t.Fatalf("the clamped deadline %s has no monotonic reading: a wall-clock step after the finalize would move the barrier", d)
}
if !d.Equal(base.Add(45 * time.Second)) {
t.Fatalf("the clamped deadline %s, want base + 45 s", d)
}
}
@@ -0,0 +1,199 @@
package authority
import (
"fmt"
"log"
"time"
)
// The cluster format level (FORMAT-GATE). Until the operator finalizes the
// v1.1 format the master keeps v1.0's semantics, so a v1.0.x master started
// on its store is safe: renewals keep the persisted lease horizon current
// (a background extender writes it ahead, and a grant is clamped to it),
// the forced-move barrier is the later of that horizon and the grant
// deadline plus skew, and records are written in envelope version 1. The
// finalize raises the level to 1, v1.1's semantics, in one step.
// WithFormatLevel sets the publisher's starting format level (0 or 1; the
// default is 1). A master sets it from its store before it serves.
func WithFormatLevel(level uint32) PublisherOption {
return func(p *Publisher) {
if level <= 1 {
p.formatLevel = level
}
}
}
// SetFormatLevelBeforeServing sets the format level a master read from its
// store. It is called before anything is served (no renewal, write or
// move has run); afterwards only FinalizeFormatLevel changes the level.
func (p *Publisher) SetFormatLevelBeforeServing(level uint32) {
if level > 1 {
return
}
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatLevel = level
}
// FormatLevel is the publisher's format level.
func (p *Publisher) FormatLevel() uint32 {
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
return p.formatLevel
}
// FinalizeFormatLevel switches the publisher to level 1. The caller has
// already made the level durable. It flips under mu and leaseMu, so forced
// moves (mu) and renewals (leaseMu, which read the level, grant and raise
// the deadline in one section) see one level. Every lease's deadline was
// raised by every grant at level 0 as well, so the level-1 barrier
// (deadline plus skew) still covers every grant made before the switch. An
// extender already admitted finds level 1 and writes nothing.
func (p *Publisher) FinalizeFormatLevel() {
p.mu.Lock()
defer p.mu.Unlock()
p.leaseMu.Lock()
defer p.leaseMu.Unlock()
p.formatLevel = 1
}
// envelopeVersionLocked is the record envelope version the level writes:
// v1.0's (1) at level 0. Caller holds mu.
func (p *Publisher) envelopeVersionLocked() int {
if p.formatLevel == 0 {
return storeEnvelopeVersionV100
}
return storeEnvelopeVersion
}
// ackValidityLocked is the host validity a revocation ACK is judged by: at
// level 0 v1.0's (the granted deadline, never above the persisted horizon),
// at level 1 the deadline's. Caller holds mu.
func (p *Publisher) ackValidityLocked(volume string, lease *WorkspaceLease) time.Duration {
deadline := p.leaseDeadlineLocked(volume)
if p.formatLevel == 0 {
l := *lease
l.ExpiresAtNS = min(l.ExpiresAtNS, deadline.UnixNano())
return p.WorkspaceLeaseValidity(l)
}
return p.deadlineValidity(deadline, lease.MaxClockSkewNS, p.workspaceNow())
}
// forcedMoveBarrierV100Locked is v1.0's forced-move barrier: the later of
// the persisted horizon and the grant (or restart) deadline, each plus
// skew. The audit bound is in wall time; the admission keeps both
// predicates, the deadline's monotonic reading included. Caller holds mu.
func (p *Publisher) forcedMoveBarrierV100Locked(lease *WorkspaceLease, deadline time.Time, skew time.Duration, now time.Time) (int64, time.Time, error) {
lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano()
if d := deadline.Add(skew).UnixNano(); d > lostUntil {
lostUntil = d
}
if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) {
return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed")
}
return lostUntil, now, nil
}
// renewV100Locked is a level-0 renewal of a live lease, v1.0's: the grant
// is min(now+TTL, horizon), it raises the deadline, and once the horizon is
// less than 1.25 TTL ahead an extender is admitted to write it ahead. It
// releases leaseMu. Caller holds leaseMu and has checked the lease.
func (p *Publisher) renewV100Locked(volume, holder string, epoch uint64, lv *leaseView, now time.Time) (WorkspaceLease, error) {
grant := now.Add(p.workspaceTTL)
if h := time.Unix(0, lv.d.horizon); grant.After(h) {
// Clamped to the horizon, as the time left to it from now: the grant
// (and the deadline it raises, which the level-1 barrier reads after
// a finalize) keeps now's monotonic reading, so a wall-clock step
// cannot move it.
grant = now.Add(h.Sub(now))
}
// A grant without positive host validity would make the host fence on an
// invalid reply; refuse with an error instead.
if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 {
horizon := lv.d.horizon
p.leaseMu.Unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
}
if grant.After(lv.deadline) {
lv.deadline = grant
}
if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing {
lv.extending = true
p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders
go p.extendWorkspaceLease(volume, holder, epoch, now)
}
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS}
p.leaseMu.Unlock()
return l, nil
}
// extendWorkspaceLease is an ordinary writer: under mu it rechecks the
// lease (and that the level is still 0) and writes horizon H = trigger +
// 1.5 TTL through persistWorkspaceLocked, so its write and its publication
// are one mu section. A write error latches uncertainty
// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write.
func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) {
defer p.extWG.Done()
p.beforeWorkspaceGrantLock("extension")
var note string
defer func() {
if note != "" {
log.Print(note)
}
}()
p.mu.Lock()
defer p.mu.Unlock()
defer func() {
p.leaseMu.Lock()
if lv := p.leaseViews[volume]; lv != nil {
lv.extending = false
}
p.leaseMu.Unlock()
}()
if p.leaseClosing || p.formatLevel != 0 || p.deleteReserved[volume] {
return
}
_, line, ok := p.workspaceLineLocked(volume)
s := cloneWorkspace(p.workspace[volume])
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking ||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) ||
p.workspaceUncertain[volume] || p.store == nil {
return
}
h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano()
old := s.Lease.ExpiresAtNS
if h <= old {
return
}
s.Lease.ExpiresAtNS = h
write, _, err := p.persistWorkspaceTimedLocked(volume, s)
took := write.Round(time.Millisecond)
if err != nil {
if p.extendFailures[volume] == 0 {
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err)
}
p.extendFailures[volume]++
return
}
if n := p.extendFailures[volume]; n > 0 {
note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano))
delete(p.extendFailures, volume)
}
}
// CloseWorkspaceExtenders stops admitting lease extensions and joins every
// admitted extender. Owners call it before closing the authority store:
// closing is set under mu and leaseMu, so an extender either finished its
// write before or sees closing and does not write.
func (p *Publisher) CloseWorkspaceExtenders() {
p.mu.Lock()
p.leaseMu.Lock()
p.leaseClosing = true
p.leaseMu.Unlock()
p.mu.Unlock()
p.extWG.Wait()
}
@@ -37,8 +37,9 @@ type leaseDerived struct {
// restart+TTL; a barrier adds the skew bound to it) is owned by the view; d
// is derived.
type leaseView struct {
d leaseDerived
deadline time.Time
d leaseDerived
deadline time.Time
extending bool // format level 0: an extender of this volume's horizon is admitted
}
// deriveLeaseLocked computes the derived lease view from published state.
@@ -125,7 +126,16 @@ func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise boo
// deadline), never a persisted value. Without a deadline (a published lease
// always has one) it reports 0, which gives the host no validity: fail
// closed.
func (lv *leaseView) replyExpiryNS() int64 {
//
// At format level 0 it is v1.0's: the granted deadline, never above the
// persisted horizon (min(horizon, deadline)).
func (lv *leaseView) replyExpiryNS(level uint32) int64 {
if level == 0 {
if lv.deadline.IsZero() {
return lv.d.horizon
}
return min(lv.deadline.UnixNano(), lv.d.horizon)
}
if lv.deadline.IsZero() {
return 0
}
@@ -152,7 +162,7 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
return WorkspaceLease{}, false
}
l := lv.d.lease
l.ExpiresAtNS = lv.replyExpiryNS()
l.ExpiresAtNS = lv.replyExpiryNS(p.formatLevel)
return l, true
}
@@ -262,11 +272,11 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
}
if lv.d.revoking { // tell the host to drain; never extend
l := lv.d.lease
l.ExpiresAtNS = lv.replyExpiryNS()
l.ExpiresAtNS = lv.replyExpiryNS(p.formatLevel)
unlock()
return l, nil
}
if !now.Before(lv.deadline) {
if !now.Before(lv.deadline) || (p.formatLevel == 0 && now.UnixNano() >= lv.d.horizon) {
unlock()
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
}
@@ -276,6 +286,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
}
if p.formatLevel == 0 {
return p.renewV100Locked(volume, holder, epoch, lv, now) // releases leaseMu
}
// The grant stays a time.Time with its monotonic reading: the deadline
// it raises is what admission compares (this process's own clock); only
// the reply carries wall nanoseconds.
@@ -284,8 +297,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
// bound, leaseFact) would make the host fence on an invalid reply and lose
// its remaining validity; refuse with an error instead.
if p.deadlineValidity(grant, lv.d.maxSkewNS, now) == 0 {
skew := lv.d.maxSkewNS // the view is leaseMu's: read it before the unlock
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(lv.d.maxSkewNS))
return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(skew))
}
if grant.After(lv.deadline) {
lv.deadline = grant
@@ -376,9 +390,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st
// start; it never compares clocks.
skew := p.workspaceSkew(s.Lease)
retry := max(p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0)
if p.formatLevel == 0 {
retry = max(retry, time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).Sub(now))
}
return WorkspaceLease{}, &LeaseBarrierError{Until: now.Add(retry), RetryAfter: retry, err: err}
}
lease, grant := p.newWorkspaceLease(holder, epoch, now)
if p.formatLevel == 0 {
lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) // v1.0: the horizon never drops
}
lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease))
s.Lease = lease
if err := p.persistWorkspaceLocked(volume, s); err != nil {
+2
View File
@@ -19,6 +19,8 @@ var masterRules = map[string]auth.Rule{
control.LifecycleService_GetVolume_FullMethodName: {Min: auth.RoleViewer},
control.LifecycleService_ReserveVolumeDeletion_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName: {Min: auth.RoleViewer},
control.LifecycleService_FinalizeFormat_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.LifecycleService_RetireHost_FullMethodName: {Min: auth.RoleAdmin, Strict: true},
control.ObservationService_ReportHeartbeat_FullMethodName: {Node: true},
control.ObservationService_ReportClusterEvent_FullMethodName: {Min: auth.RoleOperator},
+4 -4
View File
@@ -42,8 +42,8 @@ func TestMasterAuthorizationTableCoversEveryMethod(t *testing.T) {
}
// SubscribeProbeRounds and AnswerProbe (the promotion probe round) are
// node-only, each for the caller's own server id.
if len(registered) != 29 {
t.Fatalf("%d registered methods; the table was written for 29: review the new ones", len(registered))
if len(registered) != 31 {
t.Fatalf("%d registered methods; the table was written for 31 (FinalizeFormat and RetireHost added, admin and strict): review the new ones", len(registered))
}
}
@@ -77,7 +77,7 @@ func TestMasterOperatorMethodsAreStrict(t *testing.T) {
t.Errorf("%s is named in notStrict but is not a non-strict operator method: drop the entry", m)
}
}
if strict != 11 {
t.Errorf("%d strict methods; the phase 0 set is 11 (update this count with the change that adds one)", strict)
if strict != 13 {
t.Errorf("%d strict methods; the phase 0 set is 11, plus FinalizeFormat and RetireHost: 13 (update this count with the change that adds one)", strict)
}
}
@@ -0,0 +1,298 @@
package master
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// readsLevels holds the format read level each of a server's processes
// reported (its latest heartbeat's reads_level), in memory only, one entry
// per volume: a server runs one process per volume, so a later report for
// the same volume is that volume's process (restarted or replaced) and
// supersedes the earlier one. A server reads the lowest level of its
// entries. Silence is not proof that a process is gone: an entry whose
// volume the server still serves (a placement, a live line) stays, however
// long its process has been silent; only a silent entry of a volume the
// server no longer serves leaves after the freshness window. A registered
// server with no entry reads level 0: unknown counts as old.
type readsLevels struct {
mu sync.Mutex
window time.Duration
now func() time.Time
procs map[string]map[string]procLevel // server -> volume -> report
}
type procLevel struct {
level uint32
process string
seen time.Time
}
func newReadsLevels(window time.Duration) *readsLevels {
return &readsLevels{window: window, now: time.Now, procs: map[string]map[string]procLevel{}}
}
// note records the level the process holding volume (on server) reported.
func (r *readsLevels) note(server, volume, process string, level uint32) {
r.mu.Lock()
defer r.mu.Unlock()
if r.procs[server] == nil {
r.procs[server] = map[string]procLevel{}
}
r.procs[server][volume] = procLevel{level: level, process: process, seen: r.now()}
}
// forget drops every entry of server (a retired host).
func (r *readsLevels) forget(server string) {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.procs, server)
}
// liveLocked returns server's entries that still count: every entry of a
// served volume, and the others reported within the window (a silent
// entry of an unserved volume is dropped).
func (r *readsLevels) liveLocked(server string, served map[string]bool) map[string]procLevel {
cutoff := r.now().Add(-r.window)
for v, e := range r.procs[server] {
if e.seen.Before(cutoff) && !served[v] {
delete(r.procs[server], v)
}
}
return r.procs[server]
}
// of is the lowest level of server's live entries, and whether it has any.
func (r *readsLevels) of(server string, served map[string]bool) (uint32, bool) {
r.mu.Lock()
defer r.mu.Unlock()
var low uint32
found := false
for _, e := range r.liveLocked(server, served) {
if !found || e.level < low {
low, found = e.level, true
}
}
return low, found
}
// below names server's live entries below level, sorted, each as
// "process of volume (reads level N)".
func (r *readsLevels) below(server string, level uint32, served map[string]bool) []string {
r.mu.Lock()
defer r.mu.Unlock()
var out []string
for v, e := range r.liveLocked(server, served) {
if e.level < level {
out = append(out, fmt.Sprintf("%s of %s (reads level %d)", e.process, v, e.level))
}
}
sort.Strings(out)
return out
}
// noteHeartbeat records reads for every volume a heartbeat reports (each
// slot), naming the reporting process by the slot's incarnation (new on
// every process start), else its data address. A heartbeat with no slot
// is recorded under no volume.
func (r *readsLevels) noteHeartbeat(server string, slots []*control.HeartbeatSlot, reads uint32) {
if len(slots) == 0 {
r.note(server, "", "", reads)
return
}
for _, s := range slots {
process := s.GetIncarnation()
if process == "" {
process = s.GetDataAddr()
}
r.note(server, s.GetVolumeId(), process, reads)
}
}
// servedBy is the set of volumes server holds work for (volumesServedBy).
func (h *Host) servedBy(server string) map[string]bool {
out := map[string]bool{}
for _, v := range h.volumesServedBy(server) {
out[v] = true
}
return out
}
// formatLevelState is the cluster's format level in memory: 0 until the
// operator finalizes the v1.1 format.
type formatLevelState struct{ v atomic.Uint32 }
// formatLevel is the cluster's format level: 0 until the operator
// finalizes the v1.1 format.
func (h *Host) formatLevel() uint32 { return h.format.v.Load() }
// formatEligible reports whether server may be given new work (placement, a
// move, a failover) at the cluster's format level: its binary reads that
// level. At level 0 every server is.
func (h *Host) formatEligible(server string) bool {
level := h.formatLevel()
if level == 0 {
return true
}
reads, ok := h.reads.of(server, h.servedBy(server))
return ok && reads >= level
}
// formatTooOld names why server is not format-eligible, or "" when it is.
func (h *Host) formatTooOld(server string) string {
if h.formatEligible(server) {
return ""
}
reads, ok := h.reads.of(server, h.servedBy(server))
if !ok {
return fmt.Sprintf("node %q has not reported its format read level; the cluster's format level is %d", server, h.formatLevel())
}
return fmt.Sprintf("node %q reads format level %d (the lowest of its processes); the cluster's format level is %d (binary_too_old)", server, reads, h.formatLevel())
}
// belowLevel lists the given servers whose reported read level is below
// level, or that have not reported, sorted, each with what it reported.
func (h *Host) belowLevel(servers []string, level uint32) []string {
var out []string
for _, s := range servers {
served := h.servedBy(s)
reads, ok := h.reads.of(s, served)
switch {
case !ok:
out = append(out, fmt.Sprintf("%s (no report)", s))
case reads < level:
out = append(out, fmt.Sprintf("%s (process %s)", s, strings.Join(h.reads.below(s, level, served), ", ")))
}
}
sort.Strings(out)
return out
}
// errFormatHostsTooOld is a finalize refused for registered hosts that do
// not read the new level; errHostHoldsWork a retire refused for a host that
// holds work. Both name what refused them.
type errFormatHostsTooOld struct{ hosts []string }
func (e errFormatHostsTooOld) Error() string {
return fmt.Sprintf("format finalize refused: registered hosts do not read format level 1: %s; upgrade each one, or retire it (sw-block cluster retire-host)", strings.Join(e.hosts, ", "))
}
type errHostHoldsWork struct {
server string
volumes []string
}
func (e errHostHoldsWork) Error() string {
return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", "))
}
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
// Finalize; FormatGateMaster: the one durable step). It is refused while any
// registered host has not reported reads_level >= 1 since this master
// started. Otherwise, in order: the attestation envelope is written durably
// (the level, and the fence against v1.0.x masters, in one write); the
// publisher switches to level 1 under its locks; then the answer. At level
// 1 it writes nothing (already).
func (h *Host) FinalizeFormat(level uint32) (already bool, err error) {
if level != 1 {
return false, fmt.Errorf("format finalize: level %d; the only level to finalize is 1", level)
}
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
if h.formatLevel() >= 1 {
return true, nil
}
var registered []string
if h.lifecycle != nil {
for _, n := range h.lifecycle.Nodes.ListNodes() {
registered = append(registered, n.ServerID)
}
}
if below := h.belowLevel(registered, 1); len(below) > 0 {
return false, errFormatHostsTooOld{hosts: below}
}
if _, err := h.attest.finalize(); err != nil {
return false, fmt.Errorf("format finalize: %w", err)
}
h.Publisher().FinalizeFormatLevel()
h.format.v.Store(1)
h.log.Printf("blockmaster: cluster format level finalized at 1 (%d registered hosts read it)", len(registered))
return false, nil
}
// RetireHost removes server from the node inventory, so it no longer counts
// for the format finalize or for placement. It is refused while server
// holds a lease or an assignment for any volume (FormatGate r2: a retire
// of a holding host breaks OneServer). A retired host that returns
// registers again (the spec import) and is judged at its reported level.
func (h *Host) RetireHost(server, confirm string) error {
if server == "" || confirm != server {
return fmt.Errorf("retire refused: confirm must repeat the server id %q", server)
}
if h.lifecycle == nil {
return fmt.Errorf("retire refused: this master keeps no node inventory")
}
h.finalizeMu.Lock()
defer h.finalizeMu.Unlock()
if _, ok := h.lifecycle.Nodes.GetNode(server); !ok {
return fmt.Errorf("retire refused: host %q is not registered", server)
}
if vols := h.volumesServedBy(server); len(vols) > 0 {
return errHostHoldsWork{server: server, volumes: vols}
}
if err := h.lifecycle.Nodes.RemoveNode(server); err != nil {
return fmt.Errorf("retire: %w", err)
}
h.reads.forget(server)
h.log.Printf("blockmaster: host %s retired from the node inventory", server)
return nil
}
// FinalizeFormat is the RPC of Host.FinalizeFormat.
func (s *services) FinalizeFormat(ctx context.Context, req *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
already, err := s.host.FinalizeFormat(req.GetLevel())
var old errFormatHostsTooOld
switch {
case errors.As(err, &old):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonFormatHostsTooOld).Err()
case err != nil && req.GetLevel() != 1:
return nil, status.Error(codes.InvalidArgument, err.Error())
case err != nil:
return nil, status.Error(codes.Unavailable, err.Error())
}
return &control.FinalizeFormatResponse{FormatLevel: s.host.formatLevel(), Already: already}, nil
}
// RetireHost is the RPC of Host.RetireHost. It holds the workspace lock, as
// a placement does, so no placement onto the host lands between its check
// and the removal.
func (s *services) RetireHost(ctx context.Context, req *control.RetireHostRequest) (*control.RetireHostResponse, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.host.workspaceMu.Lock()
defer s.host.workspaceMu.Unlock()
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
var holds errHostHoldsWork
switch {
case errors.As(err, &holds):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork).Err()
case err != nil:
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
return &control.RetireHostResponse{ServerId: req.GetServerId()}, nil
}
@@ -0,0 +1,561 @@
package master
import (
"bytes"
"context"
"errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// fgHeartbeat sends server's heartbeat reporting reads (its binary's format
// read level).
func (r *isolationRig) fgHeartbeat(server string, reads uint32) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: reads,
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
return err
}
func binaryTooOld(err error) bool {
st := status.Convert(err)
if st.Code() != codes.FailedPrecondition {
return false
}
for _, d := range st.Details() {
if info, ok := d.(*errdetails.ErrorInfo); ok && info.Reason == lifecycleclient.ReasonBinaryTooOld {
return true
}
}
return false
}
// At level 0 every binary's heartbeat is taken; at level 1 one that reads
// only level 0 (or reports nothing: a v1.0.x binary) is refused, typed
// binary_too_old, and one that reads level 1 is taken (FormatGate: Join,
// Eligible).
func TestFormatGateRefusesAnOldBinarysHeartbeatAtLevel1(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if err := r.fgHeartbeat("node-a", 0); err != nil {
t.Fatalf("level 0: an old binary's heartbeat was refused: %v", err)
}
r.m.format.v.Store(1)
if err := r.fgHeartbeat("node-a", 0); !binaryTooOld(err) || !strings.Contains(status.Convert(err).Message(), "reads format level 0") {
t.Fatalf("level 1: an old binary's heartbeat: %v, want FailedPrecondition with reason %s", err, lifecycleclient.ReasonBinaryTooOld)
}
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatalf("level 1: a binary that reads level 1 was refused: %v", err)
}
}
// At level 1 no new work goes to a host that does not read it: a workspace
// placement and a move onto an old host (or one that never reported) are
// refused; at level 0 they are not refused for the format (FormatGate:
// Assign, NoStrand).
func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
for _, level := range []uint32{1, 0} {
for _, reported := range []bool{true, false} {
name := map[uint32]string{1: "level1", 0: "level0"}[level] + map[bool]string{true: "-old", false: "-silent"}[reported]
t.Run(name, func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if reported {
if err := r.fgHeartbeat("node-b", 0); err != nil {
t.Fatal(err)
}
}
r.m.format.v.Store(level)
r.createVolume(t, "placed")
r.place(t, "placed", "node-a")
r.createVolume(t, "fresh")
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
t.Fatal(err)
}
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
why := map[bool]string{true: "reads format level 0", false: "has not reported its format read level"}[reported]
if level == 0 {
if placeErr != nil {
t.Fatalf("level 0: placement refused: %v", placeErr)
}
if moveErr != nil && strings.Contains(moveErr.Error(), "format") {
t.Fatalf("level 0: move refused for the format: %v", moveErr)
}
return
}
if status.Code(placeErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(placeErr).Message(), why) {
t.Fatalf("level 1: PlaceWorkspace onto node-b: %v, want %q", placeErr, why)
}
if _, ok := r.m.Lifecycle().Placements.GetPlacement("fresh"); ok {
t.Fatal("a refused placement was recorded")
}
if status.Code(moveErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(moveErr).Message(), "move target node \"node-b\" "+why) {
t.Fatalf("level 1: MoveWorkspace onto node-b: %v, want %q", moveErr, why)
}
})
}
}
}
// At level 1 the product loop never places a new volume on a host that does
// not read it, and does on one that does.
func TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel(t *testing.T) {
for _, reads := range []uint32{0, 1} {
t.Run(map[uint32]string{0: "old", 1: "new"}[reads], func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502",
Pools: []lifecycle.StoragePool{{PoolID: "p1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096}}}); err != nil {
t.Fatal(err)
}
if err := r.fgHeartbeat("node-c", reads); err != nil {
t.Fatal(err)
}
r.m.format.v.Store(1)
r.createVolume(t, "auto")
if _, err := r.m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
p, ok := r.m.Lifecycle().Placements.GetPlacement("auto")
if reads == 0 && ok {
t.Fatalf("level 1: the product loop placed a new volume on a host that reads level 0: %+v", p)
}
if reads == 1 && (!ok || p.Slots[0].ServerID != "node-c") {
t.Fatalf("level 1: the product loop did not place on node-c, which reads level 1: %+v ok=%v", p, ok)
}
})
}
}
// Every assignment carries the cluster's format level.
func TestAssignmentFactCarriesTheFormatLevel(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
svc := &services{host: r.m}
for _, level := range []uint32{0, 1} {
r.m.format.v.Store(level)
if got := svc.assignmentFact(adapter.AssignmentInfo{VolumeID: "v", ReplicaID: "r1", Epoch: 1}).GetFormatLevel(); got != level {
t.Fatalf("level %d: AssignmentFact.format_level = %d", level, got)
}
}
}
func reasonOf(err error) string {
for _, d := range status.Convert(err).Details() {
if info, ok := d.(*errdetails.ErrorInfo); ok {
return info.Reason
}
}
return ""
}
// The finalize is refused, naming each one, while a registered host has not
// reported or reads level 0, and leaves the attestation file in v1.0.x's
// form (level 0). Once every registered host reads level 1 it writes the
// envelope (format_level 1), switches the publisher, and a second finalize
// writes nothing. A restarted master is still at level 1 (FormatGate:
// Finalize, FinalizeKeepsHosts, OneWay).
func TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable(t *testing.T) {
authDir, lcDir := t.TempDir(), t.TempDir()
r := newIsolationRig(t, false, authDir, lcDir)
file := filepath.Join(authDir, storeAttestationFile)
finalize := func() (*control.FinalizeFormatResponse, error) {
return r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
}
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
for _, step := range []struct {
reads *uint32
want string
}{{nil, "node-b (no report)"}, {ptr(uint32(0)), "node-b (process 127.0.0.1:19311 of hb-node-b (reads level 0))"}} {
if step.reads != nil {
if err := r.fgHeartbeat("node-b", *step.reads); err != nil {
t.Fatal(err)
}
}
_, err := finalize()
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), step.want) {
t.Fatalf("finalize with %s: %v (reason %q)", step.want, err, reasonOf(err))
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatal("a refused finalize changed the level")
}
if b, err := os.ReadFile(file); err == nil && bytes.Contains(b, []byte(`"format"`)) {
t.Fatalf("a refused finalize wrote the envelope: %s", b)
}
}
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatal(err)
}
resp, err := finalize()
if err != nil || resp.GetFormatLevel() != 1 || resp.GetAlready() {
t.Fatalf("finalize with every host at level 1: %+v %v", resp, err)
}
if r.m.formatLevel() != 1 || r.m.Publisher().FormatLevel() != 1 {
t.Fatal("the finalize did not switch the master and the publisher to level 1")
}
b, err := os.ReadFile(file)
if err != nil || !bytes.Contains(b, []byte(`"format":2`)) || !bytes.Contains(b, []byte(`"format_level":1`)) {
t.Fatalf("the attestation file after the finalize: %s %v", b, err)
}
if resp, err := finalize(); err != nil || !resp.GetAlready() {
t.Fatalf("a second finalize: %+v %v, want already", resp, err)
}
r.close(t)
r2 := newIsolationRig(t, false, authDir, lcDir)
if r2.m.formatLevel() != 1 || r2.m.Publisher().FormatLevel() != 1 {
t.Fatal("a restarted master is not at level 1")
}
}
func ptr[T any](v T) *T { return &v }
// An envelope that says a level below 1 is refused at start: the level
// never drops.
func TestAnAttestationEnvelopeBelowLevel1IsRefused(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":2,"format_level":0,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := loadStoreAttestations(dir); err == nil {
t.Fatal("an envelope at format_level 0 was read")
}
}
// A retire is refused, naming the volume, while the host holds an
// assignment, and when confirm does not repeat the server id. A host
// holding nothing is retired, and the finalize no longer counts it.
func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "held")
r.place(t, "held", "node-b")
_, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-b", Confirm: "node-b"})
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonHostHoldsWork || !strings.Contains(status.Convert(err).Message(), "held") {
t.Fatalf("retire of a host holding a placement: %v (reason %q)", err, reasonOf(err))
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("retire with a confirm that does not match: %v", err)
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil {
t.Fatalf("retire of a host holding nothing: %v", err)
}
if _, ok := r.m.Lifecycle().Nodes.GetNode("node-a"); ok {
t.Fatal("the retired host is still registered")
}
// node-b (holding "held") reports level 1; node-a, retired, never
// reported: the finalize goes through.
if err := r.fgHeartbeat("node-b", 1); err != nil {
t.Fatal(err)
}
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err != nil {
t.Fatalf("finalize after the silent host was retired: %v", err)
}
}
// A finalize whose durable write fails changes no level: the publisher and
// the master stay at 0 (the switch follows the write; FormatGateMaster
// finalize_not_atomic).
func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
for _, s := range []string{"node-a", "node-b"} {
if err := r.fgHeartbeat(s, 1); err != nil {
t.Fatal(err)
}
}
saved := syncAttestationDir
t.Cleanup(func() { syncAttestationDir = saved })
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err == nil {
t.Fatal("a finalize whose envelope write failed succeeded")
}
if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 {
t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel())
}
}
// fgProcessHeartbeat sends a heartbeat of one of server's processes (its
// incarnation) for vol, reporting reads.
func (r *isolationRig) fgProcessHeartbeat(server, incarnation, vol string, reads uint32) error {
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: reads,
Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r-" + incarnation, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1], Incarnation: incarnation}}})
return err
}
// One server id is shared by its per-volume processes, which may run
// different binaries: an old process's level 0 is not hidden by a new
// process's later level 1. The finalize is refused naming the old process;
// at level 1 the server takes no new work while the old process is live,
// and the new process's own heartbeat is taken (FormatGate: a host is a
// process).
func TestAServerReadsTheLowestLevelOfItsProcesses(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of va (reads level 0)") {
t.Fatalf("finalize with an old process beside a new one on node-b: %v", err)
}
r.m.format.v.Store(1)
if r.m.formatEligible("node-b") {
t.Fatal("level 1: node-b is eligible while its old process is live")
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatalf("level 1: the new process's own heartbeat was refused: %v", err)
}
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); !binaryTooOld(err) {
t.Fatalf("level 1: the old process's heartbeat: %v", err)
}
}
// Silence is not proof that a process is gone: an entry of a volume its
// server still serves stays, however long its process is silent; an
// unserved volume's silent entry leaves after the window; a later report
// for the same volume (its restarted or replaced process) supersedes it.
func TestAServerKeepsASilentProcessThatStillHoldsItsVolume(t *testing.T) {
rl := newReadsLevels(time.Minute)
now := time.Unix(1000, 0)
rl.now = func() time.Time { return now }
rl.note("s", "va", "old", 0)
rl.note("s", "vb", "new", 1)
now = now.Add(2 * time.Minute)
rl.note("s", "vb", "new", 1)
if l, ok := rl.of("s", map[string]bool{"va": true}); !ok || l != 0 {
t.Fatalf("va still served, its process silent past the window: level %d %v, want 0", l, ok)
}
if l, ok := rl.of("s", map[string]bool{}); !ok || l != 1 {
t.Fatalf("va no longer served and silent: level %d %v, want 1", l, ok)
}
rl.note("s", "va", "old", 0)
rl.note("s", "va", "restarted", 1)
if l, ok := rl.of("s", map[string]bool{"va": true}); !ok || l != 1 {
t.Fatalf("va's process replaced by one reading 1: level %d %v, want 1", l, ok)
}
}
// An old process holds a placed volume, a new sibling
// keeps reporting, the old one falls silent past the freshness window. The
// finalize stays refused naming the old process, and at level 1 a placement
// onto the server stays refused by the format check.
func TestASilentOldHolderKeepsTheFinalizeAndNewWorkRefused(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
now := time.Now()
r.m.reads.now = func() time.Time { return now }
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
r.createVolume(t, "va")
r.place(t, "va", "node-b")
if err := r.fgProcessHeartbeat("node-b", "old-proc", "va", 0); err != nil {
t.Fatal(err)
}
now = now.Add(time.Hour) // past any freshness window: the old process is silent
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vb", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of va (reads level 0)") {
t.Fatalf("finalize with a silent old holder of va: %v", err)
}
r.m.format.v.Store(1)
if why := r.m.formatTooOld("node-b"); why == "" {
t.Fatal("level 1: node-b takes new work while its silent old process still holds va")
}
r.createVolume(t, "fresh")
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
t.Fatal(err)
}
if _, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}); status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "binary_too_old") {
t.Fatalf("level 1: a placement onto node-b: %v, want the format refusal", err)
}
}
// The publication boundary judges the server's level when the ask is
// published: an ask whose server reads below the cluster's level is refused
// there and its publish never runs; the control publishes (the admission
// itself, called with a recording publish).
func TestThePublicationBoundaryRefusesAnAskForAnOldServer(t *testing.T) {
for _, old := range []bool{true, false} {
t.Run(map[bool]string{true: "old-process", false: "control"}[old], func(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-b")
level := uint32(1)
if old {
level = 0
}
if err := r.fgProcessHeartbeat("node-b", "proc", "v", level); err != nil {
t.Fatal(err)
}
r.m.format.v.Store(1)
published := false
err := r.m.admitWorkspacePublication(authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302", Intent: authority.IntentBind},
func() error { published = true; return nil })
if old && (err == nil || published || !strings.Contains(err.Error(), "binary_too_old")) {
t.Fatalf("level 1, node-b's process reads 0: err %v, published %v; want refused before the publish", err, published)
}
if !old && (err != nil || !published) {
t.Fatalf("control: err %v, published %v; want published", err, published)
}
})
}
}
// A heartbeat that reports several volumes records the level for each: an
// old process reporting [va, vb] is kept for vb, still placed on its
// server, after va stops being served and the report ages past the
// window.
func TestEveryVolumeOfAHeartbeatKeepsItsLevel(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
now := time.Now()
r.m.reads.now = func() time.Time { return now }
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
r.createVolume(t, "vb")
r.place(t, "vb", "node-b")
if _, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 0,
Slots: []*control.HeartbeatSlot{
{VolumeId: "va", ReplicaId: "r-a", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-proc"},
{VolumeId: "vb", ReplicaId: "r-b", DataAddr: hbPorts["node-b"][0], CtrlAddr: hbPorts["node-b"][1], Incarnation: "old-proc"},
}}); err != nil {
t.Fatal(err)
}
now = now.Add(time.Hour)
if err := r.fgHeartbeat("node-a", 1); err != nil {
t.Fatal(err)
}
if err := r.fgProcessHeartbeat("node-b", "new-proc", "vc", 1); err != nil {
t.Fatal(err)
}
_, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1})
if reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), "old-proc of vb (reads level 0)") {
t.Fatalf("finalize with the old process still holding vb (its second slot): %v", err)
}
}
// The queued-ask schedule: a bind is
// decided and reaches its publication admission while node-b's only process
// reads level 1; it is held there; another node-b process then reports level
// 0; released, the same ask is refused by the format check (binary_too_old)
// and no line is published. The control, with no downgrade, publishes.
func TestAHeldAskIsRefusedAfterItsServerTurnsOutOld(t *testing.T) {
for _, downgrade := range []bool{true, false} {
t.Run(map[bool]string{true: "downgrade", false: "control"}[downgrade], func(t *testing.T) {
authDir, lcDir := t.TempDir(), t.TempDir()
logs := &syncBuffer{}
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: lcDir, WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume,
Logger: log.New(logs, "", 0),
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{}, nil
}})
if err != nil {
t.Fatal(err)
}
entered, release, hookDone := make(chan struct{}), make(chan struct{}), make(chan struct{})
result := make(chan error, 1)
var once, releaseOnce sync.Once
releaseHold := func() { releaseOnce.Do(func() { close(release) }) }
m.testPublicationAdmission = func(ask authority.AssignmentAsk, next func() error) error {
if ask.VolumeID != "v" {
return next()
}
held := false
once.Do(func() { held = true })
if !held {
return next()
}
defer close(hookDone)
close(entered)
<-release
err := next()
result <- err
return err
}
m.format.v.Store(1)
m.Start()
t.Cleanup(func() { closeTestMaster(t, m) })
// Runs before the master's close (cleanups run last-in first): a
// failure before the release frees the held admission, and its
// return is joined (bounded) so Publisher.Run is never stranded.
t.Cleanup(func() {
releaseHold()
select {
case <-entered:
select {
case <-hookDone:
case <-time.After(10 * time.Second):
t.Error("the held publication admission did not return after its release")
}
default: // the hold was never reached
}
})
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
r := &isolationRig{m: m, logs: logs, ws: control.NewWorkspaceServiceClient(conn), lc: control.NewLifecycleServiceClient(conn), obs: control.NewObservationServiceClient(conn), ctx: ctx}
if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"}); err != nil {
t.Fatal(err)
}
r.createVolume(t, "v")
r.place(t, "v", "node-b")
if _, err := r.obs.ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-b", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 1,
Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302", Incarnation: "new-proc", Reachable: true, Eligible: true}}}); err != nil {
t.Fatal(err)
}
if _, err := m.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
select {
case <-entered:
case <-time.After(20 * time.Second):
t.Fatal("the bind never reached its publication admission")
}
if downgrade {
_ = r.fgProcessHeartbeat("node-b", "old-proc", "other", 0) // refused at level 1, but its level is recorded
}
releaseHold()
var got error
select {
case got = <-result:
case <-time.After(20 * time.Second):
t.Fatal("the held admission never finished")
}
_, bound := m.Publisher().VolumeAuthorityLine("v")
if downgrade && (got == nil || !strings.Contains(got.Error(), "binary_too_old") || bound) {
t.Fatalf("downgrade: admission %v, bound %v; want refused binary_too_old and no line", got, bound)
}
if !downgrade && (got != nil || !bound) {
t.Fatalf("control: admission %v, bound %v; want published", got, bound)
}
})
}
}
@@ -79,29 +79,45 @@ func TestAttestationGoldenFileIsTheV100File(t *testing.T) {
}
}
// Today's store writes the v1.0.0 file's volumes for the same steps, inside
// this version's envelope: {"format":2,"volumes":<the v1.0.0 bytes>}. The
// one change since v1.0.0, by the format path: a v1.0.x master refuses the
// envelope at start (TestAV100MasterRefusesTheAttestationEnvelope).
func TestAttestationsWriteTheV100FileInTheEnvelope(t *testing.T) {
// Until the format finalize (level 0) today's store writes the v1.0.0 file
// itself, byte for byte. The finalize writes this version's envelope around
// the same volumes, {"format":2,"format_level":1,"volumes":<the v1.0.0
// bytes>}: the one change since v1.0.0, by the format path, and a v1.0.x
// master refuses it at start (TestAV100MasterRefusesTheAttestationEnvelope).
func TestAttestationsWriteTheV100FileUntilTheFinalize(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
got, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
want := append(append([]byte(`{"format":2,"volumes":`), readGoldenAttestations(t)...), '}')
if want := readGoldenAttestations(t); !bytes.Equal(got, want) {
t.Fatalf("level 0: %s\n got %s\n want %s", goldenAttestationFix, got, want)
}
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
got, err = os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
want := append(append([]byte(`{"format":2,"format_level":1,"volumes":`), readGoldenAttestations(t)...), '}')
if !bytes.Equal(got, want) {
t.Fatalf("%s\n got %s\n want %s", goldenAttestationFix, got, want)
t.Fatalf("after the finalize: %s\n got %s\n want %s", goldenAttestationFix, got, want)
}
}
// A v1.0.x master decodes store-attestations.json as a bare map of volume
// records (json.Unmarshal into map[string]attestedStores, its
// loadStoreAttestations), and its New returns that error before it listens
// or publishes. The envelope fails that decode; today's master reads both
// forms, and a master started on a v1.0.x store rewrites it as the envelope
// before it serves.
// or publishes. Until the finalize the file is that map, so a v1.0.x master
// starts (going back works); the finalize's envelope fails that decode.
// Today's master reads both forms, and a start (ensureEnvelope) leaves a
// v1.0.x store in its form.
func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
@@ -110,39 +126,38 @@ func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) {
t.Fatal(err)
}
var v100 map[string]attestedStores // v1.0.x's decode, verbatim
if err := json.Unmarshal(b, &v100); err == nil {
t.Fatalf("a v1.0.x master's decode accepted the file written now: %v", v100)
if err := json.Unmarshal(b, &v100); err != nil {
t.Fatalf("level 0: a v1.0.x master's decode refused the file written now: %v", err)
}
if bad := readAttestations(dir); len(bad) != 0 {
t.Fatalf("today's master does not read its own envelope: %v", bad)
}
// A v1.0.x store (the bare map) is read, and ensureEnvelope rewrites it.
old := t.TempDir()
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
t.Fatal(err)
}
s, err := loadStoreAttestations(old)
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if bad := readAttestations(old); len(bad) != 0 {
t.Fatalf("today's master does not read the v1.0.x form: %v", bad)
}
if err := s.ensureEnvelope(); err != nil {
t.Fatal(err)
}
b, err = os.ReadFile(filepath.Join(old, storeAttestationFile))
if after, _ := os.ReadFile(filepath.Join(dir, storeAttestationFile)); !bytes.Equal(after, b) {
t.Fatalf("a level-0 start rewrote the v1.0.x file: %s", after)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
b, err = os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
v100 = nil
if err := json.Unmarshal(b, &v100); err == nil {
t.Fatal("after ensureEnvelope, a v1.0.x master's decode still accepts the store")
t.Fatalf("after the finalize, a v1.0.x master's decode accepted the file: %v", v100)
}
if bad := readAttestations(dir); len(bad) != 0 {
t.Fatalf("today's master does not read its own envelope: %v", bad)
}
// An envelope of a later format is refused by this master too.
if err := os.WriteFile(filepath.Join(old, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := loadStoreAttestations(old); err == nil {
if _, err := loadStoreAttestations(dir); err == nil {
t.Fatal("this master accepted attestation format 3")
}
}
@@ -243,10 +258,11 @@ func TestAttestationEnvelopeNeedsItsVolumesObject(t *testing.T) {
}
}
// An envelope already on disk is fsynced again (file and directory) on every
// start: a start that renamed it in and then failed its directory fsync must
// not leave the next start serving on an envelope that may not survive a
// crash.
// The finalize's envelope write fails when its directory fsync fails, and
// an envelope already on disk is fsynced again (file and directory) on every
// start: a finalize (or start) that renamed it in and then failed its
// directory fsync must not leave the next start serving on an envelope that
// may not survive a crash.
func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil {
@@ -260,8 +276,8 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := s.ensureEnvelope(); err == nil {
t.Fatal("a failed directory fsync of the first envelope write was not an error (the master would serve)")
if _, err := s.finalize(); err == nil || s.level() != 0 {
t.Fatalf("a failed directory fsync of the finalize's envelope: err=%v level=%d (want an error, level 0)", err, s.level())
}
// The process restarts: the envelope is on disk (the rename happened).
s, err = loadStoreAttestations(dir)
@@ -284,11 +300,18 @@ func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) {
func TestAttestationEnvelopeRoundTrips(t *testing.T) {
dir := t.TempDir()
goldenAttestations(t, dir)
s, err := loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
first, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil {
t.Fatal(err)
}
s, err := loadStoreAttestations(dir)
s, err = loadStoreAttestations(dir)
if err != nil {
t.Fatal(err)
}
@@ -304,14 +327,19 @@ func TestAttestationEnvelopeRoundTrips(t *testing.T) {
}
}
// master.New refuses to serve when the attestation envelope cannot be made
// durable: it returns the error before it listens.
// master.New at level 1 refuses to serve when the attestation envelope
// cannot be made durable: it returns the error before it listens.
func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(`{"format":2,"format_level":1,"volumes":{}}`), 0o644); err != nil {
t.Fatal(err)
}
saved := syncAttestationDir
t.Cleanup(func() { syncAttestationDir = saved })
syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") }
h, err := New(Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"})
h, err := New(Config{AuthorityStoreDir: dir, Listen: "127.0.0.1:0"})
if err == nil {
h.Start()
closeTestMaster(t, h)
t.Fatal("master.New served with a failed attestation envelope fsync")
}
@@ -320,8 +348,9 @@ func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) {
}
}
// A v1.0.x file that is null holds no attestations (as v1.0.x read it): it
// migrates to an envelope with an explicit {} that the next start reads.
// A v1.0.x file that is null holds no attestations (as v1.0.x read it); a
// level-0 start leaves it as it is, and the finalize writes an envelope
// with an explicit {} that the next start reads.
func TestAV100NullAttestationFileMigrates(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte("null"), 0o644); err != nil {
@@ -334,11 +363,17 @@ func TestAV100NullAttestationFileMigrates(t *testing.T) {
if err := s.ensureEnvelope(); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(filepath.Join(dir, storeAttestationFile)); string(b) != "null" {
t.Fatalf("a level-0 start rewrote the null file: %s", b)
}
if _, err := s.finalize(); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile))
if err != nil || string(b) != `{"format":2,"volumes":{}}` {
t.Fatalf("migrated to %s (%v)", b, err)
if err != nil || string(b) != `{"format":2,"format_level":1,"volumes":{}}` {
t.Fatalf("finalized to %s (%v)", b, err)
}
if _, err := loadStoreAttestations(dir); err != nil {
t.Fatalf("the next start refuses the migrated file: %v", err)
t.Fatalf("the next start refuses the finalized file: %v", err)
}
}
+18 -5
View File
@@ -152,9 +152,15 @@ type Host struct {
statusLn net.Listener
statusHTTP *http.Server
journal *journalIsolation
grpc *grpc.Server
topo authority.AcceptedTopology
lifecycle *LifecycleStores
reads *readsLevels // each server's reported format read level (format_gate.go)
format formatLevelState // the cluster's format level (format_gate.go)
finalizeMu sync.Mutex // serializes the format finalize and host retires (format_gate.go)
// testPublicationAdmission, when a test sets it before Start, wraps each
// publication admission: next runs the admission itself.
testPublicationAdmission func(ask authority.AssignmentAsk, next func() error) error
grpc *grpc.Server
topo authority.AcceptedTopology
lifecycle *LifecycleStores
// RPC registration/place/move/ACK/delete and product ticks serialize here.
// Order: workspaceMu -> publisher or lifecycle store locks (not reversed).
workspaceMu sync.Mutex
@@ -267,6 +273,7 @@ func New(cfg Config) (*Host, error) {
topo: cfg.Topology,
events: newEventRing(1024),
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
reads: newReadsLevels(cfg.Freshness.EffectiveFreshnessWindow()),
}
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
@@ -287,12 +294,16 @@ func New(cfg Config) (*Host, error) {
return nil, fmt.Errorf("master.New: %w", err)
}
// Under the authority store's lock and before anything is served: the
// attestation file in this version's envelope, which a v1.0.x master
// refuses at start (store_attestation.go).
// cluster's format level is the attestation file's form (the envelope
// is level 1, re-fsynced here; v1.0.x's form is level 0, where this
// master keeps v1.0's semantics: store_attestation.go, format_gate.go).
if err := h.attest.ensureEnvelope(); err != nil {
_ = boot.Close()
return nil, fmt.Errorf("master.New: %w", err)
}
level := h.attest.level()
boot.Publisher.SetFormatLevelBeforeServing(level)
h.format.v.Store(level)
var sink authority.ControllerSink = ctrl
if len(cfg.Topology.Volumes) == 0 {
@@ -638,6 +649,8 @@ func (h *Host) Close(ctx context.Context) error {
}
h.wg.Wait()
// Level 0's horizon extenders write through the store: join them first.
h.boot.Publisher.CloseWorkspaceExtenders()
return errors.Join(statusErr, h.boot.Close())
}
@@ -1,6 +1,7 @@
package master
import (
"sort"
"encoding/json"
"fmt"
"net"
@@ -73,19 +74,25 @@ func (j *journalIsolation) setSelf(id storeident.Identity) {
// takes neither workspaceMu nor the publisher lock (held across authority
// store writes), only the published authority lines and the lifecycle
// stores, whose locks cover only their own file I/O.
func (h *Host) nodeServesVolumes(server string) bool {
func (h *Host) nodeServesVolumes(server string) bool { return len(h.volumesServedBy(server)) > 0 }
// volumesServedBy names, sorted and once each, every volume server holds
// work for: a placement slot (also every line it sources), a live line a
// move issued to it, or a static topology line on it.
func (h *Host) volumesServedBy(server string) []string {
seen := map[string]bool{}
lines := h.Publisher().PublishedAuthorityLines()
if h.lifecycle != nil {
for _, p := range h.lifecycle.Placements.ListPlacements() {
for _, slot := range p.Slots {
if slot.ServerID == server {
return true // also every line a placement slot sources
seen[p.VolumeID] = true
}
}
}
for volume, line := range lines {
if _, live := h.lifecycle.Volumes.GetVolumeSnapshot(volume); live && line.IssuedHost == server {
return true
seen[volume] = true
}
}
}
@@ -96,11 +103,16 @@ func (h *Host) nodeServesVolumes(server string) bool {
}
for _, slot := range v.Slots {
if slot.ServerID == server && slot.ReplicaID == line.ReplicaID {
return true
seen[v.VolumeID] = true
}
}
}
return false
out := make([]string, 0, len(seen))
for v := range seen {
out = append(out, v)
}
sort.Strings(out)
return out
}
// refuseColocatedHeartbeat is the strict heartbeat rule: a co-located node
@@ -122,13 +134,21 @@ func (h *Host) colocatedTargetRefused(server string) bool {
return h.cfg.StrictJournalIsolation && h.journal.isColocated(server)
}
// reconcilePlacements runs the product loop's placement reconcile. Under
// strict isolation each volume plans against the nodes without co-located
// ones, except the nodes its existing placement already names: a placement
// on a co-located node is kept (re-planning it away would move a serving
// volume), and no new placement chooses a co-located node.
// newWorkRefused reports whether server may not be given new work: strict
// isolation refuses a co-located node, and the format gate a node whose
// binary does not read the cluster's format level.
func (h *Host) newWorkRefused(server string) bool {
return h.colocatedTargetRefused(server) || !h.formatEligible(server)
}
// reconcilePlacements runs the product loop's placement reconcile. Each
// volume plans against the nodes new work may go to (newWorkRefused: not
// co-located under strict isolation, reading the cluster's format level),
// plus the nodes its existing placement already names: such a placement is
// kept (re-planning it away would move a serving volume), and no new
// placement chooses a refused node.
func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.NodeRegistration) []lifecycle.ReconcileResult {
if !h.cfg.StrictJournalIsolation {
if !h.cfg.StrictJournalIsolation && h.formatLevel() == 0 {
return lifecycle.ReconcilePlacement(h.readyVolumeRecords(stores.liveVolumes()), nodes, stores.Placements)
}
var out []lifecycle.ReconcileResult
@@ -141,7 +161,7 @@ func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.No
}
allowed := make([]lifecycle.NodeRegistration, 0, len(nodes))
for _, n := range nodes {
if placed[n.ServerID] || !h.journal.isColocated(n.ServerID) {
if placed[n.ServerID] || !h.newWorkRefused(n.ServerID) {
allowed = append(allowed, n)
}
}
@@ -30,7 +30,7 @@ func TestLayoutStoreReadyDecisionSites(t *testing.T) {
"product_loop.go submitPlacementSnapshots readyPlacements": 1,
"workspace_binding.go PlaceWorkspace workspaceVolume": 1,
"workspace_binding.go RegisterWorkspaceBinding workspaceVolume": 1,
"workspace_binding.go admitWorkspacePublication layoutStoreReady": 1,
"workspace_binding.go admitWorkspacePublicationNow layoutStoreReady": 1,
"workspace_service.go AckWorkspaceRevoked workspaceVolume": 1,
"workspace_service.go MoveWorkspace MoveWorkspace": 1,
"workspace_service.go MoveWorkspace workspaceVolume": 2,
@@ -304,7 +304,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
h.holdCreating(vol, why)
continue
}
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex)
currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) && h.formatEligible(vol.Slots[currentIdx].ServerID)
// A fencing round fenced survivors above this line and nothing was
// published: they refuse the primary at its epoch (and may no longer
// look ready), so heal before anything else while it is acceptable.
@@ -319,7 +319,7 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
for _, slot := range vol.Slots {
if slot.ReplicaID != vol.Authority.ReplicaID {
candidates = append(candidates, slot)
if candidateAcceptableForPromotionGate(slot, serverIndex) {
if candidateAcceptableForPromotionGate(slot, serverIndex) && h.formatEligible(slot.ServerID) {
readyCandidate = true
}
}
@@ -537,6 +537,15 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
if err := s.host.refuseServerIDFromOtherHost(r); err != nil {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
// The format gate: the reporting process's read level, recorded before
// it is judged (its server then reads at most that level for new work);
// a process whose binary cannot read the cluster's format level is
// refused, so it is never observed as a candidate.
s.host.reads.noteHeartbeat(r.GetServerId(), r.GetSlots(), r.GetReadsLevel())
if level := s.host.formatLevel(); r.GetReadsLevel() < level {
why := fmt.Sprintf("node %q process reads format level %d; the cluster's format level is %d (binary_too_old)", r.GetServerId(), r.GetReadsLevel(), level)
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "heartbeat refused: "+why), lifecycleclient.ReasonBinaryTooOld).Err()
}
msg := heartbeatFromWire(r)
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
return nil, fmt.Errorf("ingest: %w", err)
@@ -1266,6 +1275,7 @@ func (s *services) assignmentFact(info adapter.AssignmentInfo) *control.Assignme
EvidenceFirstLsn: info.Primary.DataFirstLSN,
LineIncarnation: info.Incarnation,
AckProfile: s.host.lineAckProfile(),
FormatLevel: s.host.formatLevel(),
}
if info.Primary.StoreID != ([16]byte{}) {
id := info.Primary.StoreID
@@ -1,6 +1,7 @@
package master
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
@@ -19,17 +20,19 @@ import (
// write (temp file, fsync, rename, directory fsync).
const storeAttestationFile = "store-attestations.json"
// storeAttestationFormat is the envelope this master writes:
// {"format": 2, "volumes": {...}}. A v1.0.x master decodes the file as a
// bare map of volume records, so the number under "format" fails its whole
// start (before any listener or authority publication): the downgrade guard
// for what this version stops keeping current (the lease horizon). The
// bare map (v1.0.x's form) is still read.
// storeAttestationFormat is the envelope the format finalize writes:
// {"format": 2, "format_level": 1, "volumes": {...}}. The file's form IS the
// cluster's format level: v1.0.x's bare map is level 0, the envelope level
// 1. A v1.0.x master decodes the file as a bare map of volume records, so
// the number under "format" fails its whole start (before any listener or
// authority publication): the finalize's one durable write raises the level
// and fences v1.0.x masters together.
const storeAttestationFormat = 2
type storeAttestationEnvelope struct {
Format int `json:"format"`
Volumes map[string]attestedStores `json:"volumes"`
Format int `json:"format"`
FormatLevel int `json:"format_level"`
Volumes map[string]attestedStores `json:"volumes"`
}
// attestedStores is one volume's last attestation: the primary line that
@@ -68,8 +71,8 @@ type storeAttestations struct {
mu sync.Mutex
path string // "" = memory only
vols map[string]attestedStores
// enveloped: the file on disk is this version's envelope (persist always
// writes it; ensureEnvelope writes it at start).
// enveloped: the file on disk is the envelope, so the cluster's format
// level is 1 (persist then keeps that form; finalize writes it first).
enveloped bool
// changed[vol] is closed (and dropped) when vol's record changes.
changed map[string]chan struct{}
@@ -119,6 +122,12 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error)
if env.Volumes == nil {
return nil, false, fmt.Errorf("format %d without a volumes object", format)
}
// format_level is 1 (an envelope written before the level was
// recorded in it says nothing, and is level 1 too); anything else
// is refused: the level never drops.
if lv, ok := probe["format_level"]; ok && string(bytes.TrimSpace(lv)) != "1" {
return nil, false, fmt.Errorf("format %d with format_level %s, this master reads level 1", format, bytes.TrimSpace(lv))
}
return env.Volumes, true, nil
}
}
@@ -134,23 +143,44 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error)
return vols, false, nil
}
// ensureEnvelope makes the file in this version's envelope durable before
// the master serves anything, so a v1.0.x master started on this store
// afterwards refuses its whole start: it writes the envelope when the file is
// absent or in v1.0.x's form, and fsyncs an envelope already there (file and
// directory) on every start, since an earlier start may have renamed it in
// and then failed its directory fsync.
// level is the cluster's format level the file holds: 1 with the envelope,
// 0 with v1.0.x's form (or no file).
func (s *storeAttestations) level() uint32 {
s.mu.Lock()
defer s.mu.Unlock()
if s.enveloped {
return 1
}
return 0
}
// finalize writes the envelope durably (file and directory fsync): the one
// write that raises the cluster's format level to 1 and makes a v1.0.x
// master refuse this store. At level 1 it writes nothing (already true).
// On a failed write the level stays 0 in memory; the file may hold either
// form, and the next start reads whichever it holds.
func (s *storeAttestations) finalize() (already bool, err error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.enveloped {
return true, nil
}
s.enveloped = true
if err := s.persist(s.vols); err != nil {
s.enveloped = false
return false, err
}
return false, nil
}
// ensureEnvelope, at level 1, fsyncs the envelope (file and directory) at
// every start before the master serves anything, since an earlier start (or
// the finalize) may have renamed it in and then failed its directory fsync.
// At level 0 it does nothing: the file stays v1.0.x's form.
func (s *storeAttestations) ensureEnvelope() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.path == "" {
return nil
}
if !s.enveloped {
if err := s.persist(s.vols); err != nil {
return err
}
s.enveloped = true
if s.path == "" || !s.enveloped {
return nil
}
f, err := os.OpenFile(s.path, os.O_RDWR, 0)
@@ -437,7 +467,16 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error {
if s.path == "" {
return nil
}
payload, err := json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, Volumes: vols})
if vols == nil {
vols = map[string]attestedStores{}
}
var payload []byte
var err error
if s.enveloped {
payload, err = json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, FormatLevel: 1, Volumes: vols})
} else {
payload, err = json.Marshal(vols) // level 0: v1.0.x's form
}
if err != nil {
return err
}
@@ -220,6 +220,11 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) && s.host.colocatedTargetRefused(binding.ServerID) {
return nil, workspaceError(fmt.Errorf("workspace placement: node %q shares the authority store's file system (strict journal isolation)", binding.ServerID))
}
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) {
if why := s.host.formatTooOld(binding.ServerID); why != "" {
return nil, workspaceError(fmt.Errorf("workspace placement: %s", why))
}
}
err = s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error {
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok {
if identical(p) {
@@ -244,6 +249,14 @@ 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 {
if hook := h.testPublicationAdmission; hook != nil {
return hook(ask, func() error { return h.admitWorkspacePublicationNow(ask, publish) })
}
return h.admitWorkspacePublicationNow(ask, publish)
}
// admitWorkspacePublicationNow is the publication admission itself.
func (h *Host) admitWorkspacePublicationNow(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 {
@@ -272,6 +285,11 @@ func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish fu
epoch = line.Epoch
}
server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch)
// The format gate at the last boundary: an ask decided on observations
// taken before its server reported a lower read level is not published.
if why := h.formatTooOld(server); why != "" {
return fmt.Errorf("workspace publication: %s", why)
}
b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}
if bound {
matched := false
@@ -86,15 +86,16 @@ func TestLeaseRefusalKinds(t *testing.T) {
t.Fatal("first grant:", err)
}
// BARRIER: past the grant (TTL, 30 s) but before it plus the default
// skew (2/3 TTL), i.e. 50 s after the grant.
// BARRIER: past the grant (TTL, 30 s) but before the barrier. A fresh
// master is at format level 0, whose barrier is v1.0's: the persisted
// horizon (1.5 TTL) plus the default skew (2/3 TTL), 65 s after the grant.
nowNS.Add(int64(40 * time.Second))
text, r := refusalOf(t, "expired re-grant before the barrier", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }())
if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_BARRIER {
t.Fatalf("re-grant before the barrier: detail %v; want BARRIER", r)
}
if left := time.Duration(r.GetRetryAfterNs()); left < 9*time.Second || left > 11*time.Second {
t.Fatalf("BARRIER retry_after %v; want 10 s (the barrier 50 s after the grant, now +40 s)", left)
if left := time.Duration(r.GetRetryAfterNs()); left < 24*time.Second || left > 26*time.Second {
t.Fatalf("BARRIER retry_after %v; want 25 s (level 0: the barrier 65 s after the grant, now +40 s)", left)
}
if !strings.HasPrefix(text, "workspace forced move lease expiry plus clock-skew margin has not elapsed") || !strings.Contains(text, "re-grant refused until") {
t.Fatalf("BARRIER text %q: want the barrier text with its time", text)
@@ -455,6 +455,8 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho
// after these endpoint and binding checks, also for a same-host target.
case !replay && s.host.colocatedTargetRefused(target.ServerID):
refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
case !replay && s.host.formatTooOld(target.ServerID) != "":
refusal = "move target " + s.host.formatTooOld(target.ServerID)
case !matched:
refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
}
@@ -35,7 +35,8 @@ func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChun
// then) and is granted on the predecessor's unchanged HEAD. A late claim by
// the dead grantee never displaces the new owner's higher epoch.
func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
// The real lease (the 30 s TTL) plus skew takes ~50 s.
// The real lease horizon (1.5 x the 30 s TTL, format level 0) plus skew
// takes ~65 s.
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
defer cancel()
remote := storage.NewMemChunkRemote()
@@ -114,8 +115,10 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) {
if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking {
t.Fatalf("the issued move must start node-b's lease: %+v", st)
}
granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a") // the issue's deadline, not the record's
barrier := time.Unix(0, granted.ExpiresAtNS).Add(skew)
// The barrier at either format level: the later of the granted deadline
// and (level 0, v1.0's rule) the persisted horizon, plus skew.
granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a")
barrier := time.Unix(0, max(granted.ExpiresAtNS, st.Lease.ExpiresAtNS)).Add(skew)
if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee {
t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err)
}
+6
View File
@@ -810,6 +810,11 @@ func (h *Host) runHeartbeat(ctx context.Context) {
}
}
// ReadsFormatLevel is the highest cluster format level this binary reads
// (the v1.1 format is level 1), reported on every heartbeat as reads_level:
// the master finalizes the format only when every registered host reads it.
const ReadsFormatLevel = 1
// buildReport collects local slot facts into a wire HeartbeatReport.
// T0 single-volume-per-process simplicity: one replica slot.
func (h *Host) buildReport() *control.HeartbeatReport {
@@ -825,6 +830,7 @@ func (h *Host) buildReport() *control.HeartbeatReport {
DurableRootDev: h.cfg.StorageIdentity.Dev,
DurableRootFsid: h.cfg.StorageIdentity.FSID,
StoreAttestation: h.storeAttestation(),
ReadsLevel: ReadsFormatLevel,
Slots: []*control.HeartbeatSlot{
{
VolumeId: h.cfg.VolumeID,
File diff suppressed because it is too large. Load diff
@@ -790,6 +790,8 @@ const (
LifecycleService_CommitVolumeDeleting_FullMethodName = "/seaweedfs.block.control.LifecycleService/CommitVolumeDeleting"
LifecycleService_ReserveVolumeDeletion_FullMethodName = "/seaweedfs.block.control.LifecycleService/ReserveVolumeDeletion"
LifecycleService_CheckVolumeNoLiveLease_FullMethodName = "/seaweedfs.block.control.LifecycleService/CheckVolumeNoLiveLease"
LifecycleService_FinalizeFormat_FullMethodName = "/seaweedfs.block.control.LifecycleService/FinalizeFormat"
LifecycleService_RetireHost_FullMethodName = "/seaweedfs.block.control.LifecycleService/RetireHost"
)
// LifecycleServiceClient is the client API for LifecycleService service.
@@ -821,6 +823,20 @@ type LifecycleServiceClient interface {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
CheckVolumeNoLiveLease(ctx context.Context, in *MarkVolumeDeletingRequest, opts ...grpc.CallOption) (*MarkVolumeDeletingResponse, error)
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
FinalizeFormat(ctx context.Context, in *FinalizeFormatRequest, opts ...grpc.CallOption) (*FinalizeFormatResponse, error)
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
RetireHost(ctx context.Context, in *RetireHostRequest, opts ...grpc.CallOption) (*RetireHostResponse, error)
}
type lifecycleServiceClient struct {
@@ -903,6 +919,24 @@ func (c *lifecycleServiceClient) CheckVolumeNoLiveLease(ctx context.Context, in
return out, nil
}
func (c *lifecycleServiceClient) FinalizeFormat(ctx context.Context, in *FinalizeFormatRequest, opts ...grpc.CallOption) (*FinalizeFormatResponse, error) {
out := new(FinalizeFormatResponse)
err := c.cc.Invoke(ctx, LifecycleService_FinalizeFormat_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *lifecycleServiceClient) RetireHost(ctx context.Context, in *RetireHostRequest, opts ...grpc.CallOption) (*RetireHostResponse, error) {
out := new(RetireHostResponse)
err := c.cc.Invoke(ctx, LifecycleService_RetireHost_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LifecycleServiceServer is the server API for LifecycleService service.
// All implementations must embed UnimplementedLifecycleServiceServer
// for forward compatibility
@@ -932,6 +966,20 @@ type LifecycleServiceServer interface {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error)
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
FinalizeFormat(context.Context, *FinalizeFormatRequest) (*FinalizeFormatResponse, error)
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
RetireHost(context.Context, *RetireHostRequest) (*RetireHostResponse, error)
mustEmbedUnimplementedLifecycleServiceServer()
}
@@ -963,6 +1011,12 @@ func (UnimplementedLifecycleServiceServer) ReserveVolumeDeletion(context.Context
func (UnimplementedLifecycleServiceServer) CheckVolumeNoLiveLease(context.Context, *MarkVolumeDeletingRequest) (*MarkVolumeDeletingResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CheckVolumeNoLiveLease not implemented")
}
func (UnimplementedLifecycleServiceServer) FinalizeFormat(context.Context, *FinalizeFormatRequest) (*FinalizeFormatResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method FinalizeFormat not implemented")
}
func (UnimplementedLifecycleServiceServer) RetireHost(context.Context, *RetireHostRequest) (*RetireHostResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RetireHost not implemented")
}
func (UnimplementedLifecycleServiceServer) mustEmbedUnimplementedLifecycleServiceServer() {}
// UnsafeLifecycleServiceServer may be embedded to opt out of forward compatibility for this service.
@@ -1120,6 +1174,42 @@ func _LifecycleService_CheckVolumeNoLiveLease_Handler(srv interface{}, ctx conte
return interceptor(ctx, in, info, handler)
}
func _LifecycleService_FinalizeFormat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FinalizeFormatRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LifecycleServiceServer).FinalizeFormat(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: LifecycleService_FinalizeFormat_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LifecycleServiceServer).FinalizeFormat(ctx, req.(*FinalizeFormatRequest))
}
return interceptor(ctx, in, info, handler)
}
func _LifecycleService_RetireHost_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetireHostRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LifecycleServiceServer).RetireHost(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: LifecycleService_RetireHost_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LifecycleServiceServer).RetireHost(ctx, req.(*RetireHostRequest))
}
return interceptor(ctx, in, info, handler)
}
// LifecycleService_ServiceDesc is the grpc.ServiceDesc for LifecycleService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -1159,6 +1249,14 @@ var LifecycleService_ServiceDesc = grpc.ServiceDesc{
MethodName: "CheckVolumeNoLiveLease",
Handler: _LifecycleService_CheckVolumeNoLiveLease_Handler,
},
{
MethodName: "FinalizeFormat",
Handler: _LifecycleService_FinalizeFormat_Handler,
},
{
MethodName: "RetireHost",
Handler: _LifecycleService_RetireHost_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "control.proto",
@@ -16,6 +16,16 @@ const (
// names chunks of a volume other than its source (a restore target's
// snapshot cannot be restored again).
ReasonRestoreSourceNotOwn = "RESTORE_SOURCE_NOT_OWN"
// ReasonBinaryTooOld: the caller's binary does not read the cluster's
// format level (its heartbeat's reads_level is below it), so the master
// refuses it and gives it no work.
ReasonBinaryTooOld = "BINARY_TOO_OLD"
// ReasonFormatHostsTooOld: the format finalize was refused because a
// registered host has not reported that it reads the new level.
ReasonFormatHostsTooOld = "FORMAT_HOSTS_TOO_OLD"
// ReasonHostHoldsWork: a host retire was refused because the host still
// holds a lease or an assignment for a volume.
ReasonHostHoldsWork = "HOST_HOLDS_WORK"
)
// WithReason returns st with an ErrorInfo detail carrying reason in
@@ -119,6 +119,38 @@ service LifecycleService {
// HEAD read and its update: OK only with the committed reservation and
// no live lease on any line of the volume (granted lines included).
rpc CheckVolumeNoLiveLease(MarkVolumeDeletingRequest) returns (MarkVolumeDeletingResponse);
// FinalizeFormat raises the cluster's format level to 1 (the v1.1
// format), durably and one-way: a v1.0.x master refuses the store from
// then on, and holders may upgrade. Refused (FAILED_PRECONDITION, reason
// FORMAT_HOSTS_TOO_OLD) while any registered host has not reported
// reads_level >= 1 since the master started; the refusal names each one.
// At level 1 it succeeds without writing.
rpc FinalizeFormat(FinalizeFormatRequest) returns (FinalizeFormatResponse);
// RetireHost removes a registered host from the node inventory, so it no
// longer counts for the format finalize or for placement. Refused
// (FAILED_PRECONDITION, reason HOST_HOLDS_WORK) while the host holds a
// lease or an assignment for any volume; the refusal names them. confirm
// must repeat server_id. A retired host that returns registers again and
// is judged at its reported read level.
rpc RetireHost(RetireHostRequest) returns (RetireHostResponse);
}
message FinalizeFormatRequest {
uint32 level = 1; // the level to finalize: 1
}
message FinalizeFormatResponse {
uint32 format_level = 1;
bool already = 2; // the cluster was already at this level: nothing written
}
message RetireHostRequest {
string server_id = 1;
string confirm = 2; // must equal server_id
}
message RetireHostResponse {
string server_id = 1;
}
// FailbackService — disabled-by-default authority failback endpoint.
@@ -156,6 +188,12 @@ message HeartbeatReport {
// the server that holds the volume's current primary line at that
// epoch. A replica's own report of its store never sets it.
StoreAttestation store_attestation = 9;
// reads_level is the highest cluster format level the reporting
// binary reads: 1 for a binary that reads the v1.1 format. A v1.0.x
// binary sends none (0). The master finalizes the cluster's format only
// when every registered host reports at least the new level, and places,
// moves and fails volumes over only to hosts that read the current one.
uint32 reads_level = 10;
}
// StoreAttestation is a primary's attestation of its write-ACK set at one
@@ -329,6 +367,11 @@ message AssignmentFact {
// is another one does not serve: a later failover reads its
// acknowledged writes by this profile's rules.
string ack_profile = 18;
// The cluster's format level (0 until the operator finalizes the v1.1
// format, then 1). A holder upgrades a store and writes the v1.1 format
// only at level 1; absent (an older master, or no assignment yet) means
// level 0.
uint32 format_level = 19;
}
// PrimaryKind is how a line made its primary the primary.
+7 -2
View File
@@ -821,8 +821,13 @@ Notes:
| `INV-WS-LEASE-HORIZON-001` | Retired: v1.1 keeps no lease horizon current; renewals write nothing and a restarted master waits for its own restart floor (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
| `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED |
| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE |
| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL, own monotonic clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
| `INV-WS-AUTH-RECORD-V2-001` | Before it serves, this master writes the store's attestation file as format 2, on which a v1.0.x master refuses its whole start; its authority records are envelope version 2 (a v1.0.x master would skip them). It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileInTheEnvelope`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
| `INV-WS-RESTART-GRACE-001` | At format level 1, a renewal writes nothing durable. A forced move, an expired re-grant and a no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE |
| `INV-WS-AUTH-RECORD-V2-001` | The format finalize writes the store's attestation file as format 2 (`INV-FMT-LEVEL-001`), on which a v1.0.x master refuses its whole start; from then on its authority records are envelope version 2 (a v1.0.x master would skip them); before it, both are v1.0's. It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE |
| `INV-FMT-LEVEL-001` | The cluster's format level is the attestation file's form: v1.0.x's bare map is level 0, the envelope (format 2, format_level 1) level 1. It only rises: the finalize is its only writer, and an envelope below level 1 is refused at start. | FormatGate Finalize (level 0 → 1) | `core/host/master/store_attestation.go` `decodeStoreAttestations`, `finalize`, `persist`, `level`; `core/host/master/host.go` `New` | `TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable`, `TestAnAttestationEnvelopeBelowLevel1IsRefused` (`core/host/master/format_gate_test.go`); `TestAttestationsWriteTheV100FileUntilTheFinalize`, `TestAV100MasterRefusesTheAttestationEnvelope` (`core/host/master/golden_v100_test.go`) | `FormatGate` `OneWay` (mutation `level_lowered`) | ACTIVE |
| `INV-FMT-FINALIZE-001` | The finalize is refused, naming them, while a registered host has not reported reads_level >= 1 since the master started. Else it writes the envelope durably, then switches the publisher under both its locks, then answers; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `belowLevel`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable`, `TestAFailedFinalizeWriteLeavesLevel0` (`core/host/master/format_gate_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE |
| `INV-FMT-ELIGIBLE-001` | At format level L no new work goes to a server that reads below L or has not reported: no placement, workspace placement or move target, and its heartbeat is refused binary_too_old. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRefusesAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE |
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
+15
View File
@@ -30,3 +30,18 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
created with, and v1.1's differ. Upgrade such a host whole: stop every process using the directory, remove
`<dir>/configuration.json`, then start them all on v1.1. Until then a new process refuses the directory, naming the
file and this cure, and a host that mixes old and new processes skips background cuts with an alarm.
- **The v1.1 format is switched on by the operator, and going back works until then.** v1.1 keeps writing the v1.0
format, and blockmaster keeps v1.0's lease semantics, until `sw-block cluster finalize-format --master <addr>`. Each
host reports the format its binary reads; the finalize refuses while a registered host has not reported that it
reads v1.1, and names each one: upgrade it, or retire it (`sw-block cluster retire-host --server <id> --confirm <id>
--master <addr>`, refused while the host still holds a volume).
- Before the finalize, going back to v1.0.x works: stop the v1.1 binaries and start v1.0.x. Name-only snapshot
deletes keep v1.0's semantics until then (a retry after a lost answer may act twice).
- The finalize is one-way. Afterwards a v1.0.x blockmaster refuses to start on the store, and a v1.0.x holder that
meets a volume v1.1 has opened refuses it and writes nothing to it, but exits with a status its systemd unit
treats as retryable, so the unit restarts it until its start limit. With its local store it answers `invalid
superblock`; without one, `HEAD written by a newer version` (v1.0.0 and v1.0.1 report that HEAD as malformed).
None of these means damage: do not rebuild the volume; start v1.1 again.
- After the finalize, a host whose binary does not read v1.1 is refused (`binary_too_old`) and gets no volume.
- v1.1 answers the reverse case, a store or HEAD written by a later version, with a final exit 78
(`store_format_newer`, `head_newer_version`), which the unit does not restart.