Merge pull request #640 from seaweedfs/test/known-zero-current-cli

test: the process-level tests run the current CLI
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-26 10:15:23 -08:00
commit f08aa2c128
37 files changed
+1822 -1003

No files matched your search

@@ -59,11 +59,7 @@ func TestCutoverWriteSnapshotKillRestartRestore(t *testing.T) {
func startCutoverLayoutEnv(t *testing.T, precreateTarget bool) *handoffEnv {
t.Helper()
var tlsCfg map[string]time.Time
if procedureTLSOn() {
tlsCfg = map[string]time.Time{}
}
return startHandoffEnvConfigured(t, 1, []string{"v2"}, tlsCfg, precreateTarget)
return startHandoffEnvConfigured(t, 1, []string{"v2"}, procedureTLSConfig(), precreateTarget)
}
func startCutoverVolume(t *testing.T, env *handoffEnv, label, host string) *daemon {
@@ -0,0 +1,54 @@
package main_test
import (
"errors"
"fmt"
"testing"
)
// fillProgress is what a test knows about a running fill: the absent chunk
// count when its reader started, the count now, and the reader's state.
type fillProgress struct {
baseline, absent int
reads int64
readerErr error
finished bool
}
// fillWitness is nil only while a fill is observably running: the reader
// has completed a read without error and has not finished, the absent
// count fell below its value when the reader started, and work remains.
// Remaining work alone does not show a fill is running.
func fillWitness(p fillProgress) error {
switch {
case p.readerErr != nil:
return fmt.Errorf("the reader failed: %w", p.readerErr)
case p.reads == 0:
return errors.New("the reader has completed no read")
case p.finished:
return errors.New("the reader finished: no fill left to interrupt")
case p.absent >= p.baseline:
return fmt.Errorf("no chunk was made local since the reader started (%d absent, %d at its start)", p.absent, p.baseline)
case p.absent == 0:
return errors.New("every chunk is local: no fill left to interrupt")
}
return nil
}
func TestFillWitnessNeedsAnObservedRunningFill(t *testing.T) {
running := fillProgress{baseline: 16, absent: 12, reads: 3}
if err := fillWitness(running); err != nil {
t.Fatalf("a running fill: %v", err)
}
for name, p := range map[string]fillProgress{
"reader never started": {baseline: 16, absent: 16},
"reader failed": {baseline: 16, absent: 12, reads: 3, readerErr: errors.New("read: i/o timeout")},
"reader finished": {baseline: 16, absent: 12, reads: 8, finished: true},
"no progress": {baseline: 16, absent: 16, reads: 3},
"nothing left": {baseline: 16, absent: 0, reads: 16},
} {
if err := fillWitness(p); err == nil {
t.Errorf("%s: %+v accepted as a running fill", name, p)
}
}
}
@@ -21,7 +21,7 @@ import (
// a right-flag start on the same root then fails on the leftover store.
func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
b := env.hosts["n-v2"]
args := append([]string{}, env.volArgsFor(b)...)
@@ -70,7 +70,7 @@ func TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
// cannot deliver the record is the retryable case, 75: the unit test.)
func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
b := env.hosts["n-v2"]
right := append([]string{}, env.volArgsFor(b)...)
@@ -121,7 +121,7 @@ func TestCorruptRecordIsRefusedBeforeTheStoreIsCreated(t *testing.T) {
// check (exit 1) before the record check and before any store exists.
func TestFirstStartWithTheFilerDownCreatesNoStore(t *testing.T) {
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
b := env.hosts["n-v2"]
env.cluster.stopProc(t, "filer")
@@ -0,0 +1,76 @@
package main_test
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// handoffHeadJSON adapts the CLI's typed show envelope to the canonical HEAD
// bytes the process tests inspect. A public volume name is not its directory.
func handoffHeadJSON(out string) (string, error) {
var result struct {
Head *layout.Head `json:"head"`
}
if err := json.Unmarshal([]byte(out), &result); err != nil {
return "", err
}
if result.Head == nil {
return "", fmt.Errorf("show returned no HEAD")
}
raw, err := result.Head.Encode()
return string(raw), err
}
func handoffDeleteCompleted(out string) bool {
var result struct {
Volume string `json:"volume"`
State string `json:"state"`
}
return json.Unmarshal([]byte(out), &result) == nil && result.Volume != "" && result.State == layout.StateDeleted
}
func TestHandoffShowUsesTheNestedLayoutHead(t *testing.T) {
for _, state := range []string{layout.StateLive, layout.StateDeleted} {
t.Run(state, func(t *testing.T) {
head := layout.Head{VolumeID: layout.VolumeID{1}, State: state, Activity: layout.Activity{Kind: layout.ActIdle}}
// This is chunkShow's public JSON shape, not HEAD's on-filer codec.
raw, err := json.Marshal(struct {
Volume any `json:"volume"`
Head *layout.Head `json:"head"`
}{Head: &head})
if err != nil {
t.Fatal(err)
}
got, err := handoffHeadJSON(string(raw))
if err != nil || !strings.Contains(got, `"epoch":0,"holder":""`) || (state == layout.StateDeleted && !strings.Contains(got, `"state":"deleted"`)) {
t.Fatalf("show adapter: %s, %v", got, err)
}
})
}
for _, raw := range []string{`{}`, `{"head":null}`, `{"head":{"State":"deleted"}}`, `not JSON`} {
if got, err := handoffHeadJSON(raw); err == nil {
t.Errorf("invalid/absent HEAD accepted: %s -> %s", raw, got)
}
}
}
func TestHandoffDeleteUsesTheCLIState(t *testing.T) {
for _, row := range []struct {
raw string
want bool
}{
{`{"volume":"v2-34071d5f","state":"deleted"}`, true},
{`{"volume":"v2-34071d5f","state":"deleting"}`, false},
{`{"completed":true}`, false},
{`{"state":"deleted"}`, false},
{`not JSON`, false},
} {
if got := handoffDeleteCompleted(row.raw); got != row.want {
t.Errorf("delete completion for %s: %v, want %v", row.raw, got, row.want)
}
}
}
@@ -0,0 +1,52 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"context"
"net"
"sync/atomic"
"testing"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
)
type handoffIdentityServer struct {
control.UnimplementedLifecycleServiceServer
calls atomic.Int32
}
func (s *handoffIdentityServer) GetVolume(_ context.Context, req *control.GetLifecycleVolumeRequest) (*control.CreateVolumeResponse, error) {
s.calls.Add(1)
return &control.CreateVolumeResponse{VolumeId: req.VolumeId, LayoutId: "00112233445566778899aabbccddeeff"}, nil
}
// Known-zero's source and target env constructors begin without a cache.
// Resolve through the real helper/RPC, then require cached reads to keep
// working when the master is unavailable (the crash fixtures depend on it).
func TestHandoffLayoutIdentityCacheStartsEmpty(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
rpc := &handoffIdentityServer{}
control.RegisterLifecycleServiceServer(server, rpc)
go server.Serve(listener)
t.Cleanup(server.Stop)
env := &handoffEnv{h: &plannedHandoffHarness{t: t, masterAddr: listener.Addr().String()}}
const want = "00112233445566778899aabbccddeeff"
for _, volume := range []string{"kzext4", "kzxfs", "kzext4", "kzxfs"} {
if got := env.layoutID(volume); got != want {
t.Fatalf("%s id=%s want %s", volume, got, want)
}
}
if got := rpc.calls.Load(); got != 2 {
t.Fatalf("resolve calls=%d want two distinct volumes", got)
}
server.Stop()
if got := env.layoutID("kzext4"); got != want {
t.Fatalf("cached id after master stop=%s", got)
}
}
@@ -14,11 +14,14 @@ import (
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// HEAD size against volume size, informative: it measures,
@@ -194,6 +197,9 @@ type headSzVol struct {
// its spec data and ctrl addresses are host:<port> (ports picked here, not
// probed there), and the test running on that host uses the same ones.
host string
// restoreTarget lists the volume with its placement only, no size_bytes:
// it has no volume record until a restore creates it.
restoreTarget bool
}
// headSzStartCluster starts one weed cluster (the filer's default store, no
@@ -226,7 +232,11 @@ func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoff
if v.server != "" {
nodes += fmt.Sprintf(" - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", server, b.data, b.ctrl)
}
fmt.Fprintf(&spec, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, v.bytes, server, replica)
size := fmt.Sprintf(" size_bytes: %d\n", v.bytes)
if v.restoreTarget {
size = ""
}
fmt.Fprintf(&spec, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, size, server, replica)
}
specPath := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(specPath, []byte("nodes:\n"+nodes+"volumes:\n"+spec.String()), 0o644); err != nil {
@@ -398,7 +408,7 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu
as := time.Now()
out, code := headSzRun(t, env, cfg.snapshotTimeout, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout,
"--name", fmt.Sprintf("%s-%d", name, cut), "--request-id", fmt.Sprintf("%s-%s-%d", name, b.volume, cut))
at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: headSzCountDir(t, env, env.chunkPath+"/"+b.volume+"/keys")}
at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: env.poolObjects(t, b.volume)}
if code != 0 {
var e struct{ Code, Message string }
if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) == nil {
@@ -446,15 +456,26 @@ func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cu
r.UploadedChunks, r.UploadedBytes = l.UploadedChunks, l.UploadedBytes
}
}
head := headSzGet(t, "http://"+env.cluster.filerHTTP+env.chunkPath+"/"+b.volume+"/HEAD", 256<<20)
r.HeadBytes = len(head)
var doc struct {
Segments map[string]json.RawMessage `json:"segments"`
// The volume's store directory is <name>-<id8>, its id from blockmaster's
// record. HEAD names the current root; the root names the segments.
id, err := layout.ParseVolumeID(env.layoutID(b.volume))
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(head, &doc); err != nil {
t.Fatalf("HEAD of %s is not JSON (%d bytes): %v", b.volume, len(head), err)
dir := "http://" + env.cluster.filerHTTP + path.Join(env.chunkPath, layout.VolumeDir(b.volume, id))
raw := headSzGet(t, dir+"/"+layout.HeadName, 256<<20)
r.HeadBytes = len(raw)
head, err := layout.DecodeHead(raw, 0, id)
if err != nil {
t.Fatalf("HEAD of %s (%d bytes): %v", b.volume, len(raw), err)
}
if head.Current != nil {
root, err := layout.DecodeRoot(headSzGet(t, dir+"/"+head.Current.Path(), 256<<20))
if err != nil {
t.Fatalf("current root of %s: %v", b.volume, err)
}
r.HeadSegments = len(root.Segments)
}
r.HeadSegments = len(doc.Segments)
return r
}
@@ -3,8 +3,10 @@
package main_test
import (
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
@@ -12,18 +14,20 @@ import (
// TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot: two restore targets of
// a snapshot of v1 (v2, v3) are refused for local headroom on the small file
// system (as in TestHeadroomRefusesARestoreAndAForkTargetThenServesThem; run
// system (as in TestHeadroomRefusesRestoreTargetsThenServesThem; run
// it with testdata/headroom-small-fs.sh). Then:
//
// - another root on the same host is a way out: v3's blockvolume, started
// again on the same host (same server and endpoints) with --durable-root
// on a file system with room and nothing freed, starts and serves the
// snapshot;
// - no blast radius: while v2 stays refused (in the catalog, never
// started), deleting the source's snapshot is allowed (deleting), and the
// source volume is then deleted through the volume-lifecycle page's steps
// (seal, revoke, ACK, volume-delete), which complete. Each step answers
// within its bound; nothing is blocked by the refused target.
// - the source's snapshot stays while targets depend on it: its delete is
// refused with snapshot_has_dependents while v2 is refused and v3
// serves. Once both targets are deleted (v2 started on a root with room;
// each through the volume-lifecycle page's seal, revoke, ACK and
// volume-delete), the snapshot delete succeeds, and the source volume is
// then deleted through the same steps. Each step answers within its
// bound.
func TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot(t *testing.T) {
small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER")
if small == "" || filler == "" {
@@ -50,7 +54,7 @@ func TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot(t *testing.T) {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", "base")
for _, v := range []string{"v2", "v3"} {
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", v,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", v,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
env.refusedForHeadroom(t, v, "blockvolume-"+v+"-no-room")
}
@@ -66,11 +70,32 @@ func TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot(t *testing.T) {
})
env.requireImage(t, "n-v3", img)
// Blast radius, v2 still refused: delete the source's snapshot, then the source volume.
out, errOut, code := env.h.run(t, "ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "base",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
if code != 0 || !strings.Contains(out, `"state":"deleting"`) {
t.Fatalf("snapshot-delete of the source snapshot while a restore target is refused: exit %d %s %s; want deleting", code, out, errOut)
// While v2 is refused and v3 serves, the source's snapshot cannot be deleted.
deleteBase := func() (string, string, int) {
return env.h.run(t, "ops", "chunk", "snapshot-delete", "--master", env.h.masterAddr, "--volume", "v1", "--name", "base",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
}
out, errOut, code := deleteBase()
if code == 0 || !strings.Contains(out+errOut, "snapshot_has_dependents") {
t.Fatalf("snapshot-delete of the source snapshot while restore targets depend on it: exit %d %s %s; want snapshot_has_dependents", code, out, errOut)
}
// Delete both targets: v2 on a root with room, then each through the
// page's steps.
b2 := env.hosts["n-v2"]
b2.root = filepath.Join(env.h.dir, "vol-n-v2-with-room")
env.hosts["n-v2"] = b2
adopted := func(vol string) *regexp.Regexp {
return regexp.MustCompile(`blockvolume: volume ` + vol + ` adopted as PRIMARY at r1@(\d+) `)
}
d2 := env.startTarget(t, "v2", "blockvolume-v2-with-room")
env.deleteServingTarget(t, "v2", env.hosts["n-v2"], d2, logUint(t, d2, adopted("v2")))
env.deleteServingTarget(t, "v3", b3, d3, logUint(t, d3, adopted("v3")))
// Now the snapshot delete succeeds, and then the source volume's delete.
out, errOut, code = deleteBase()
if code != 0 || !strings.Contains(out, `"state":"absent"`) {
t.Fatalf("snapshot-delete of the source snapshot after its targets were deleted: exit %d %s %s; want absent", code, out, errOut)
}
g := env.seal(t, "s1", e)
env.revoke(t, e, g)
@@ -79,20 +104,19 @@ func TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot(t *testing.T) {
}
env.waitAck(t, e, g)
out, errOut, code = env.volumeDelete(t, "del-v1")
requireDeleteCompleted(t, out, errOut, code, false)
requireDeleteCompleted(t, out, errOut, code)
}
// TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC: a restore
// target (v2) refused for local headroom has never hydrated, so its HEAD
// names its source's chunks. While it waits, the source's snapshot is
// deleted and then the source volume (seal, revoke, ACK, volume-delete), and
// the collector runs two applying passes a grace apart (its shortest grace;
// about 25 minutes). Then space is freed and v2 starts: it must read back
// the snapshot exactly, at once and again after its restore reaches
// independence. A read that differs or reads zero is a data-loss path and
// fails the test as such; a target that refuses to start fails with its
// reason.
func TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC(t *testing.T) {
// TestHeadroomRefusedRestoreTargetKeepsItsSourceSnapshot: a restore target
// (v2) refused for local headroom has never read a chunk, so its HEAD names
// its source's chunks. While it waits, its source snapshot cannot go: the
// delete through the source's holder (whose cleaning pass would collect the
// snapshot's chunks) is refused because v2 depends on it, and the source's
// pool keeps every chunk. Then space is freed and v2 starts: it must read
// back the snapshot exactly, at once and again after every chunk is made
// local. A read that differs or reads zero is a data-loss path and fails the
// test as such; a target that refuses to start fails with its reason.
func TestHeadroomRefusedRestoreTargetKeepsItsSourceSnapshot(t *testing.T) {
small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER")
if small == "" || filler == "" {
t.Skip("CHUNKSTORE_SMALL_ROOT and CHUNKSTORE_SMALL_FILLER name a small file system and its filler file")
@@ -101,13 +125,12 @@ func TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC(t *testing.T)
if free := freeBytes(t, small); free >= need {
t.Fatalf("the small file system has %d bytes free, not less than the %d a volume needs: fix the runner", free, need)
}
requireBudget(t, 2*ladderGCWait+10*time.Minute)
t.Cleanup(func() { _ = os.RemoveAll(filepath.Join(small, t.Name())) })
env := startHandoffEnvWith(t, 1, []string{"v2"})
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
src := env.start(t, "blockvolume-v1", "s1")
e := env.adopt(t, src, "s1")
env.adopt(t, src, "s1")
b2 := env.hosts["n-v2"]
b2.root = filepath.Join(small, t.Name(), "vol-n-v2")
env.hosts["n-v2"] = b2
@@ -117,34 +140,21 @@ func TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC(t *testing.T)
img := ladderImage("srcgone", []uint64{0, 3, 9}, 4)
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", "base")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
env.refusedForHeadroom(t, "v2", "blockvolume-v2-no-room")
// The source goes: its snapshot, then the volume, by the documented steps.
env.deleteSnapshot(t, "v1", "base")
g := env.seal(t, "s1", e)
env.revoke(t, e, g)
if err := src.wait(30 * time.Second); err != nil {
t.Fatalf("s1 after the revocation: %v; want a clean exit by itself", err)
// The source snapshot stays while v2 depends on it.
stored := env.poolObjects(t, "v1")
code, out := env.holderDeleteSnapshot(t, "s1", "v1", "base")
if code == http.StatusOK || !strings.Contains(out, "dependents") {
t.Fatalf("holder delete of the snapshot v2 depends on: status %d %s; want it refused (dependents)", code, out)
}
env.waitAck(t, e, g)
out, errOut, code := env.volumeDelete(t, "del-v1")
requireDeleteCompleted(t, out, errOut, code, false)
deleted := time.Now()
// Two collector passes a grace apart.
requireBudget(t, time.Until(deleted.Add(ladderGCWait))+ladderGCWait+5*time.Minute)
time.Sleep(time.Until(deleted.Add(ladderGCWait)))
objs1, n1 := env.gc(t, true)
first := time.Now()
requireBudget(t, ladderGCWait+5*time.Minute)
time.Sleep(time.Until(first.Add(ladderGCWait)))
objs2, n2 := env.gc(t, true)
for _, o := range append(objs1, objs2...) {
t.Logf("GC reclaimed %s %s (fid %s)", o.Volume, o.Key, o.FID)
env.requireSnapshotNames(t, "v1", "base")
time.Sleep(5 * time.Second) // a cleaning pass, had one run, ends well inside this
if got := env.poolObjects(t, "v1"); got != stored {
t.Fatalf("the source pool held %d chunk objects before the refused delete and %d after; want them all kept", stored, got)
}
t.Logf("GC: first pass reclaimed %d, second %d", n1, n2)
// The refused target, now with room, must read the snapshot exactly.
if err := os.Remove(filler); err != nil {
@@ -155,19 +165,18 @@ func TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC(t *testing.T)
for end := time.Now().Add(60 * time.Second); time.Now().Before(end) && !adopted; time.Sleep(200 * time.Millisecond) {
select {
case <-d2.done:
t.Fatalf("v2 refused to start after its source was deleted and collected: %v; %q", d2.err, strings.TrimSpace(d2.line("blockvolume:")))
t.Fatalf("v2 refused to start: %v; %q", d2.err, strings.TrimSpace(d2.line("blockvolume:")))
default:
}
adopted = d2.has("blockvolume: volume v2 adopted as PRIMARY at r1@")
}
if !adopted {
t.Fatal("v2 never adopted after its source was deleted and collected")
t.Fatal("v2 never adopted once it had room")
}
poll(t, 60*time.Second, "v2 never reported its frontend ready", func() bool { return volumeFrontendReady(b2.status, "v2") })
requireImageExact(t, env, "n-v2", img, "after its source was deleted and collected")
env.h.command(t, "ops", "chunk", "restore", "--volume", "v2", "--status-addr", b2.status)
env.waitIndependent(t, "v2")
requireImageExact(t, env, "n-v2", img, "after its restore reached independence")
requireImageExact(t, env, "n-v2", img, "after the refused delete of its source snapshot")
env.hydrate(t, "v2")
requireImageExact(t, env, "n-v2", img, "after it was read in full (hydrated)")
}
// requireImageExact reads every block of img on the host and fails, marked
@@ -15,7 +15,7 @@ import (
"time"
)
// Local headroom for a restore and a fork target. The durable root of each
// Local headroom for restore targets. The durable root of each
// target is on a small file system (CHUNKSTORE_SMALL_ROOT, a directory on it)
// that a filler file (CHUNKSTORE_SMALL_FILLER, on the same file system) keeps
// below the volume size + WAL. testdata/headroom-small-fs.sh prepares both on
@@ -152,14 +152,13 @@ func (env *handoffEnv) deleteServingTarget(t *testing.T, vol string, b bvHost, d
})
out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC,
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-"+vol)
var del struct{ Completed bool }
if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed {
if code != 0 || !handoffDeleteCompleted(out) {
t.Fatalf("volume-delete of %s after the way out: exit %d %s %s; want completed", vol, code, out, errOut)
}
}
// TestHeadroomRefusesARestoreAndAForkTargetThenServesThem: a snapshot of v1
// is restored into v2, v4 and v6 and forked into v3, each target's durable
// TestHeadroomRefusesRestoreTargetsThenServesThem: a snapshot of v1 is
// restored into v2, v4 and v6 (fork is not in v1), each target's durable
// root on a small file system with less free space than the volume size +
// WAL.
// Each target's blockvolume refuses the create, naming both numbers, exits
@@ -172,9 +171,9 @@ func (env *handoffEnv) deleteServingTarget(t *testing.T, vol string, b bvHost, d
// of 1.0): a volume-delete wants a clean revocation ACK its holder cannot
// send, and a forced move to a host with room (n-v7) is refused because the
// master knows no holder of it. The one way out is run: once space is freed,
// v2 and v3 start and serve the snapshot, and v4 and v6 start, serve, and are
// v2 starts and serves the snapshot, and v4 and v6 start, serve, and are
// sealed, revoked, acknowledged and deleted.
func TestHeadroomRefusesARestoreAndAForkTargetThenServesThem(t *testing.T) {
func TestHeadroomRefusesRestoreTargetsThenServesThem(t *testing.T) {
small, filler := os.Getenv("CHUNKSTORE_SMALL_ROOT"), os.Getenv("CHUNKSTORE_SMALL_FILLER")
if small == "" || filler == "" {
t.Skip("CHUNKSTORE_SMALL_ROOT and CHUNKSTORE_SMALL_FILLER name a small file system and its filler file")
@@ -185,8 +184,8 @@ func TestHeadroomRefusesARestoreAndAForkTargetThenServesThem(t *testing.T) {
}
t.Cleanup(func() { _ = os.RemoveAll(filepath.Join(small, t.Name())) })
env := startLadderEnv(t, "v2", "v3", "v4", "v5", "v6", "v7")
for _, v := range []string{"v2", "v3", "v4", "v6"} {
env := startLadderEnv(t, "v2", "v4", "v5", "v6", "v7")
for _, v := range []string{"v2", "v4", "v6"} {
b := env.hosts["n-"+v]
b.root = filepath.Join(small, t.Name(), "vol-n-"+v)
env.hosts["n-"+v] = b
@@ -198,16 +197,14 @@ func TestHeadroomRefusesARestoreAndAForkTargetThenServesThem(t *testing.T) {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", "base")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
env.h.command(t, "ops", "chunk", "fork", "--source", "v1", "--snapshot", "base", "--target", "v3",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
for _, v := range []string{"v4", "v6"} {
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", v,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", v,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
}
refused := map[string]*daemon{}
for _, v := range []string{"v2", "v3", "v4", "v6"} {
for _, v := range []string{"v2", "v4", "v6"} {
refused[v] = env.refusedForHeadroom(t, v, "blockvolume-"+v+"-no-room")
}
@@ -225,7 +222,7 @@ func TestHeadroomRefusesARestoreAndAForkTargetThenServesThem(t *testing.T) {
env.requireImage(t, "n-v5", img)
env.requireImage(t, "s1", img) // the source is intact
if l := env.snapshots(t, "v1", "base"); len(l) != 1 || l[0].State != "active" {
if l := env.snapshots(t, "v1", "base"); len(l) != 1 {
t.Fatalf("the source's snapshot after the refusals: %+v", l)
}
@@ -235,7 +232,7 @@ func TestHeadroomRefusesARestoreAndAForkTargetThenServesThem(t *testing.T) {
if free := freeBytes(t, small); free < need {
t.Fatalf("after removing the filler the small file system has %d bytes free; the %d a volume needs does not fit: fix the runner", free, need)
}
for _, v := range []string{"v2", "v3"} {
for _, v := range []string{"v2"} {
env.startTarget(t, v, "blockvolume-"+v+"-with-room")
env.requireImage(t, "n-"+v, img)
}
@@ -14,6 +14,8 @@ import (
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// TestKnownZeroAcceptance is the KNOWN-ZERO acceptance test of a fresh volume,
@@ -52,7 +54,7 @@ func TestKnownZeroAcceptance(t *testing.T) {
run = fmt.Sprintf("local-%d", time.Now().Unix())
}
// KZ_ROLE: "" = every step in this process (the smoke); "source" = steps
// 1, 2 and 5 here, the restore and fork targets on KZ_TARGET_HOST (the
// 1, 2 and 5 here, the restore target on KZ_TARGET_HOST (the
// second host), handed over through KZ_HANDOFF; "target" = steps
// 3 and 4 on this host against the source's cluster named in KZ_HANDOFF.
role := os.Getenv("KZ_ROLE")
@@ -70,13 +72,12 @@ func TestKnownZeroAcceptance(t *testing.T) {
} else if role != "" {
t.Fatalf("KZ_ROLE %q: want source, target or unset", role)
}
// per file system: the source and two targets of its S1, each target on
// its own server node (on KZ_TARGET_HOST in the source role)
// per file system: the source and a restore target of its S1 on its own
// server node (on KZ_TARGET_HOST in the source role); fork is not in v1
var vols []headSzVol
for _, fs := range fss {
vols = append(vols, headSzVol{id: "kz" + fs, bytes: bytes},
headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost},
headSzVol{id: "kz" + fs + "f", bytes: bytes, server: "t-" + fs + "f", host: targetHost})
headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost, restoreTarget: true})
}
// step 5: up to kzCrashTries fresh volumes (a try whose stop lands after the
// attach commit has committed that store, so a retry needs a new one)
@@ -93,7 +94,7 @@ func TestKnownZeroAcceptance(t *testing.T) {
if !v.S1.Completed {
continue
}
for _, kind := range []string{"restore", "fork"} {
for _, kind := range []string{"restore"} {
tb := env.hosts["kz"+fs+kind[:1]]
if role == "source" {
ho.Targets = append(ho.Targets, kzHandoffTarget{Kind: kind, Volume: tb.volume, Server: tb.server, Data: tb.data, Ctrl: tb.ctrl,
@@ -111,7 +112,7 @@ func TestKnownZeroAcceptance(t *testing.T) {
}
// kzHandoff is what the source role hands to the target role (KZ_HANDOFF):
// the cluster to use and, per target, the S1 to restore or fork and what the
// the cluster to use and, per target, the S1 to restore and what the
// source wrote into it.
type kzHandoff struct {
Run string `json:"run"`
@@ -278,7 +279,7 @@ type kzTargetRecord struct {
FirstCut kzCutRecord `json:"first_snapshot"`
}
// kzTarget restores or forks the source's S1 into tb, then runs step 4 (read
// kzTarget restores the source's S1 into tb, then runs step 4 (read
// the S1-named blocks BEFORE hydration: data, never zeros; the read itself
// waits for its chunk) and step 3 (all contents equal the source; the target's
// first snapshot completes without a full scan).
@@ -286,8 +287,14 @@ func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind s
t.Helper()
r := kzTargetRecord{Volume: tb.volume, Kind: kind, Source: src.Volume, Snapshot: src.S1Name,
NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, tb.volume)}
env.h.command(t, "ops", "chunk", kind, "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--request-id", "kz-"+kind+"-"+tb.volume)
// The target is placement only: before its restore the master has no
// record of it, so the restore creates it.
if out, errOut, code := env.h.run(t, "ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", tb.volume,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath); code == 0 || !strings.Contains(out+errOut, "resolve --volume") || !strings.Contains(out+errOut, "not found") {
t.Fatalf("restore target %s has a volume record before its restore: exit %d %s %s", tb.volume, code, out, errOut)
}
env.h.command(t, "ops", "chunk", "restore", "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume,
"--master", env.h.masterAddr, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--request-id", "kz-"+kind+"-"+tb.volume)
d, refusal := headSzStartVolume(t, env, tb, bytes, "--nvme-subsysnqn", r.NQN)
if d == nil {
rep.step(t, 3, tb.volume, false, kind+" target refused: "+refusal)
@@ -318,10 +325,8 @@ func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind s
kind, r.Reads, r.ReadsEqual, r.ReadsZero, r.Before.AbsentChunks, r.After.AbsentChunks, waited,
r.After.Hydration.Fetches-r.Before.Hydration.Fetches))
// (3) contents equal + first snapshot without a full scan
if kind == "restore" {
env.h.command(t, "ops", "chunk", "restore", "--volume", tb.volume, "--status-addr", tb.status)
}
// (3) contents equal + first snapshot without a full scan (v1 fills a
// restore target on access: the reads below fetch any chunk still absent)
if device {
r.Identity, r.FilesEqual = kzDeviceVerify(t, tb, r.NQN, src, run)
} else {
@@ -443,10 +448,34 @@ func kzHoldBin(t *testing.T, rep *kzReport) string {
return p
}
// kzFreshAtStop reads, after the held first start was killed, whether b's
// store is still fresh: the fresh state is in the store's descriptor
// (WALStore.LayoutIdentity), set before the first claim and cleared only by
// the attach commit; the .chunkfresh sidecar the step once looked for no
// longer exists. The store is the one under b's layout directory
// (<root>/<volume>-<id8>/, --layout-id), or under b's root without one. The
// returned record (markers_at_stop) names the store read and what it held.
func kzFreshAtStop(b bvHost) (bool, []string) {
stores, _ := filepath.Glob(filepath.Join(b.root, b.volume+"-*", b.volume+".bin"))
if len(stores) == 0 {
stores, _ = filepath.Glob(filepath.Join(b.root, b.volume+".bin"))
}
if len(stores) != 1 {
return false, []string{fmt.Sprintf("%d stores for %s under %s", len(stores), b.volume, b.root)}
}
ws, err := storage.OpenWALStore(stores[0])
if err != nil {
return false, []string{fmt.Sprintf("%s: open: %v", stores[0], err)}
}
defer ws.Close()
claim, fresh, ok := ws.LayoutIdentity()
return ok && fresh, []string{fmt.Sprintf("%s layout_identity set=%t fresh=%t claim=%s", stores[0], ok, fresh, claim)}
}
// kzCrashFirstStart is step 5:
// the first start of a fresh volume runs the kzhold test binary, which holds
// at the boundary before the fresh marker is retired; the test requires the
// .chunkfresh marker present there, then SIGKILLs it. More than one try fails
// at the boundary before the fresh marker is retired; the test SIGKILLs it
// there and requires the store still fresh (kzFreshAtStop). More than one try fails
// the step. Then restart that volume and
// repeat steps 1-2: nothing certified known-zero (KnownZeroChunks 0, no
// fresh-attach line), the first cut scans every chunk once, the next cut only
@@ -494,11 +523,9 @@ func kzCrashFirstStart(t *testing.T, env *handoffEnv, rep *kzReport, bytes uint6
if err := d.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatalf("SIGSTOP %s: %v", b.id, err)
}
markers, _ := filepath.Glob(filepath.Join(b.root, "*.chunkfresh"))
more, _ := filepath.Glob(b.root + "*.chunkfresh")
markers = append(markers, more...)
d.kill(t)
try := kzCrashTry{Volume: b.volume, Markers: markers, Before: len(markers) > 0}
fresh, markers := kzFreshAtStop(b)
try := kzCrashTry{Volume: b.volume, Markers: markers, Before: fresh}
r.Tries = append(r.Tries, try)
if try.Before {
break
@@ -45,15 +45,17 @@ func TestProcedureMasterKilledAfterMoveBeforeTargetStarts(t *testing.T) {
}
}
out, _ = env.h.command(t, env.chunkShow()...)
if got := mustU(sealedHeadLSN(out, e, g)); got != l {
if got := mustU(sealedLayoutHeadPosition(out, e, g)); got != l {
t.Fatalf("sealed HEAD LSN %d; want %d", got, l)
}
nw := env.start(t, "blockvolume-s2", "s2")
must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2"))
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("target adopted epoch %d; want recovered epoch %d", got, e2)
}
env.requireHeadHolder(t, e2, "s2")
// Planned hand-over step 8 observes the completed layout claim in HEAD:
// its identity advanced while the sealed image and position were kept.
out, _ = env.h.command(t, env.chunkShow()...)
must(checkLayoutHeadReopenedBy(out, e2, g, l, "s2"))
if !bytes.Equal(env.readBlock(t, "s2", 0), block) {
t.Fatal("acknowledged source block changed after master crash and move recovery")
}
@@ -306,7 +306,7 @@ func TestManyVolumesServeTogetherAfterMasterRestart(t *testing.T) {
for i := 2; i <= n; i++ {
targets = append(targets, fmt.Sprintf("v%d", i))
}
env := startHandoffEnvWith(t, 1, targets)
env := startHandoffEnvVolumes(t, 1, targets)
hosts := []bvHost{env.hosts["s1"]}
hosts[0].volume = "v1"
for _, v := range targets {
@@ -4,7 +4,6 @@ package main_test
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
@@ -29,16 +28,15 @@ func TestNeverAttachedRestoreTargetIsDeletable(t *testing.T) {
env.snapshot(t, "s1", "v1", "s1")
// The target exists in the catalog; its blockvolume never starts.
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC,
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-never-started")
var del struct{ Completed bool }
if code != 0 || json.Unmarshal([]byte(out), &del) != nil || !del.Completed {
if code != 0 || !handoffDeleteCompleted(out) {
t.Fatalf("volume-delete of a never-attached target must complete; exit %d:\n%s\n%s", code, out, errOut)
}
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
shown := env.headOf(t, "v2")
if !strings.Contains(shown, `"state":"deleted"`) {
t.Fatalf("the deleted target's HEAD is not a deleted tombstone:\n%s", shown)
}
@@ -62,7 +60,7 @@ func TestNeverStartedDeleteFencesALateStart(t *testing.T) {
env.adopt(t, holder, "s1")
env.writeBlock(t, "s1", 0, cutCrashBlock('L', 0))
env.snapshot(t, "s1", "v1", "s1")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
out, errOut, code := env.h.run(t, "ops", "chunk", "volume-delete", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC,
"--chunk-path", env.chunkPath, "--master", env.h.masterAddr, "--request-id", "del-v2-late")
@@ -73,7 +71,7 @@ func TestNeverStartedDeleteFencesALateStart(t *testing.T) {
late := env.h.start(t, "blockvolume-v2-late", env.h.volume, env.volArgsFor(b)...)
err := late.wait(60 * time.Second)
served := late.has("durable: HEAD claim for volume=v2 done") || volumeFrontendReady(b.status, "v2")
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
shown := env.headOf(t, "v2")
t.Logf("late start after the delete: exit %v, served %v, HEAD %s", err, served, firstLine(shown))
if served || err == nil || strings.Contains(fmt.Sprint(err), "still running") || !strings.Contains(shown, `"state":"deleted"`) {
t.Fatalf("1.0.1: a start after the delete must exit without claiming or serving and leave the volume deleted; exit %v, served %v, HEAD:\n%s", err, served, shown)
@@ -93,7 +91,7 @@ func TestNeverStartedDeleteRacesAStart(t *testing.T) {
env.writeBlock(t, "s1", 0, cutCrashBlock('R', 0))
env.snapshot(t, "s1", "v1", "s1")
for _, v := range targets {
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
b := env.hosts["n-"+v]
type delResult struct {
@@ -118,7 +116,7 @@ func TestNeverStartedDeleteRacesAStart(t *testing.T) {
// claim) or its frontend became ready; adopting the assignment comes
// before the claim and is not serving.
served := d.has("durable: HEAD claim for volume="+v+" done") || volumeFrontendReady(b.status, v)
shown, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
shown := env.headOf(t, v)
isDeleted := strings.Contains(shown, `"state":"deleted"`)
t.Logf("%s: delete exit %d, served %v, HEAD deleted %v: %s", v, r.code, served, isDeleted, firstLine(r.out))
switch {
@@ -145,6 +143,35 @@ func (env *handoffEnv) deleteNoRevoke(ctx context.Context, v, request string) (s
return out + errOut, code
}
// deleteAfterTheHorizon is v1's delete of a line HEAD never reached: the
// delete may be refused only while the stranded line's lease can still be
// live ("lease expiry plus clock-skew margin has not elapsed"); nobody
// renews it, so the same delete (same request id, which resumes it) run
// past the horizon it names completes. Any other refusal is returned as it
// is. The immediate delete of a never-started line, without waiting, is the
// 1.0.1 fix.
func (env *handoffEnv) deleteAfterTheHorizon(t *testing.T, v, request string) (string, int) {
t.Helper()
out, code := env.deleteNoRevoke(context.Background(), v, request)
if code == 0 || !strings.Contains(out, "has not elapsed") {
return out, code
}
wait := 75 * time.Second
if i := strings.Index(out, "live until "); i >= 0 {
if f := strings.Fields(out[i+len("live until "):]); len(f) > 0 {
if until, err := time.Parse(time.RFC3339Nano, strings.TrimRight(f[0], ":")); err == nil {
wait = time.Until(until) + 5*time.Second
}
}
}
if wait < 0 || wait > 90*time.Second {
t.Fatalf("the refusal names a horizon %v away (want within 90 s):\n%s", wait, out)
}
t.Logf("%s: refused until its lease horizon; retrying in %v:\n%s", v, wait.Round(time.Second), firstLine(out))
time.Sleep(wait)
return env.deleteNoRevoke(context.Background(), v, request)
}
// lineOf returns the master's durable authority record for v (the line:
// replica, epoch, and any workspace lease), as stored in --authority-store.
func (env *handoffEnv) lineOf(t *testing.T, v string) string {
@@ -185,7 +212,7 @@ func (env *handoffEnv) requireNeverStarted(t *testing.T, v string, e, headEpoch
// and the process exits. The filer comes back. Line at 1, no lease, HEAD 0.
func (env *handoffEnv) strandStoreDown(t *testing.T, v string) {
t.Helper()
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
env.cluster.stopProc(t, "filer")
d := env.h.start(t, "blockvolume-"+v+"-store-down", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...)
@@ -206,7 +233,7 @@ func (env *handoffEnv) strandStoreDown(t *testing.T, v string) {
func (env *handoffEnv) strandAtGrant(t *testing.T, candidates ...string) string {
t.Helper()
for _, v := range candidates {
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", v,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", v,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := env.h.start(t, "blockvolume-"+v+"-stopped-at-grant", env.h.volume, env.volArgsFor(env.hosts["n-"+v])...)
deadline := time.Now().Add(60 * time.Second)
@@ -236,7 +263,8 @@ func (env *handoffEnv) strandAtGrant(t *testing.T, candidates ...string) string
return ""
}
// 1.0.1 red (INV-WS-DELETE-NO-LIVE-HOLDER-001): a line whose epoch HEAD never
// INV-WS-DELETE-NO-LIVE-HOLDER-001 (on v1 past the stranded line's lease
// horizon: deleteAfterTheHorizon; at once is 1.0.1): a line whose epoch HEAD never
// reached has acknowledged nothing, so volume-delete completes WITHOUT a
// revoke; HEAD becomes a deleted tombstone, the source is untouched, and no
// granted lease stays on the deleted volume. Routes, each without root:
@@ -252,13 +280,12 @@ func TestNeverStartedLineIsDeletableWithoutARevoke(t *testing.T) {
deleted := func(t *testing.T, env *handoffEnv, v, request string) {
t.Helper()
before := env.workspaceShow(t, v)
out, code := env.deleteNoRevoke(context.Background(), v, request)
var del struct{ Completed bool }
completed := code == 0 && json.Unmarshal([]byte(firstLine(out)), &del) == nil && del.Completed
out, code := env.deleteAfterTheHorizon(t, v, request)
completed := code == 0 && handoffDeleteCompleted(out)
head, after := env.headOf(t, v), env.workspaceShow(t, v)
t.Logf("delete exit %d, completed %v, HEAD %s\nworkspace show before:\n%s\nafter:\n%s\ndelete output:\n%s", code, completed, head, before, after, out)
if !completed {
t.Fatalf("1.0.1: volume-delete of %s (line above HEAD) must complete without a revoke; exit %d", v, code)
t.Fatalf("volume-delete of %s (line above HEAD) must complete without a revoke, past the lease horizon; exit %d", v, code)
}
if !strings.Contains(head, `"state":"deleted"`) || strings.Contains(after, "lease state: granted") {
t.Fatalf("a completed delete must leave a deleted HEAD and no granted lease")
@@ -310,7 +337,7 @@ func requireSourceUntouched(t *testing.T, env *handoffEnv) {
}
}
// 1.0.1 red: after that delete, a start of the target with the store up
// After that delete (on v1 past the lease horizon), a start of the target with the store up
// must not claim it: it exits without serving and the HEAD stays deleted.
// S1 and S2.
func TestNeverStartedLineDeleteFencesALateStart(t *testing.T) {
@@ -329,8 +356,8 @@ func TestNeverStartedLineDeleteFencesALateStart(t *testing.T) {
} else {
v = env.strandAtGrant(t, c.targets...)
}
if out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-late"); code != 0 {
t.Fatalf("1.0.1: volume-delete of %s (line above HEAD): exit %d:\n%s", v, code, out)
if out, code := env.deleteAfterTheHorizon(t, v, "del-"+v+"-late"); code != 0 {
t.Fatalf("volume-delete of %s (line above HEAD), past the lease horizon: exit %d:\n%s", v, code, out)
}
b := env.hosts["n-"+v]
late := env.h.start(t, "blockvolume-"+v+"-late", env.h.volume, env.volArgsFor(b)...)
@@ -383,7 +410,7 @@ func TestNeverStartedLineDeleteRacesAStart(t *testing.T) {
}
}
// 1.0.1 red (master restart, one direction): the master is SIGKILLed and
// Master restart, one direction (on v1 past the lease horizon): the master is SIGKILLed and
// restarted between the stranding and the delete; the delete still completes
// without a revoke, from what the master and the HEAD keep durably. S1 and S2.
func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) {
@@ -398,9 +425,9 @@ func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) {
env.strandStoreDown(t, v)
}
restartKilledMaster(t, env)
out, code := env.deleteNoRevoke(context.Background(), v, "del-"+v+"-after-restart")
out, code := env.deleteAfterTheHorizon(t, v, "del-"+v+"-after-restart")
if head := env.headOf(t, v); code != 0 || !strings.Contains(head, `"state":"deleted"`) {
t.Fatalf("1.0.1: after a master restart, volume-delete of %s must complete; exit %d, HEAD %s:\n%s", v, code, head, out)
t.Fatalf("after a master restart, volume-delete of %s must complete (past the lease horizon); exit %d, HEAD %s:\n%s", v, code, head, out)
}
})
}
@@ -412,7 +439,7 @@ func TestNeverStartedDeleteAfterAMasterRestart(t *testing.T) {
// without a revoke and an ACK is refused and the HEAD is not tombstoned.
func TestClaimedTargetAfterAMasterRestartIsNotNeverStarted(t *testing.T) {
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := env.startTarget(t, "v2", "blockvolume-v2")
if head := env.headOf(t, "v2"); strings.Contains(head, `"holder":""`) {
@@ -0,0 +1,87 @@
package main_test
import (
"errors"
"fmt"
"testing"
)
// nvmeHostMaxRetries is the Linux NVMe host's default retry count for a
// command whose status has Do Not Retry clear (nvme_core max_retries).
const nvmeHostMaxRetries = 5
// nvmeStatusError is a completion with a non-zero status. Bit 15 of the
// status field is Do Not Retry.
type nvmeStatusError struct {
op string
status uint16
}
func (e *nvmeStatusError) Error() string { return fmt.Sprintf("nvme %s status 0x%04x", e.op, e.status) }
func (e *nvmeStatusError) retryable() bool { return e.status&0x8000 == 0 }
// retryLikeHost runs op as the Linux NVMe host runs a command: a completion
// whose status has Do Not Retry clear is retried, at most max times; it
// returns the number of such refusals. When max retries are used up the
// error is returned, as the host returns EIO then. A status with Do Not
// Retry set, or any other error (transport, lost or unexpected bytes), is
// returned at once.
func retryLikeHost(max int, op func() error) (refused int, err error) {
for {
err = op()
var se *nvmeStatusError
if err == nil || !errors.As(err, &se) || !se.retryable() {
return refused, err
}
refused++
if refused > max {
return refused, fmt.Errorf("%w: refused %d times, %d retries used up", err, refused, max)
}
}
}
func TestRetryLikeHostRetriesOnlyDNRClearStatusFiveTimes(t *testing.T) {
busy := &nvmeStatusError{op: "Write", status: 0x0104} // namespace not ready, DNR clear
permanent := &nvmeStatusError{op: "Write", status: 0x8004} // DNR set
script := func(errs ...error) (func() error, *int) {
calls := 0
return func() error {
calls++
if calls <= len(errs) {
return errs[calls-1]
}
return nil
}, &calls
}
repeat := func(e error, n int) []error {
out := make([]error, n)
for i := range out {
out[i] = e
}
return out
}
for _, tc := range []struct {
name string
max int
errs []error
refused int
calls int
fails bool
}{
{"five refusals then success", nvmeHostMaxRetries, repeat(busy, 5), 5, 6, false},
{"six refusals use up the retries", nvmeHostMaxRetries, repeat(busy, 6), 6, 6, true},
{"retries off fails on the first refusal", 0, repeat(busy, 1), 1, 1, true},
{"do not retry set fails at once", nvmeHostMaxRetries, []error{permanent}, 0, 1, true},
{"a transport error fails at once", nvmeHostMaxRetries, []error{errors.New("nvme Write: want R2T: EOF")}, 0, 1, true},
{"success", nvmeHostMaxRetries, nil, 0, 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
op, calls := script(tc.errs...)
refused, err := retryLikeHost(tc.max, op)
if refused != tc.refused || *calls != tc.calls || (err != nil) != tc.fails {
t.Fatalf("refused %d calls %d err %v; want refused %d calls %d fails %v", refused, *calls, err, tc.refused, tc.calls, tc.fails)
}
})
}
}
@@ -9,14 +9,16 @@ import (
"testing"
)
// #425: the procedure gate's owner-endpoint check rejects when EITHER recipient's evidence is missing, unreadable,
// has no forced-epoch delivery, or carries another host's endpoints; it passes only with positive evidence from both.
// The procedure gate needs positive evidence from every recipient: an owner's
// delivery or the documented MOVED refusal before any assignment is delivered.
// A refusal never excuses wrong endpoints in a delivery that did occur.
func TestWrongOwnerEndpointsNeedsPositiveEvidenceFromEachRecipient(t *testing.T) {
owner := bvHost{id: "s2", data: "127.0.0.1:2001", ctrl: "127.0.0.1:2002"}
dir := t.TempDir()
good := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=1 data="127.0.0.1:2001" ctrl="127.0.0.1:2002"`
wrong := `blockvolume: assignment stream delivery process="X" server="s2" volume="v1" replica="r1" epoch=2 ev=2 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"`
other := `blockvolume: assignment stream delivery process="X" server="s1" volume="v1" replica="r1" epoch=1 ev=1 data="127.0.0.1:1001" ctrl="127.0.0.1:1002"`
moved := `blockvolume: exiting status=78 reason=moved`
logOf := func(name string, lines ...string) *daemon {
p := filepath.Join(dir, name+".log")
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
@@ -35,6 +37,10 @@ func TestWrongOwnerEndpointsNeedsPositiveEvidenceFromEachRecipient(t *testing.T)
{"first has no epoch delivery", []*daemon{logOf("a3", other), logOf("b3", good)}, "no epoch delivery logged"},
{"second carries another host's endpoints", []*daemon{logOf("a4", good), logOf("b4", good, wrong)}, "127.0.0.1:1001"},
{"first empty log", []*daemon{logOf("a5"), logOf("b5", good)}, "no epoch delivery logged"},
{"source refused before delivery", []*daemon{logOf("a6", good), logOf("b6", moved)}, ""},
{"refusal does not excuse wrong endpoints", []*daemon{logOf("a7", good), logOf("b7", wrong, moved)}, "127.0.0.1:1001"},
{"unclassified exit is not a moved refusal", []*daemon{logOf("a8", good), logOf("b8", "blockvolume: exiting status=78")}, "no epoch delivery logged"},
{"retry exit is not a moved refusal", []*daemon{logOf("a9", good), logOf("b9", "blockvolume: exiting status=75 reason=assignment_timeout")}, "no epoch delivery logged"},
} {
bad := wrongOwnerEndpoints(2, owner, c.ds...)
switch {
@@ -138,12 +138,16 @@ func sealedLayoutHeadPosition(out string, epoch, gen uint64) (uint64, error) {
}
func checkLayoutHeadReopened(out string, epoch, sealedGen, position uint64) error {
return checkLayoutHeadReopenedBy(out, epoch, sealedGen, position, "s1")
}
func checkLayoutHeadReopenedBy(out string, epoch, sealedGen, position uint64, host string) error {
h, err := parseLayoutHead(out)
if err != nil {
return err
}
if h.Gen <= sealedGen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "" || h.Position != position || len(h.Current) == 0 || string(h.Current) == "null" {
return fmt.Errorf("layout HEAD after claim %+v; want live image above gen %d at epoch %d position %d holder s1/r1", h, sealedGen, epoch, position)
if h.Gen <= sealedGen || h.Epoch != epoch || h.Holder != host+"/r1" || h.ClaimID == "" || h.State != "" || h.Position != position || len(h.Current) == 0 || string(h.Current) == "null" {
return fmt.Errorf("layout HEAD after claim %+v; want live image above gen %d at epoch %d position %d holder %s/r1", h, sealedGen, epoch, position, host)
}
return nil
}
@@ -21,10 +21,13 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// TestStandalonePlannedHandoffToTheSameHost runs the planned hand-over back
@@ -209,17 +212,29 @@ func startHandoffEnv(t *testing.T, n int, masterArgs ...string) *handoffEnv {
return startHandoffEnvWith(t, n, nil, masterArgs...)
}
// startHandoffEnvWith is startHandoffEnv with more volume records in the
// cluster spec: each of targets (a volume id) is placed on a node of its
// own, named after it, with its own endpoints and local root (a restore
// target, for example).
// startHandoffEnvWith is startHandoffEnv with restore targets: each of
// targets (a volume id) is placed on a node of its own, named after it, with
// its own endpoints and local root. A target has placement only, no volume
// record: its restore creates it.
func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...string) *handoffEnv {
t.Helper()
var tlsCfg map[string]time.Time
return startHandoffEnvConfigured(t, n, targets, procedureTLSConfig(), false, masterArgs...)
}
// startHandoffEnvVolumes is startHandoffEnvWith with ordinary volumes: each
// of volumes gets a volume record from the cluster spec, so it starts
// without a restore.
func startHandoffEnvVolumes(t *testing.T, n int, volumes []string, masterArgs ...string) *handoffEnv {
t.Helper()
return startHandoffEnvConfigured(t, n, volumes, procedureTLSConfig(), true, masterArgs...)
}
// procedureTLSConfig is nil without mutual TLS, else an empty expiry map.
func procedureTLSConfig() map[string]time.Time {
if procedureTLSOn() {
tlsCfg = map[string]time.Time{}
return map[string]time.Time{}
}
return startHandoffEnvTLS(t, n, targets, tlsCfg, masterArgs...)
return nil
}
// startHandoffEnvTLS is startHandoffEnvWith with mutual TLS when tlsNotAfter
@@ -232,9 +247,19 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s
// VolumeRecord. The restore-create test uses that form so the master creates
// the target's identity and restored image in one request.
func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, masterArgs ...string) *handoffEnv {
t.Helper()
return startHandoffEnvOnCluster(t, n, targets, tlsNotAfter, precreateTargets, nil, masterArgs...)
}
// startHandoffEnvOnCluster also admits a caller-owned stock filer behind a
// fault-injection front; ordinary callers keep the default cluster unchanged.
func startHandoffEnvOnCluster(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, cluster *w4WeedCluster, masterArgs ...string) *handoffEnv {
t.Helper()
h := newPlannedHandoffHarness(t)
env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
if cluster == nil {
cluster = startWorkspaceWeed(t)
}
env := &handoffEnv{h: h, cluster: cluster, chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
must, _ := fatalOn(t)
env.hosts["s1"] = bvHost{id: "s1", data: h.dataAddr, ctrl: h.ctrlAddr, status: h.statusAddr, nvme: h.nvmeAddr, root: filepath.Join(h.dir, "vol")}
for i := 2; i <= n; i++ {
@@ -245,7 +270,7 @@ func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfte
id := "n-" + v
env.hosts[id] = bvHost{id: id, data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id), volume: v}
}
cluster, chunkPath := env.cluster, env.chunkPath
chunkPath := env.chunkPath
if tlsNotAfter != nil {
servers := make([]string, 0, len(env.hosts))
for _, b := range env.hosts {
@@ -327,11 +352,25 @@ func (env *handoffEnv) layoutID(volume string) string {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
id, err := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume)
if err != nil {
t.Fatalf("resolve layout identity for %s: %v", volume, err)
// blockmaster logs "lock acquired" before it imports the cluster spec
// (each volume's layout created on the filer) and only serves after
// that, so a lookup right after that line can find it not serving yet:
// retry while it is unavailable, within 60 s. Any other answer (not
// found, refused) fails at once.
var id layout.VolumeID
for end := time.Now().Add(60 * time.Second); ; time.Sleep(500 * time.Millisecond) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
id, err = lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume)
cancel()
if err == nil {
break
}
if c := status.Code(err); (c != codes.Unavailable && c != codes.DeadlineExceeded) || time.Now().After(end) {
t.Fatalf("resolve layout identity for %s: %v", volume, err)
}
}
if env.layoutIDs == nil {
env.layoutIDs = make(map[string]string)
}
env.layoutIDs[volume] = id.String()
return id.String()
@@ -386,7 +386,7 @@ func TestProcedureCrashDuringACut(t *testing.T) {
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
h, err := parseHead(out)
h, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
@@ -62,7 +62,7 @@ func TestProcedureLocalDiskFull(t *testing.T) {
for _, m := range []string{root, limit} {
requireSmallDedicatedMount(t, m)
}
env := startHandoffEnvWith(t, 1, []string{"v2"})
env := startHandoffEnvVolumes(t, 1, []string{"v2"})
if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" {
t.Cleanup(func() { copyLogs(t, env.h.dir, d) })
}
@@ -76,7 +76,7 @@ func TestProcedureLocalDiskFull(t *testing.T) {
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
hd, err := parseHead(out)
hd, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
@@ -50,7 +50,6 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...)
e2 := mustU(movedEpochTo(moved, e, g, l, "s2"))
nw := env.start(t, "blockvolume-s2", "s2")
must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2"))
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
@@ -58,7 +57,7 @@ func TestProcedurePlannedHandoffToAnotherHost(t *testing.T) {
must(wantLines(out, fmt.Sprintf("holder: r1@%d (logical replica)", e2),
fmt.Sprintf("move: request=move-v1-1 kind=clean issued=true s1/r1@%d -> s2/r1@%d HEAD generation %d remote LSN %d", e, e2, g, l)))
out, _ = h.command(t, env.chunkShow()...)
must(checkHeadReopenedBy(out, e2, g, l, "s2"))
must(checkLayoutHeadReopenedBy(out, e2, g, l, "s2"))
if !bytes.Equal(env.readBlock(t, "s2", 0), block) {
t.Fatal("the block written on s1 does not read back on s2")
}
@@ -195,24 +194,27 @@ func TestProcedureForcedMoveWithTheOldHostReturning(t *testing.T) {
t.Fatal("the block written after the last cut reads back on s2; the page says it is lost")
}
// The old host returns with its old local root, and the example unit
// (Restart=on-failure, RestartSec=5s) starts it again after it exits,
// until its start limit. Each time it must not take s2's line as its own
// (a holder is server and replica), report its frontend ready or listen
// for I/O; it logs a refusal and exits with status 75.
back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 75)
time.Sleep(5 * time.Second) // RestartSec of the example unit
again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 75)
// Control: on a fresh local root there is no stale root, so its refusal
// is the identity check alone; it also exits 75.
// The old host returns with its old local root. blockmaster refuses its
// lease with a typed MOVED (the volume moved to s2 at a newer epoch), so
// it exits 78, which the example unit does not restart
// (RestartPreventExitStatus=78); an operator's start again ends the same
// way. Each time it must not take s2's line as its own (a holder is server
// and replica), report its frontend ready or listen for I/O; it logs
// `exiting status=78 reason=moved`.
back := env.oldHostRefuses(t, "blockvolume-s1-back", env.hosts["s1"], e2, 78)
time.Sleep(5 * time.Second)
again := env.oldHostRefuses(t, "blockvolume-s1-restarted", env.hosts["s1"], e2, 78)
// Control: on a fresh local root there is no stale root; the master's
// MOVED refusal alone ends it, also with status 78.
fresh := env.hosts["s1"]
fresh.root = fresh.root + "-fresh"
freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 75)
freshRoot := env.oldHostRefuses(t, "blockvolume-s1-fresh-root", fresh, e2, 78)
// A line carries its owner and that owner's endpoints: every line
// delivered at the forced epoch, to the new owner and to each returning
// old host alike, carries s2's own endpoints, never another host's.
// delivered at the forced epoch carries s2's own endpoints, never another
// host's. A returning source can instead be refused MOVED before the
// assignment stream delivers anything (volume-lifecycle.md, do-not list).
if bad := wrongOwnerEndpoints(e2, env.hosts["s2"], nw, back, again, freshRoot); len(bad) > 0 {
t.Errorf("epoch-%d deliveries not proven to carry s2's endpoints (want data=%s ctrl=%s in every recipient's lines):\n%s",
t.Errorf("epoch-%d owner evidence invalid (want data=%s ctrl=%s in every delivery, or a moved refusal before delivery):\n%s",
e2, env.hosts["s2"].data, env.hosts["s2"].ctrl, strings.Join(bad, "\n"))
}
env.h.waitPrimaryAt(t, env.hosts["s2"].status, e2)
@@ -308,65 +310,6 @@ func TestProcedureStartInsideTheBarrierWaitIsReGranted(t *testing.T) {
}
}
// TestProcedureStartTooEarlyExitsAndARestartServes: with
// --workspace-max-clock-skew 50s the barrier is at most 95 s after the stop.
// A holder started 31 s after the stop ends its 30 s authority wait before
// the barrier: it does not serve and exits with status 75, so a supervisor
// (Restart=on-failure, RestartSec=5s) starts it again; a start that waits
// past the barrier is re-granted and serves at the same epoch.
func TestProcedureStartTooEarlyExitsAndARestartServes(t *testing.T) {
env := startHandoffEnv(t, 1, "--workspace-max-clock-skew", "50s")
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
block := pattern("start-too-early!")
env.writeBlock(t, "s1", 0, block)
first.kill(t)
time.Sleep(31 * time.Second)
// Attempt 2 starts about 66 s after the stop and its wait ends about
// 96 s after it, against a barrier of at most 95 s, so attempt 2 normally
// serves; up to 4 attempts allow for scheduling on a loaded host.
for attempt := 1; ; attempt++ {
d := env.start(t, fmt.Sprintf("blockvolume-s1-try%d", attempt), "s1")
served := false
end := time.Now().Add(45 * time.Second)
for time.Now().Before(end) {
if env.servingNow("s1") {
served = true
break
}
select {
case <-d.done:
end = time.Now()
default:
time.Sleep(200 * time.Millisecond)
}
}
if served {
if attempt == 1 {
t.Fatal("started before the barrier with its wait ending first, the holder served")
}
if got := env.adopt(t, d, "s1"); got != e {
t.Fatalf("attempt %d adopted epoch %d; want the same epoch %d", attempt, got, e)
}
break
}
if err := d.wait(5 * time.Second); exitCode(err) != 75 {
t.Fatalf("attempt %d did not serve and did not exit 75: %v", attempt, err)
}
if !d.has("blockvolume: exiting status=75 reason=assignment_timeout") {
t.Fatalf("attempt %d exited 75 without the reason assignment_timeout", attempt)
}
if attempt == 4 {
t.Fatal("four supervised starts never served")
}
time.Sleep(5 * time.Second)
}
if !bytes.Equal(env.readBlock(t, "s1", 0), block) {
t.Fatal("the block written before the stop does not read back")
}
}
// lastLogTime is the time of the last log line containing s (second
// resolution, the log's local time), or zero.
func lastLogTime(d *daemon, s string) time.Time {
@@ -422,7 +365,10 @@ func (env *handoffEnv) oldHostRefuses(t *testing.T, name string, b bvHost, e2 ui
if err := d.wait(5 * time.Second); exitCode(err) != wantExit {
failures = append(failures, fmt.Sprintf("it did not exit with status %d: %v", wantExit, err))
}
if !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") {
if wantExit == 78 && !d.has("exiting status=78 reason=moved") {
failures = append(failures, "it did not log `exiting status=78 reason=moved`")
}
if wantExit != 78 && !d.has("refusing to attach volume=v1") && !d.has("workspace lease: stale authority") && !d.has("foreign assignment") {
failures = append(failures, "it logged no refusal (stale root, stale authority, or another server's assignment)")
}
if len(failures) > 0 {
@@ -441,12 +387,12 @@ func (env *handoffEnv) servingNow(id string) bool {
func (env *handoffEnv) requireHeadHolder(t *testing.T, e uint64, host string) {
t.Helper()
out, _ := env.h.command(t, env.chunkShow()...)
head, err := parseHead(out)
head, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
if head.State != "active" || head.Epoch != e || head.Holder != host+"/r1" {
t.Fatalf("HEAD %+v; want active at epoch %d held by %s/r1", head, e, host)
if head.State != "" || head.ClaimID == "" || head.Epoch != e || head.Holder != host+"/r1" {
t.Fatalf("HEAD %+v; want live at epoch %d held by %s/r1", head, e, host)
}
}
@@ -511,14 +457,14 @@ func (env *handoffEnv) seal(t *testing.T, id string, e uint64) uint64 {
}
func (env *handoffEnv) chunkShow() []string {
return []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
return []string{"ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
}
func (env *handoffEnv) sealedLSN(t *testing.T, e, g uint64) uint64 {
t.Helper()
_, mustU := fatalOn(t)
out, _ := env.h.command(t, env.chunkShow()...)
return mustU(sealedHeadLSN(out, e, g))
return mustU(sealedLayoutHeadPosition(out, e, g))
}
func (env *handoffEnv) revoke(t *testing.T, e, g uint64) {
@@ -565,8 +511,8 @@ func (env *handoffEnv) forceMove(t *testing.T, e uint64, target, request string)
}
// wrongOwnerEndpoints returns every "assignment stream delivery" log line at epoch e (in any of ds) whose data or control
// endpoint is not owner's, plus an entry for each recipient whose log cannot be read or shows no epoch-e
// delivery at all (each recipient must positively have received the owner's line).
// endpoint is not owner's, plus an entry for each recipient whose log cannot be
// read or shows neither an epoch-e delivery nor the documented MOVED refusal.
func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string {
var bad []string
tag := fmt.Sprintf(" epoch=%d ev=", e)
@@ -586,7 +532,9 @@ func wrongOwnerEndpoints(e uint64, owner bvHost, ds ...*daemon) []string {
bad = append(bad, d.name+": "+strings.TrimSpace(l))
}
}
if seen == 0 { // positive evidence per recipient: a check that saw no forced-epoch delivery proves nothing
if seen == 0 && !strings.Contains(string(raw), "blockvolume: exiting status=78 reason=moved") {
// Mere absence proves nothing. The master's typed MOVED refusal
// ends an old source's stream before any fact can be delivered.
bad = append(bad, d.name+": no epoch delivery logged")
}
}
@@ -0,0 +1,61 @@
package main_test
import (
"encoding/json"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// chunk show marshals layout.Head, not the on-store headDoc or the retired
// storage HEAD. Keep the procedure checks tied to that actual output type.
func TestProcedureLayoutHeadChecksReadProductShape(t *testing.T) {
show := func(h layout.Head) string {
t.Helper()
b, err := json.Marshal(struct {
Head layout.Head `json:"head"`
}{h})
if err != nil {
t.Fatal(err)
}
return string(b)
}
sealed := layout.Head{Gen: 7, Epoch: 3, Holder: "s1/r1", ClaimID: "claim",
Position: 91, State: layout.StateDetached, Current: &layout.RootName{Hash: layout.Hash{1}}}
if got, err := sealedLayoutHeadPosition(show(sealed), 3, 7); err != nil || got != 91 {
t.Fatalf("detached layout image: position=%d err=%v", got, err)
}
live := sealed
live.Gen, live.Epoch, live.Holder, live.ClaimID, live.State = 8, 4, "s2/r1", "next-claim", layout.StateLive
if err := checkLayoutHeadReopenedBy(show(live), 4, 7, 91, "s2"); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
mutate func(*layout.Head)
}{
{"generation", func(h *layout.Head) { h.Gen = 6 }},
{"epoch", func(h *layout.Head) { h.Epoch++ }},
{"holder", func(h *layout.Head) { h.Holder = "foreign/r1" }},
{"claim", func(h *layout.Head) { h.ClaimID = "" }},
{"image", func(h *layout.Head) { h.Current = nil }},
{"state", func(h *layout.Head) { h.State = layout.StateDeleting }},
} {
t.Run(tc.name, func(t *testing.T) {
h := sealed
tc.mutate(&h)
if _, err := sealedLayoutHeadPosition(show(h), 3, 7); err == nil {
t.Fatal("invalid detached proof accepted")
}
h = live
tc.mutate(&h)
if err := checkLayoutHeadReopenedBy(show(h), 4, 7, 91, "s2"); err == nil {
t.Fatal("invalid successor accepted")
}
})
}
live.Position++
if err := checkLayoutHeadReopenedBy(show(live), 4, 7, 91, "s2"); err == nil {
t.Fatal("changed committed position accepted")
}
}
@@ -26,8 +26,8 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) {
env.writeCutCrashImage(t, 'A')
env.h.command(t, "ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status)
out, _ := env.h.command(t, env.chunkShow()...)
before, err := parseHead(out)
if err != nil || before.State != "active" || before.Epoch != e {
before, err := parseLayoutHead(out)
if err != nil || before.State != "" || before.ClaimID == "" || before.Epoch != e {
t.Fatalf("baseline HEAD: %+v: %v", before, err)
}
env.writeCutCrashImage(t, 'B')
@@ -55,11 +55,11 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) {
t.Fatal(err)
}
out, _ = env.h.command(t, env.chunkShow()...)
atKill, err := parseHead(out)
if err != nil || atKill.Gen != before.Gen || atKill.State != "active" || atKill.RemoteLSN != before.RemoteLSN {
atKill, err := parseLayoutHead(out)
if err != nil || atKill.Gen != before.Gen || atKill.State != "" || atKill.ClaimID != before.ClaimID || atKill.Position != before.Position {
t.Fatalf("missed mid-upload window: before=%+v stopped=%+v: %v", before, atKill, err)
}
t.Logf("kill witness: immutable keys %d -> %d, HEAD gen=%d LSN=%d remains active", keys, plainDetachStoredKeys(t, env), atKill.Gen, atKill.RemoteLSN)
t.Logf("kill witness: immutable keys %d -> %d, HEAD gen=%d LSN=%d remains active", keys, plainDetachStoredKeys(t, env), atKill.Gen, atKill.Position)
select {
case <-cli.done:
t.Fatal("detach completed or aborted before the verified kill window")
@@ -91,8 +91,8 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) {
env.requireCutCrashImage(t, "s1", 'B')
g := env.seal(t, "s1", e)
l := env.sealedLSN(t, e, g)
if l <= before.RemoteLSN {
t.Fatalf("retry did not publish the acknowledged image: remote LSN %d <= baseline %d", l, before.RemoteLSN)
if l <= before.Position {
t.Fatalf("retry did not publish the acknowledged image: remote LSN %d <= baseline %d", l, before.Position)
}
if again := env.seal(t, "s1", e); again != g {
t.Fatalf("plain seal replay changed generation %d -> %d", g, again)
@@ -52,7 +52,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
hd, err := parseHead(out)
hd, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
@@ -69,7 +69,7 @@ func storeDownDuringACut(t *testing.T, down string, cowBytes int64, cowWindow bo
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
hd, err := parseHead(out)
hd, err := parseLayoutHead(out)
if err != nil {
t.Fatal(err)
}
@@ -0,0 +1,189 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"context"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// snapshotFilerBoundary forwards the stock filer API unchanged. One applied
// write's reply is held until the test kills the holder. Thus the receipt
// proves an actual Begin, object create or Commit, independent of a delay.
// Assumptions: one snapshot at a time, capture timer/schedule disabled, no GC.
// Writers enumerated: UpdateEntry(HEAD Begin/Commit), CreateEntry(pool).
// All other writers/readers pass through; pre-restart HEAD uses the backend.
type snapshotFilerBoundary struct {
filerpb.UnimplementedSeaweedFilerServer
backend filerpb.SeaweedFilerClient
dir string
id layout.VolumeID
mu sync.Mutex
kind, name string
reached chan struct{}
release chan struct{}
hit bool
}
func newSnapshotFilerBoundary(t *testing.T, cluster *w4WeedCluster) *snapshotFilerBoundary {
t.Helper()
conn, err := grpc.NewClient(cluster.filerGRPC, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
p := &snapshotFilerBoundary{backend: filerpb.NewSeaweedFilerClient(conn)}
_, gp, _ := net.SplitHostPort(cluster.filerGRPC)
listener, err := net.Listen("tcp", net.JoinHostPort(testListenHost(), gp))
if err != nil {
t.Fatal(err)
}
backendURL, err := url.Parse("http://" + cluster.filerHTTP)
if err != nil {
t.Fatal(err)
}
_, hp, _ := net.SplitHostPort(cluster.filerHTTP)
httpListener, err := net.Listen("tcp", net.JoinHostPort(testListenHost(), hp))
if err != nil {
t.Fatal(err)
}
httpServer := &http.Server{Handler: httputil.NewSingleHostReverseProxy(backendURL), ReadHeaderTimeout: 10 * time.Second}
httpDone := make(chan struct{})
go func() { defer close(httpDone); _ = httpServer.Serve(httpListener) }()
server := grpc.NewServer()
filerpb.RegisterSeaweedFilerServer(server, p)
done := make(chan struct{})
go func() { defer close(done); _ = server.Serve(listener) }()
t.Cleanup(func() {
p.unblock()
server.Stop()
_ = listener.Close()
<-done
_ = httpServer.Close()
<-httpDone
_ = conn.Close()
})
cluster.filerGRPC = listener.Addr().String()
cluster.filerHTTP = httpListener.Addr().String()
return p
}
func (p *snapshotFilerBoundary) arm(kind, name string) <-chan struct{} {
p.mu.Lock()
defer p.mu.Unlock()
p.kind, p.name = kind, name
p.reached = make(chan struct{})
p.release = make(chan struct{})
p.hit = false
return p.reached
}
func (p *snapshotFilerBoundary) unblock() {
p.mu.Lock()
defer p.mu.Unlock()
if p.release != nil {
close(p.release)
p.release = nil
}
}
func (p *snapshotFilerBoundary) after(ctx context.Context, dir string, entry *filerpb.Entry) {
p.mu.Lock()
if p.hit || p.reached == nil || entry == nil || os.Getenv("E1_TEST_SKIP_BOUNDARY") == "1" {
p.mu.Unlock()
return
}
match := p.kind == "OBJECT" && path.Dir(dir) == path.Join(p.dir, "pool")
if dir == p.dir && entry.Name == layout.HeadName {
h, err := chunkstore.DecodeLayoutHeadEntry(entry, p.id)
if err == nil {
_, named := h.Snapshots[p.name]
match = (p.kind == "BEGIN" && h.Activity.Kind == layout.ActSnap && !named) || (p.kind == "COMMIT" && named)
}
}
if !match {
p.mu.Unlock()
return
}
p.hit = true
close(p.reached)
release := p.release
p.mu.Unlock()
select {
case <-release:
case <-ctx.Done():
}
}
func (p *snapshotFilerBoundary) head(t *testing.T) layout.Head {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
r, err := p.backend.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: p.dir, Name: layout.HeadName})
if err != nil {
t.Fatal(err)
}
h, err := chunkstore.DecodeLayoutHeadEntry(r.Entry, p.id)
if err != nil {
t.Fatal(err)
}
return h
}
func (p *snapshotFilerBoundary) LookupDirectoryEntry(ctx context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) {
return p.backend.LookupDirectoryEntry(ctx, r)
}
func (p *snapshotFilerBoundary) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) {
out, err := p.backend.CreateEntry(ctx, r)
if err == nil && out.GetErrorCode() == filerpb.FilerError_OK && out.GetError() == "" {
p.after(ctx, r.Directory, r.Entry)
}
return out, err
}
func (p *snapshotFilerBoundary) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
out, err := p.backend.UpdateEntry(ctx, r)
if err == nil {
p.after(ctx, r.Directory, r.Entry)
}
return out, err
}
func (p *snapshotFilerBoundary) DeleteEntry(ctx context.Context, r *filerpb.DeleteEntryRequest) (*filerpb.DeleteEntryResponse, error) {
return p.backend.DeleteEntry(ctx, r)
}
func (p *snapshotFilerBoundary) AssignVolume(ctx context.Context, r *filerpb.AssignVolumeRequest) (*filerpb.AssignVolumeResponse, error) {
return p.backend.AssignVolume(ctx, r)
}
func (p *snapshotFilerBoundary) LookupVolume(ctx context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) {
return p.backend.LookupVolume(ctx, r)
}
func (p *snapshotFilerBoundary) GetFilerConfiguration(ctx context.Context, r *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) {
return p.backend.GetFilerConfiguration(ctx, r)
}
func (p *snapshotFilerBoundary) ListEntries(r *filerpb.ListEntriesRequest, s grpc.ServerStreamingServer[filerpb.ListEntriesResponse]) error {
stream, err := p.backend.ListEntries(s.Context(), r)
if err != nil {
return err
}
for {
v, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if err = s.Send(v); err != nil {
return err
}
}
}
@@ -3,85 +3,37 @@
package main_test
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"path"
"sync"
"testing"
"time"
)
// restoreProgress is the restore driver's status of a target.
type restoreProgress struct {
Phase string `json:"phase"`
Running bool `json:"running"`
Filled int `json:"filled"`
Owned int `json:"owned"`
Foreign int `json:"foreign"`
Batches int `json:"batches"`
}
// restoreStatus reads target's restore status straight from its status
// server (a GET answers the status without starting a run).
func (env *handoffEnv) restoreStatus(c *http.Client, target string) (restoreProgress, string, bool) {
resp, err := c.Get("http://" + env.hosts["n-"+target].status + "/chunk/restore?volume=" + target)
if err != nil {
return restoreProgress{}, "", false
}
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
var st restoreProgress
if resp.StatusCode != http.StatusOK || json.Unmarshal(b, &st) != nil {
return restoreProgress{}, string(b), false
}
return st, string(b), true
}
// awaitRestorePhase polls target's restore status every 10 ms until ok
// holds and returns that status, logging each change with when it was seen
// (the record of where a kill landed). It fails the test if the restore
// failed, became independent first (the moment was missed), or bound passed.
// The driver's counters (filled, owned, foreign) are written when a step
// ends, not while it runs: a moment inside a step is chosen by the phase and
// the time spent in it, not by a counter.
func (env *handoffEnv) awaitRestorePhase(t *testing.T, target, what string, bound time.Duration, ok func(restoreProgress) bool) restoreProgress {
// awaitAbsent polls target's chunk status every 10 ms until ok holds for its
// count of chunks not yet local, and returns that count. A volume that was
// already fully local before ok held fails the test: the moment was missed.
func (env *handoffEnv) awaitAbsent(t *testing.T, target, what string, bound time.Duration, ok func(absent int) bool) int {
t.Helper()
c := &http.Client{Timeout: 2 * time.Second}
b := env.hosts["n-"+target]
began := time.Now()
last := restoreProgress{Phase: "-"}
last := -1
for time.Since(began) < bound {
if st, raw, good := env.restoreStatus(c, target); good {
if st != last {
t.Logf("restore of %s at +%v (waiting for %s): %+v", target, time.Since(began).Round(time.Millisecond), what, st)
last = st
}
switch {
case ok(st):
return st
case st.Phase == "failed":
t.Fatalf("restore of %s failed waiting for %s: %s", target, what, raw)
case st.Phase == "independent":
t.Fatalf("restore of %s became independent before %s was seen (the restore is too small to catch it): %s", target, what, raw)
}
absent := kzReadStats(t, b).AbsentChunks
if absent != last {
t.Logf("%s at +%v (waiting for %s): %d chunks absent", target, time.Since(began).Round(time.Millisecond), what, absent)
last = absent
}
if ok(absent) {
return absent
}
if absent == 0 {
t.Fatalf("%s hydrated before %s was seen (the restore is too small to catch it)", target, what)
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("restore of %s: %s not seen within %v", target, what, bound)
return restoreProgress{}
}
// requireRestoreState reads target's restore status once and fails the test
// unless the run is still going and ok holds: the check, right before a
// kill, that the kill lands where the test says.
func (env *handoffEnv) requireRestoreState(t *testing.T, target, what string, ok func(restoreProgress) bool) restoreProgress {
t.Helper()
st, raw, good := env.restoreStatus(&http.Client{Timeout: 2 * time.Second}, target)
if !good || !st.Running || !ok(st) {
t.Fatalf("restore of %s is no longer %s before the kill: %s", target, what, raw)
}
return st
t.Fatalf("%s: %s not seen within %v (last %d chunks absent)", target, what, bound, last)
return -1
}
// requireBlocksOf reads every block of img on the host and requires each to
@@ -117,29 +69,6 @@ func denseImage(tag string, chunks []uint64) map[uint64][]byte {
return img
}
// independent reports whether target's independence marker exists, read
// from the filer (not through the product's status, which reports only a
// run of this process).
func (env *handoffEnv) independent(t *testing.T, target string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
p := path.Join(env.chunkPath, target, "RESTORE-INDEPENDENT")
resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true")
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode)
return false
}
// subsetOf returns the blocks of img in the given chunks.
func subsetOf(img map[uint64][]byte, chunks []uint64) map[uint64][]byte {
in := map[uint64]bool{}
@@ -167,31 +96,106 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon {
return d
}
// TestSnapshotLadderC3KilledHydratingAndBeforeIndependence: a restore of a
// snapshot of 32 full chunks of incompressible data into v2 (128 MiB to make
// local at the driver's 64 MiB/s: about 2 s of hydrating).
// fillReader reads one block of each of its chunks, in order, on its own
// connection: v1 fills a restore target only on access, so this is the fill
// the test kills into. It stops at its first error (the kill, or a failure
// before it, which state reports) or at stop, which waits for it. Its stop
// also runs at the test's cleanup, so a failure before the explicit stop
// still ends and joins the reader.
type fillReader struct {
mu sync.Mutex
reads int64
err error
finished bool
quit chan struct{}
done chan struct{}
close func()
once sync.Once
}
func (env *handoffEnv) readConcurrently(t *testing.T, target string, chunks []uint64) *fillReader {
t.Helper()
c := dialNVMe(t, env.hosts["n-"+target].nvme, plannedHandoffNQN)
r := &fillReader{quit: make(chan struct{}), done: make(chan struct{}), close: c.close}
t.Cleanup(r.stop)
go func() {
defer close(r.done)
for _, ch := range chunks {
select {
case <-r.quit:
return
default:
}
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
_, err := c.tryRead(ch*ladderChunkBlocks, 4096)
r.mu.Lock()
if err != nil {
r.err = err
} else {
r.reads++
}
r.mu.Unlock()
if err != nil {
return
}
}
r.mu.Lock()
r.finished = true
r.mu.Unlock()
}()
return r
}
// progress is the reader's state against baseline absent chunks and absent now.
func (r *fillReader) progress(baseline, absent int) fillProgress {
r.mu.Lock()
defer r.mu.Unlock()
return fillProgress{baseline: baseline, absent: absent, reads: r.reads, readerErr: r.err, finished: r.finished}
}
func (r *fillReader) stop() {
r.once.Do(func() {
close(r.quit)
r.close()
<-r.done
})
}
// awaitFill waits until fillWitness accepts the reader's progress on target
// (a fill observably running) and fails the test with the last reason when
// it does not within bound.
func (env *handoffEnv) awaitFill(t *testing.T, target string, r *fillReader, baseline int, bound time.Duration) fillProgress {
t.Helper()
var p fillProgress
var why error
for end := time.Now().Add(bound); ; time.Sleep(20 * time.Millisecond) {
p = r.progress(baseline, kzReadStats(t, env.hosts["n-"+target]).AbsentChunks)
if why = fillWitness(p); why == nil {
return p
}
if p.readerErr != nil || p.finished || time.Now().After(end) {
t.Fatalf("%s: no running fill to kill into within %v: %v (%+v)", target, bound, why, p)
}
}
}
// TestSnapshotLadderC3KilledHydrating: a restore of a snapshot of 32 full
// chunks of incompressible data into v2 (128 MiB), its blockvolume killed
// (SIGKILL) while chunks are being made local. v1 fills a restore target only
// on access, so a reader drives the fill.
//
// 1. Its blockvolume is killed (SIGKILL) one second into hydrating and
// started again. Every other chunk is read back (a partly filled chunk
// must never be served), which makes those chunks local and leaves the
// rest to the driver, and the driver is started again.
// 2. The resumed run must report, when its hydrating step ends, that it
// filled some chunks and not all (0 < filled < 32: it resumed from a
// partly local volume). Then, the run still going and not independent,
// the guest writes to v2 (acknowledged); checked still running and not
// independent, the blockvolume is killed again and restarted. Before the
// driver is started again the independence marker must be absent (the
// kill landed before independence); every acknowledged write reads back.
// 3. The driver is started again, the guest writes once more, and the run
// reaches independence (per its status and the marker). Then v2 holds
// the snapshot with every acknowledged write over it, read back in full,
// and the source's snapshot, restored again into v3, is unchanged (none
// of v2's writes in it).
//
// Not covered: guest writes while the driver reports Owning. The status
// shows owning only once the single batch (32 chunks, under the 64-chunk
// batch) has ended, a few ms before independent.
func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) {
// 1. Killed with some chunks local and some not, then started again (fill
// progress not yet written at a checkpoint may be lost: those chunks
// are fetched again). Every other chunk is read back: each is the
// snapshot's (a partly filled chunk is never served).
// 2. The guest writes (acknowledged); killed again while a fill is running
// and restarted, every acknowledged write reads back.
// 3. The guest writes once more and every chunk is made local (no chunk
// absent).
// v2 holds the snapshot with every acknowledged write over it, read back
// in full, and the source's snapshot, restored again into v3, is
// unchanged (none of v2's writes in it).
func TestSnapshotLadderC3KilledHydrating(t *testing.T) {
env := startLadderEnv(t, "v2", "v3")
var chunks []uint64
for c := uint64(0); c < 32; c++ {
@@ -201,56 +205,51 @@ func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) {
env.writeImage(t, "s1", src)
env.snapshot(t, "s1", "v1", "base")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "base", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
target := env.startTarget(t, "v2", "blockvolume-v2")
drive := func() {
t.Helper()
env.h.command(t, "ops", "chunk", "restore", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status)
}
drive()
// Killed one second into hydrating.
env.awaitRestorePhase(t, "v2", "hydrating", 120*time.Second, func(s restoreProgress) bool { return s.Phase == "hydrating" })
time.Sleep(time.Second)
st := env.requireRestoreState(t, "v2", "hydrating", func(s restoreProgress) bool { return s.Phase == "hydrating" })
// (1) killed mid-fill
partly := func(absent int) bool { return absent > 0 && absent < len(chunks) }
reader := env.readConcurrently(t, "v2", chunks)
absent := env.awaitAbsent(t, "v2", "a partly filled volume", 120*time.Second, partly)
if p := reader.progress(len(chunks), absent); p.readerErr != nil {
t.Fatalf("the first fill's reader failed before the kill: %v", p.readerErr)
}
target.kill(t)
t.Logf("killed 1 s into hydrating: %+v", st)
target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill")
reader.stop()
t.Logf("killed with %d of %d chunks absent", absent, len(chunks))
target = env.startTarget(t, "v2", "blockvolume-v2-after-fill-kill")
// Fill progress is written at the store's next checkpoint, so a kill
// may lose some or all of it (standalone-deployment.md, restore step 4):
// such chunks are absent again and are fetched again on their next read.
t.Logf("after the restart %d of %d chunks are absent", kzReadStats(t, env.hosts["n-v2"]).AbsentChunks, len(chunks))
var even []uint64
for c := uint64(0); c < 32; c += 2 {
even = append(even, c)
}
env.requireBlocksOf(t, "n-v2", subsetOf(src, even)) // no partly filled chunk is served
drive()
// The resumed run: it fills what is not local yet; then, before
// independence, written and killed.
notDone := func(s restoreProgress) bool { return s.Phase != "independent" }
st = env.awaitRestorePhase(t, "v2", "the resumed run's hydrating step ended", 60*time.Second, func(s restoreProgress) bool {
return s.Running && s.Filled > 0 && notDone(s)
})
if st.Filled >= len(chunks) {
t.Fatalf("the resumed run filled %d chunks: it did not resume from a partly local volume (%d read back before it)", st.Filled, len(even))
}
// (2) written, then killed again while a fill is running
w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3)
env.writeImage(t, "n-v2", w1)
st = env.requireRestoreState(t, "v2", "running and not independent", notDone)
target.kill(t)
t.Logf("killed in the resumed run after it filled %d of %d chunks, after the write: %+v", st.Filled, len(chunks), st)
target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill")
if env.independent(t, "v2") {
t.Fatal("the independence marker exists after the second kill: the kill did not land before independence")
var odd []uint64
for c := uint64(1); c < 32; c += 2 {
odd = append(odd, c)
}
baseline := kzReadStats(t, env.hosts["n-v2"]).AbsentChunks
reader = env.readConcurrently(t, "v2", odd)
p := env.awaitFill(t, "v2", reader, baseline, 60*time.Second)
target.kill(t)
reader.stop()
t.Logf("killed again with a fill running: %d absent (%d when its reader started), %d reads done", p.absent, p.baseline, p.reads)
target = env.startTarget(t, "v2", "blockvolume-v2-after-write-kill")
env.requireBlocksOf(t, "n-v2", w1) // every acknowledged write survived the kill
drive()
// (3) every chunk made local
w2 := ladderImage("c3kw2", []uint64{17, 44, 60}, 2) // not chunk 40: requireEdges keeps it untouched
env.writeImage(t, "n-v2", w2)
env.waitIndependent(t, "v2")
if !env.independent(t, "v2") {
t.Fatal("the restore status says independent but the marker is absent")
}
env.hydrate(t, "v2")
env.requireImage(t, "n-v2", mergeImages(src, w1, w2))
env.restoreChecked(t, "base", "v3", src, w1, w2)
}
@@ -7,11 +7,12 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// Rung D of the snapshot ladder: deletes. D1-D3 are the logical delete: a
@@ -21,23 +22,10 @@ import (
// name), so they prove nothing about reclamation. D4 runs the collector and
// measures what it reclaims.
//
// The collector's grace may not be shorter than the operation deadline plus
// the clock skew plus the CAS apply bound (11 minutes with the defaults), and
// an unreferenced chunk is reclaimed only by a second mark at least the grace
// after the first, on a chunk older than the grace: D4 runs for about 25
// minutes.
const (
ladderGCGrace = 11 * time.Minute
// ladderGCWait is the grace plus the collector's clock skew allowance
// and its one-second timestamp resolution, with a margin.
ladderGCWait = ladderGCGrace + time.Minute + 15*time.Second
)
// deleteSnapshot deletes vol's snapshot name and checks the answer names it.
func (env *handoffEnv) deleteSnapshot(t *testing.T, vol, name string) {
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "snapshot-delete", "--volume", vol, "--name", name,
out, _ := env.h.command(t, "ops", "chunk", "snapshot-delete", "--master", env.h.masterAddr, "--volume", vol, "--name", name,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
var body struct {
VolumeID string `json:"volumeID"`
@@ -48,16 +36,60 @@ func (env *handoffEnv) deleteSnapshot(t *testing.T, vol, name string) {
}
}
// holderDeleteSnapshot deletes vol's snapshot name through its holder's
// control route (POST /chunk/snapshot/delete on hostID's status listener),
// which runs the holder's cleaning pass right after the delete. It returns
// the HTTP status and body.
//
// A snapshot delete is one conditional update of HEAD. The holder's
// cleaning (kicked by the previous delete) also updates HEAD, so a delete
// that read HEAD just before can lose its update ("HEAD generation moved")
// and change nothing; ops chunk snapshot-delete reports that as a retryable
// conflict. Only that answer is retried, within 30 s; any other is returned.
func (env *handoffEnv) holderDeleteSnapshot(t *testing.T, hostID, vol, name string) (int, string) {
t.Helper()
body, _ := json.Marshal(map[string]string{"volumeID": vol, "name": name})
c := &http.Client{Timeout: 2 * time.Minute}
for end := time.Now().Add(30 * time.Second); ; time.Sleep(200 * time.Millisecond) {
resp, err := c.Post("http://"+env.hosts[hostID].status+"/chunk/snapshot/delete", "application/json", strings.NewReader(string(body)))
if err != nil {
t.Fatal(err)
}
out, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
if resp.StatusCode == http.StatusOK || !strings.Contains(string(out), "HEAD generation moved") || time.Now().After(end) {
return resp.StatusCode, string(out)
}
t.Logf("holder delete of %s lost its HEAD update to a concurrent change; retrying: %s", name, out)
}
}
// poolObjects counts the chunk objects in vol's pool (every shard
// directory): what the volume stores, whatever names it.
func (env *handoffEnv) poolObjects(t *testing.T, vol string) int {
t.Helper()
id, err := layout.ParseVolumeID(env.layoutID(vol))
if err != nil {
t.Fatal(err)
}
pool := path.Join(env.chunkPath, layout.VolumeDir(vol, id), layout.PoolDir)
n := 0
for shard := range env.filerNames(t, pool) {
n += len(env.filerNames(t, path.Join(pool, shard)))
}
return n
}
// requireSnapshotNames checks vol's snapshot list is exactly names, in order.
func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...string) {
t.Helper()
list := env.snapshots(t, vol, "")
ok := len(list) == len(names)
for i := 0; ok && i < len(list); i++ {
ok = list[i].Name == names[i] && list[i].State == "active"
ok = list[i].Name == names[i]
}
if !ok {
t.Fatalf("snapshots of %s: %+v; want exactly %v, active", vol, list, names)
t.Fatalf("snapshots of %s: %+v; want exactly %v", vol, list, names)
}
}
@@ -67,7 +99,7 @@ func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...s
func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte, later ...map[uint64][]byte) {
t.Helper()
env.restoreInto(t, "v1", snap, target)
env.waitIndependent(t, target)
env.hydrate(t, target)
env.requireImage(t, "n-"+target, img, later...)
}
@@ -130,261 +162,44 @@ func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) {
env.restoreChecked(t, "s2", "v3", map[uint64][]byte{7: b})
}
// gcObject is one chunk object a collector pass names as eligible.
type gcObject struct {
Volume string `json:"volume"`
Key string `json:"key"`
FID string `json:"fid"`
}
// chunkKeys lists the names (unescaped) of v1's chunk-key bindings, read
// straight from the filer's directory listing, not through the collector.
func (env *handoffEnv) chunkKeys(t *testing.T, vol string) map[string]bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
dir := path.Join(env.chunkPath, vol, "keys") + "/"
keys := map[string]bool{}
for last := ""; ; {
req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"?limit=1000&lastFileName="+url.QueryEscape(last), nil)
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
var page struct {
Entries []struct {
FullPath string `json:"FullPath"`
} `json:"Entries"`
LastFileName string `json:"LastFileName"`
ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"`
}
err = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
if err != nil || resp.StatusCode != http.StatusOK {
t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err)
}
for _, e := range page.Entries {
name, err := url.PathUnescape(path.Base(e.FullPath))
if err != nil {
t.Fatalf("chunk key %q: %v", e.FullPath, err)
}
keys[name] = true
}
if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last {
return keys
}
last = page.LastFileName
}
}
// objectsByKey indexes collector objects by key and counts the records that
// are not distinct v1 chunk objects (another volume, an empty field, or a
// key or fid named again).
func objectsByKey(objs []gcObject) (map[string]gcObject, int) {
byKey, fids, odd := map[string]gcObject{}, map[string]bool{}, 0
for _, o := range objs {
_, dup := byKey[o.Key]
if o.Volume != "v1" || o.Key == "" || o.FID == "" || fids[o.FID] || dup {
odd++
continue
}
byKey[o.Key], fids[o.FID] = o, true
}
return byKey, odd
}
// requireBudget fails the test before it starts anything when the test
// binary's deadline leaves less than need: a wait cut short by the package
// timeout would skip the harness's cleanup.
func requireBudget(t *testing.T, need time.Duration) {
t.Helper()
if dl, ok := t.Deadline(); ok && time.Until(dl) < need {
t.Fatalf("this test needs %v; the test deadline leaves %v (run with -timeout 45m)", need, time.Until(dl).Round(time.Second))
}
}
// gc runs one collector pass (applying or a preview) and returns the chunk
// objects it found eligible and how many it reclaimed.
func (env *handoffEnv) gc(t *testing.T, apply bool) ([]gcObject, int) {
t.Helper()
args := []string{"ops", "chunk", "gc", "--master", env.h.masterAddr, "--grace", ladderGCGrace.String(),
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if apply {
args = append(args, "--apply")
}
out, _ := env.h.command(t, args...)
var body struct {
MarkSaved bool `json:"mark_saved"`
UnknownOutcomes []string `json:"unknown_outcomes"`
FailedDeletes []any `json:"failed_deletes"`
WouldDelete []gcObject `json:"would_delete"`
Candidates int
Reclaimed int
}
if err := json.Unmarshal([]byte(out), &body); err != nil || (apply && !body.MarkSaved) || len(body.UnknownOutcomes) != 0 || len(body.FailedDeletes) != 0 {
t.Fatalf("gc pass (apply %v): %v\n%s", apply, err, out)
}
t.Logf("gc pass (apply %v): %d candidates, %d eligible, %d reclaimed", apply, body.Candidates, len(body.WouldDelete), body.Reclaimed)
return body.WouldDelete, body.Reclaimed
}
// exclusiveBytes is what the usage command says deleting snapshot name of vol
// makes eligible for collection: the chunk bytes no other holder references.
func (env *handoffEnv) exclusiveBytes(t *testing.T, vol, name string) uint64 {
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "usage", "--volume", vol,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
var u struct {
Snapshots []struct {
Name string `json:"name"`
ExclusiveBytes uint64 `json:"exclusiveBytes"`
} `json:"snapshots"`
}
if err := json.Unmarshal([]byte(out), &u); err != nil {
t.Fatalf("usage of %s: %v\n%s", vol, err, out)
}
for _, s := range u.Snapshots {
if s.Name == name {
return s.ExclusiveBytes
}
}
t.Fatalf("usage of %s has no snapshot %s\n%s", vol, name, out)
return 0
}
// blobStored reports whether the weed store still holds the chunk data of
// fid (a volume server answers 200 for it, 404 once it is deleted).
func (env *handoffEnv) blobStored(t *testing.T, fid string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
vid, _, ok := strings.Cut(fid, ",")
if !ok {
t.Fatalf("chunk object fid %q has no volume id", fid)
}
resp, err := c.Get("http://" + env.cluster.master + "/dir/lookup?volumeId=" + vid)
if err != nil {
t.Fatal(err)
}
var lookup struct {
Locations []struct {
URL string `json:"url"`
} `json:"locations"`
}
err = json.NewDecoder(resp.Body).Decode(&lookup)
resp.Body.Close()
if err != nil || len(lookup.Locations) == 0 {
t.Fatalf("weed lookup of volume %s: %v %+v", vid, err, lookup)
}
resp, err = c.Get("http://" + lookup.Locations[0].URL + "/" + fid)
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("weed read of %s: status %d", fid, resp.StatusCode)
return false
}
// TestSnapshotLadderD4DeleteAllButOneThenCollect is a MEASUREMENT, not a
// pass/fail rung: what the collector reclaims after deletes, against an
// expected set taken independently of it. Three snapshots, each overwriting
// the same four chunks; the third and then the second are deleted. The
// third's chunks are still HEAD's, so the bindings the second's cut created
// (those that appear in the filer between the first and the second
// snapshot) are referenced by nothing. Two collector passes the grace apart
// run; the test reports, in one MEASUREMENT line, how many of the expected
// bindings a preview names and the applying pass reclaims, how many of
// those are gone from the weed store, what else either pass named, and the
// surplus left. It fails only when the harness cannot measure (the setup
// did not create the expected bindings, a command failed) or when data is
// lost: HEAD must still read the newest content and the remaining snapshot
// restore as it was.
//
// What is measured is chunk data in the weed store for the bindings the
// deleted snapshot alone created, not filer entries and not the whole store.
// The known surplus of today's format, not measured:
// - a reclaimed binding's filer entry is kept for ever (marked reclaimed),
// so filer entry counts and usage's stored bindings and stored bytes do
// not fall after collection;
// - a needle uploaded before its binding was written (a retried upload)
// cannot be enumerated and is never reclaimed;
// - disk space returns only when weed compacts its volume.
// TestSnapshotLadderD4DeleteAllButOneThenCollect: three snapshots, each
// overwriting the same four chunks; the third and then the second are
// deleted through the holder, whose cleaning pass runs right after each
// delete. The third's chunks are still HEAD's, so deleting it frees nothing;
// the second's four chunks are named by nothing after its delete, and the
// cleaning removes exactly those from the pool. No data is lost: HEAD reads
// the newest content and the remaining snapshot restores as it was.
func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) {
requireBudget(t, 2*ladderGCWait+10*time.Minute)
env := startLadderEnv(t, "v2")
chunks := []uint64{0, 1, 2, 3}
imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)}
uploads := make([]int, len(imgs))
keysAfter := make([]map[string]bool, len(imgs))
for i, img := range imgs {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))
uploads[i] = env.lastCutUploads(t, "s1", "v1")
keysAfter[i] = env.chunkKeys(t, "v1")
}
expected := map[string]bool{} // the bindings the second snapshot's cut created
for k := range keysAfter[1] {
if !keysAfter[0][k] {
expected[k] = true
stored := env.poolObjects(t, "v1")
t.Logf("after three snapshots the pool holds %d chunk objects", stored)
collect := func(name string, freed int) {
t.Helper()
if code, out := env.holderDeleteSnapshot(t, "s1", "v1", name); code != http.StatusOK {
t.Fatalf("holder delete of %s: status %d: %s", name, code, out)
}
want := stored - freed
end := time.Now().Add(60 * time.Second)
got := env.poolObjects(t, "v1")
for got != want && time.Now().Before(end) {
time.Sleep(500 * time.Millisecond)
got = env.poolObjects(t, "v1")
}
if got != want {
t.Fatalf("after deleting %s the pool holds %d chunk objects; want %d (%d freed)", name, got, want, freed)
}
stored = got
}
t.Logf("the second snapshot's cut uploaded %d chunks and created %d bindings", uploads[1], len(expected))
if len(expected) < len(chunks) {
t.Fatalf("the second snapshot's cut created %d bindings; want at least one per overwritten chunk (%d)", len(expected), len(chunks))
}
if uploads[1] != len(chunks) {
t.Fatalf("the second snapshot's cut uploaded %d chunks; want the %d it overwrote", uploads[1], len(chunks))
}
env.deleteSnapshot(t, "v1", "s3")
exclusive := env.exclusiveBytes(t, "v1", "s2")
env.deleteSnapshot(t, "v1", "s2")
collect("s3", 0) // its chunks are HEAD's
collect("s2", len(chunks)) // named by nothing now
env.requireSnapshotNames(t, "v1", "s1")
deleted := time.Now()
requireBudget(t, time.Until(deleted.Add(ladderGCWait))+ladderGCWait+5*time.Minute)
time.Sleep(time.Until(deleted.Add(ladderGCWait))) // the chunks are older than the grace
_, firstReclaimed := env.gc(t, true)
first := time.Now()
requireBudget(t, ladderGCWait+5*time.Minute)
time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first
eligible, _ := env.gc(t, false)
named, oddPreview := objectsByKey(eligible)
namedExpected, namedOther, storedBefore := 0, 0, 0
for k, o := range named {
if !expected[k] {
namedOther++
continue
}
namedExpected++
if env.blobStored(t, o.FID) {
storedBefore++
}
}
reclaimedObjs, n := env.gc(t, true)
reclaimed, oddApply := objectsByKey(reclaimedObjs)
reclaimedExpected, reclaimedOther, goneAfter := 0, 0, 0
for k, o := range reclaimed {
if !expected[k] {
reclaimedOther++
continue
}
reclaimedExpected++
if !env.blobStored(t, o.FID) {
goneAfter++
}
}
t.Logf("D4 MEASUREMENT: expected %d bindings (s2's cut uploaded %d chunks; usage: deleting s2 frees %d bytes); "+
"first mark reclaimed %d; preview named %d of them (%d still in the store), %d others, %d malformed; "+
"apply reclaimed %d (%d of them, %d now gone from the store), %d others, %d malformed; surplus left: %d of the expected",
len(expected), uploads[1], exclusive, firstReclaimed, namedExpected, storedBefore, namedOther, oddPreview,
n, reclaimedExpected, goneAfter, reclaimedOther, oddApply, len(expected)-goneAfter)
env.requireImage(t, "s1", imgs[2])
env.restoreChecked(t, "s1", "v2", imgs[0], imgs[1], imgs[2])
}
@@ -6,42 +6,18 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// Rung E of the snapshot ladder: faults. E1 kills the holder (SIGKILL) while
// a snapshot is being taken, at several points of the snapshot, and restarts
// it within its lease. The per-step crash cases of the catalog half (after
// the name record, after the intent, with the attempt create unknown) are
// pinned by a unit test of the catalog; this rung is the same property
// through the real processes.
// nameRecorded reports whether vol's catalog holds a name record for the
// snapshot name, read from the filer (not through the product).
func (env *handoffEnv) nameRecorded(t *testing.T, vol, name string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
p := path.Join(env.chunkPath, vol, "snapnames", url.PathEscape(name))
resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true")
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode)
return false
}
// Rung E: kill the real holder at applied Begin, object and Commit writes.
// The filer's reply is held until SIGKILL, and HEAD is observed before restart.
// Per-write kernel controls remain TestSnapshotSession_InterruptAtEveryStep.
// filerNames lists the entry names (unescaped) of a filer directory, read
// straight from the filer (not through the product); a missing directory
@@ -86,45 +62,28 @@ func (env *handoffEnv) filerNames(t *testing.T, dir string) map[string]bool {
}
}
// TestSnapshotLadderE1CrashDuringASnapshot: rounds on one volume. In each,
// blocks in twelve chunks are written and acknowledged (so the snapshot's cut
// has twelve chunks to upload), a snapshot with a fixed request id is
// started, and the holder is killed after a different delay (from at once to
// well after the answer), then restarted within its lease. Each kill's step
// is recorded from what it left, read from the filer and the list (not
// through the snapshot's own answer):
// - ANSWERED: the command answered success before the kill;
// - PUBLISHED: no answer, but the snapshot is listed after the restart
// (the attempt entry was written; the answer was lost);
// - CATALOG: no answer, not listed, but the name record exists (the kill
// landed in the catalog steps, before the attempt entry);
// - CUT: no answer, no name record, but an intent that was not there
// before the request (the kill landed in the snapshot's cut, which
// writes its intent first);
// - BEFORE: none of these.
//
// The test fails as inconclusive unless at least one kill is PUBLISHED,
// CATALOG or CUT (inside the snapshot). After each restart, before the
// retry:
// - the snapshot is listed at most once and only active; an ANSWERED one
// is listed, at the cut its answer gave;
// - one more block is written (acknowledged).
//
// Then a retry with the same request id completes the snapshot, listed once:
// at the cut listed before the retry if it was listed (a replay), else at a
// new cut that holds the post-restart block. At the end a next snapshot is
// taken after more writes. Every round's snapshot and the next one restore
// (to independence, per the restore status) exactly as expected: the blocks
// acknowledged before it, the post-restart block only when the retry cut
// anew, and every block written after it reading zero.
// TestSnapshotLadderE1CrashDuringASnapshot retains the data/replay/restore
// oracle, but reaches each crash boundary causally through the stock filer.
// A missed boundary is inconclusive, never a successful BEFORE-only campaign.
func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
delays := []time.Duration{0, 25 * time.Millisecond, 50 * time.Millisecond, 75 * time.Millisecond,
100 * time.Millisecond, 125 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond, 600 * time.Millisecond}
boundaries := []string{"BEGIN", "OBJECT", "COMMIT"}
var targets []string
for i := 0; i <= len(delays); i++ {
for i := 0; i <= len(boundaries); i++ {
targets = append(targets, fmt.Sprintf("v%d", i+2))
}
env := startHandoffEnvWith(t, 1, targets)
if testListenHost() != "127.0.0.1" {
t.Fatal("causal filer fixture requires loopback")
}
var boundary *snapshotFilerBoundary
cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32,
FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }})
env := startHandoffEnvOnCluster(t, 1, targets, procedureTLSConfig(), false, cluster)
id, err := layout.ParseVolumeID(env.layoutID("v1"))
if err != nil {
t.Fatal(err)
}
boundary.id = id
boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id))
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
holder := env.start(t, "blockvolume-v1", "s1")
e := env.adopt(t, holder, "s1")
@@ -139,14 +98,13 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
var images []map[uint64][]byte // what each round's snapshot must hold
cum := map[uint64][]byte{0: marker}
steps := map[string]int{}
for k, delay := range delays {
for k, kind := range boundaries {
img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 3)
env.writeImage(t, "s1", img)
cum = mergeImages(cum, img)
name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k)
intents := path.Join(env.chunkPath, "v1", "intents")
before := env.filerNames(t, intents)
reached := boundary.arm(kind, name)
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
done := make(chan result, 1)
go func() {
@@ -154,9 +112,23 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
"--name", name, "--request-id", req)
done <- result{out, errOut, code, err}
}()
time.Sleep(delay)
select {
case <-reached:
case <-time.After(30 * time.Second):
cancel()
boundary.unblock()
<-done
t.Fatalf("inconclusive: snapshot never reached applied %s boundary", kind)
}
holder.kill(t)
killed := time.Now()
// Restart can abort the old session, so read the real backend first.
crashed := boundary.head(t)
_, published := crashed.Snapshots[name]
if kind == "COMMIT" && !published || kind != "COMMIT" && (published || crashed.Activity.Kind != layout.ActSnap) {
t.Fatalf("boundary %s disagrees with pre-restart HEAD: %+v", kind, crashed)
}
boundary.unblock()
var r result
select {
case r = <-done:
@@ -171,11 +143,6 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
}
cancel()
answered := r.err == nil && r.code == 0
newIntent := false
for n := range env.filerNames(t, intents) {
newIntent = newIntent || !before[n]
}
named := env.nameRecorded(t, "v1", name)
// Restarted within the lease, as the unit's RestartSec does: the same
// epoch, serving the blocks written before the kill.
@@ -190,34 +157,19 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
env.requireImage(t, "s1", cum)
pre := env.snapshots(t, "v1", name)
step := "BEFORE"
switch {
case answered:
step = "ANSWERED"
case len(pre) == 1:
step = "PUBLISHED"
case named:
step = "CATALOG"
case newIntent:
step = "CUT"
}
step := kind
steps[step]++
t.Logf("round %d (kill after %v): step %s (exit %d err %v; name record %v, new intent %v, listed %v); adopted %v and frontend ready %v after the kill",
k, delay, step, r.code, r.err, named, newIntent, len(pre) == 1, adopted.Round(time.Millisecond), time.Since(killed).Round(time.Millisecond))
if published != (len(pre) == 1) {
t.Fatalf("round %d: pre-restart HEAD published=%v but restart lists %+v", k, published, pre)
}
t.Logf("round %d: applied %s, pre-restart HEAD gen=%d activity=%s published=%v; exit %d err %v; adopted %v after kill",
k, step, crashed.Gen, crashed.Activity.Kind, published, r.code, r.err, adopted.Round(time.Millisecond))
switch {
case len(pre) > 1:
t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(pre), pre)
case len(pre) == 1 && pre[0].State != "active":
t.Fatalf("round %d: %s listed but not active: %+v", k, name, pre[0])
case answered && len(pre) == 0:
t.Fatalf("round %d: %s answered success before the kill but is not listed: %s", k, name, r.out)
}
if answered {
var a snapshotInfo
if err := json.Unmarshal([]byte(r.out), &a); err != nil || a.CutLSN != pre[0].CutLSN || a.HeadGen != pre[0].HeadGen {
t.Fatalf("round %d: %s answered %s before the kill but is listed as %+v", k, name, r.out, pre[0])
}
}
// 16 bytes: pattern repeats it to exactly one block.
post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!!", k))}
env.writeImage(t, "s1", post)
@@ -228,12 +180,13 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name {
t.Fatalf("round %d: retry of %s: %v %s", k, name, err, out)
}
if len(pre) == 1 && (info.CutLSN != pre[0].CutLSN || info.HeadGen != pre[0].HeadGen) {
t.Fatalf("round %d: %s was listed as %+v before the retry, which answered %+v: a listed snapshot was taken again", k, name, pre[0], info)
}
if l := env.snapshots(t, "v1", name); len(l) != 1 || l[0].State != "active" || l[0].CutLSN != info.CutLSN {
l := env.snapshots(t, "v1", name)
if len(l) != 1 || l[0].Root == "" {
t.Fatalf("round %d: after the retry %s is listed as %+v; its retry answered %+v", k, name, l, info)
}
if len(pre) == 1 && l[0].Root != pre[0].Root {
t.Fatalf("round %d: %s was listed as %+v before the retry and as %+v after it: a listed snapshot was taken again", k, name, pre[0], l[0])
}
if len(pre) == 1 {
images = append(images, cum) // a replay: the post-restart block is not in it
} else {
@@ -241,8 +194,8 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
}
cum = mergeImages(cum, post)
}
t.Logf("kill steps: %v; the catalog steps (CATALOG, PUBLISHED) are pinned per step by TestCatalogRestartAfterAbandonedSnapshot", steps)
if steps["PUBLISHED"]+steps["CATALOG"]+steps["CUT"] == 0 {
t.Logf("kill steps: %v; per-write cases pinned by TestSnapshotSession_InterruptAtEveryStep", steps)
if steps["BEGIN"] != 1 || steps["OBJECT"] != 1 || steps["COMMIT"] != 1 {
t.Fatalf("inconclusive: no kill landed inside a snapshot (steps %v)", steps)
}
@@ -251,9 +204,10 @@ func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
env.snapshot(t, "s1", "v1", "e1-next")
final := mergeImages(cum, next)
for k := range delays {
for k := range boundaries {
later := []map[uint64][]byte{final}
env.restoreChecked(t, fmt.Sprintf("e1-%d", k), targets[k], images[k], later...)
}
env.restoreChecked(t, "e1-next", targets[len(delays)], final)
env.restoreChecked(t, "e1-next", targets[len(boundaries)], final)
t.Logf("final restore oracle reached: %d crash snapshots plus next snapshot read back", len(boundaries))
}
@@ -43,7 +43,9 @@ import (
// write period, so writes run before, during and after the snapshots),
// F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the
// limiter checks, a smoke may leave it unset), F1_HOST_LIMIT_SLOTS
// (the limiter's normal slots; default hostlimit's), F1_REPORT.
// (the limiter's normal slots; default hostlimit's), F1_REPORT,
// F1_NVME_RETRIES (5: the load writers retry a refused command as the Linux
// NVMe host does, see retryLikeHost; 0 turns the retries off).
//
// Each volume has two regions. The ledger region is written and flushed
// before a round's snapshot, so the snapshot must hold it exactly. The load
@@ -60,6 +62,7 @@ type f1Config struct {
LedgerBlocksPerRnd int
LoadSpan int
ControlPauseSecs int
NVMeRetries int
}
func f1ConfigFromEnv(t *testing.T) f1Config {
@@ -87,7 +90,8 @@ func f1ConfigFromEnv(t *testing.T) f1Config {
}
c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120),
HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots),
Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192), SlotRetryBound: time.Duration(retry) * time.Second}
Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192), SlotRetryBound: time.Duration(retry) * time.Second,
NVMeRetries: num("F1_NVME_RETRIES", nvmeHostMaxRetries)}
if v := os.Getenv("F1_CONTROL_PAUSE_SECONDS"); v != "" {
c.ControlPauseSecs = num("F1_CONTROL_PAUSE_SECONDS", 0)
}
@@ -111,17 +115,22 @@ type f1Sample struct {
// f1Round is one volume's measurements in one round.
type f1Round struct {
Volume string `json:"volume"`
Round int `json:"round"`
SnapshotMs float64 `json:"snapshot_request_to_commit_ms"`
CutTotalMs float64 `json:"cut_total_ms"`
BarrierPauseMs float64 `json:"cut_barrier_pause_ms"`
UploadedChunks int `json:"uploaded_chunks"`
UploadedBytes int64 `json:"uploaded_bytes"`
HostSlotWaits uint64 `json:"host_slot_waits"`
SlotRetries int `json:"snapshot_slot_refusals_retried"`
SlotWaitMs float64 `json:"snapshot_slot_wait_ms"`
RestoreMs float64 `json:"restore_ms"`
Volume string `json:"volume"`
Round int `json:"round"`
// BusyRefusals counts the load writer's commands refused with a
// retryable status (and retried); MaxConsecutiveBusy is the longest run
// of such refusals of one command.
BusyRefusals int `json:"busy_refusals"`
MaxConsecutiveBusy int `json:"max_consecutive_busy"`
SnapshotMs float64 `json:"snapshot_request_to_commit_ms"`
CutTotalMs float64 `json:"cut_total_ms"`
BarrierPauseMs float64 `json:"cut_barrier_pause_ms"`
UploadedChunks int `json:"uploaded_chunks"`
UploadedBytes int64 `json:"uploaded_bytes"`
HostSlotWaits uint64 `json:"host_slot_waits"`
SlotRetries int `json:"snapshot_slot_refusals_retried"`
SlotWaitMs float64 `json:"snapshot_slot_wait_ms"`
RestoreMs float64 `json:"restore_ms"`
// RestoreExact is true or false for a snapshot that ran, "not_run" for
// one that was never admitted.
RestoreExact any `json:"restore_exact"`
@@ -215,10 +224,12 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
for i := 1; i <= cfg.Volumes; i++ {
add(fmt.Sprintf("v%d", i), fmt.Sprintf("v%d", i), i)
}
targets := map[string]bool{}
for r := 1; r <= cfg.Rounds; r++ {
for i := 1; i <= cfg.Volumes; i++ {
v := f1RestoreTarget(i, r)
add(v, v, i+cfg.Volumes*r)
targets[v] = true
}
}
var vols strings.Builder
@@ -229,7 +240,11 @@ func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
sort.Strings(keys)
for _, k := range keys {
b := env.hosts[k]
fmt.Fprintf(&vols, " - id: %s\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: %s\n", b.volume, b.replica)
size := " size_bytes: 268435456\n"
if targets[k] {
size = "" // a restore target: placement only, its restore creates it
}
fmt.Fprintf(&vols, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: s1\n replica_id: %s\n", b.volume, size, b.replica)
}
spec := filepath.Join(h.dir, "cluster-spec.yaml")
must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644))
@@ -266,15 +281,13 @@ func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume {
}
// f1Restore restores snapshot snap of src into target (a new volume on the
// same server) and drives the restore; the target's blockvolume is stopped
// once verified (f1RunRound), so restores do not pile up processes.
// same server), which fetches its chunks on access; the target's blockvolume
// is stopped once verified (f1RunRound), so restores do not pile up processes.
func f1Restore(t *testing.T, env *handoffEnv, src, snap, target string) *daemon {
t.Helper()
b := env.hosts[target]
env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := f1Up(t, env, target)
env.h.command(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", b.status)
return d
}
@@ -334,10 +347,12 @@ func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, ro
c.close()
}
type writer struct {
mu sync.Mutex
samples []f1Sample
written int
err error
mu sync.Mutex
samples []f1Sample
written int
err error
busy int // commands refused with a retryable status, retried
maxBusyRun int // the longest run of refusals of one command
}
stop := make(chan struct{})
ws := make([]*writer, len(vols))
@@ -368,14 +383,22 @@ func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, ro
}
lba := first + uint64(n)
s := time.Now()
// Per command: dialNVMe's deadline is 60 s from the dial,
// Per attempt: dialNVMe's deadline is 60 s from the dial,
// shorter than the write period.
_ = c.io.SetDeadline(s.Add(f1CommandDeadline))
err := c.tryWrite(lba, f1Block(vol, round, "load", lba))
refused, err := retryLikeHost(cfg.NVMeRetries, func() error {
_ = c.io.SetDeadline(time.Now().Add(f1CommandDeadline))
return c.tryWrite(lba, f1Block(vol, round, "load", lba))
})
flushRefused := 0
if err == nil && n%16 == 15 {
err = c.tryFlush()
flushRefused, err = retryLikeHost(cfg.NVMeRetries, func() error {
_ = c.io.SetDeadline(time.Now().Add(f1CommandDeadline))
return c.tryFlush()
})
}
w.mu.Lock()
w.busy += refused + flushRefused
w.maxBusyRun = max(w.maxBusyRun, refused, flushRefused)
w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)})
if err != nil {
w.err = err
@@ -433,6 +456,7 @@ func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, ro
for i, v := range vols {
r := f1Round{Volume: v.id, Round: round, RestoreExact: "not_run", SlotRetries: res[i].retries}
w := ws[i]
r.BusyRefusals, r.MaxConsecutiveBusy = w.busy, w.maxBusyRun
if w.err != nil {
rep.WriteErrors++
rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: write error: %v", v.id, round, w.err))
@@ -734,7 +758,7 @@ func (c *nvmeInitiator) tryStatus(op string) error {
return fmt.Errorf("nvme %s response body: %w", op, err)
}
if resp.Status != 0 {
return fmt.Errorf("nvme %s status 0x%04x", op, resp.Status)
return &nvmeStatusError{op: op, status: resp.Status}
}
return nil
}
@@ -205,10 +205,18 @@ func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) snapshot
return info
}
// snapshotEntry is one entry of `sw-block ops chunk snapshots`: a published
// snapshot, its root and the restore targets that depend on it.
type snapshotEntry struct {
Name string `json:"name"`
Root string `json:"root"`
Dependents []string `json:"dependents"`
}
// listSnapshots lists vol's snapshots (with a name prefix when given) under
// ctx, without failing the test.
func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([]snapshotInfo, error) {
args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([]snapshotEntry, error) {
args := []string{"ops", "chunk", "snapshots", "--master", env.h.masterAddr, "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if prefix != "" {
args = append(args, "--prefix", prefix)
}
@@ -216,30 +224,26 @@ func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([
if err != nil {
return nil, err
}
var body struct {
Snapshots []snapshotInfo `json:"snapshots"`
}
if code != 0 || json.Unmarshal([]byte(out), &body) != nil {
var list []snapshotEntry
if code != 0 || json.Unmarshal([]byte(out), &list) != nil {
return nil, fmt.Errorf("snapshots of %s: exit %d: %s %s", vol, code, out, errOut)
}
return body.Snapshots, nil
return list, nil
}
// snapshots lists vol's snapshots (with a name prefix when given).
func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotInfo {
func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotEntry {
t.Helper()
args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
args := []string{"ops", "chunk", "snapshots", "--master", env.h.masterAddr, "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if prefix != "" {
args = append(args, "--prefix", prefix)
}
out, _ := env.h.command(t, args...)
var body struct {
Snapshots []snapshotInfo `json:"snapshots"`
}
if err := json.Unmarshal([]byte(out), &body); err != nil {
var list []snapshotEntry
if err := json.Unmarshal([]byte(out), &list); err != nil {
t.Fatalf("snapshots of %s: %v\n%s", vol, err, out)
}
return body.Snapshots
return list
}
// restoreAttached creates target from snapshot snap of src and starts its
@@ -248,7 +252,7 @@ func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotInf
func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) {
t.Helper()
b := env.hosts["n-"+target]
env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target))
@@ -258,15 +262,15 @@ func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) {
}
// TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between
// them. The list is exactly the committed snapshots, in order, each active,
// with the point (cut LSN), HEAD generation and size (chunk count) its
// creation answered; a prefix shows one. A snapshot being taken appears in
// the list only committed, with the fields its creation answers, and stays;
// the test fails as inconclusive unless at least one listing ran while the
// snapshot was in flight and did not show it. A snapshot request that is refused
// (a restore volume not yet independent) leaves no name in the list.
// them. The list is exactly the published snapshots, in name order, each
// with its own root; a prefix shows one. A snapshot being taken appears in
// the list only once published, and then stays with the same root; the test
// fails as inconclusive unless at least one listing ran while the snapshot
// was in flight and did not show it. A snapshot of a restore target that is
// not fully local is taken, and a restore from it is refused: it names the
// source's chunks.
func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
env := startLadderEnv(t, "v2")
env := startLadderEnv(t, "v2", "v3")
var made []snapshotInfo
for i, w := range []struct {
lba uint64
@@ -277,23 +281,17 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
}
list := env.snapshots(t, "v1", "")
if len(list) != len(made) {
t.Fatalf("list has %d snapshots; want exactly the %d committed: %+v", len(list), len(made), list)
t.Fatalf("list has %d snapshots; want exactly the %d published: %+v", len(list), len(made), list)
}
wantChunks := []int{1, 2, 2}
roots := map[string]bool{}
for i, got := range list {
m := made[i]
if got.Name != m.Name || got.State != "active" || got.CutLSN != m.CutLSN || got.HeadGen != m.HeadGen || got.ChunkCount != m.ChunkCount {
t.Fatalf("list entry %d %+v; want %+v, active", i, got, m)
}
if got.ChunkCount != wantChunks[i] {
t.Fatalf("%s holds %d chunks; want %d", got.Name, got.ChunkCount, wantChunks[i])
}
if i > 0 && (got.CutLSN <= list[i-1].CutLSN || got.HeadGen <= list[i-1].HeadGen) {
t.Fatalf("list not in order of points: %+v after %+v", got, list[i-1])
if got.Name != made[i].Name || got.Root == "" || roots[got.Root] {
t.Fatalf("list entry %d %+v; want %s with a root of its own (list %+v)", i, got, made[i].Name, list)
}
roots[got.Root] = true
}
if one := env.snapshots(t, "v1", "s2"); len(one) != 1 || one[0].Name != "s2" || one[0].CutLSN != made[1].CutLSN {
t.Fatalf("show s2: %+v", one)
if one := env.snapshots(t, "v1", "s2"); len(one) != 1 || one[0].Name != "s2" || one[0].Root != list[1].Root {
t.Fatalf("show s2: %+v; want %+v", one, list[1])
}
// A snapshot being taken: listed only committed, and then it stays. The
@@ -324,7 +322,7 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
done <- result{out, errOut, code, err}
}()
env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!"))
var observed []snapshotInfo
var observed []snapshotEntry
var r result
inFlightUnlisted := 0 // listings begun before s4 answered that did not show it
// The observation bound: every list probe runs within what is left of it,
@@ -345,7 +343,7 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
if err != nil || time.Now().After(deadline) {
t.Fatalf("listing s4 within the observation bound: %v", err)
}
var s4 *snapshotInfo
var s4 *snapshotEntry
for _, e := range list {
e := e
s4 = &e
@@ -356,8 +354,8 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
switch {
case s4 == nil && len(observed) > 0:
t.Fatal("s4 was listed, then disappeared")
case s4 != nil && (s4.State != "active" || s4.CutLSN <= made[2].CutLSN || s4.HeadGen <= made[2].HeadGen):
t.Fatalf("s4 listed before it was committed: %+v", *s4)
case s4 != nil && (s4.Root == "" || roots[s4.Root]):
t.Fatalf("s4 listed without a root of its own: %+v", *s4)
case s4 != nil:
observed = append(observed, *s4)
}
@@ -368,7 +366,7 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
if inFlightUnlisted == 0 {
t.Fatalf("inconclusive: no listing ran while s4 was in flight and unlisted (%d listings saw it committed)", len(observed))
}
t.Logf("s4: %d listings while in flight did not show it; %d showed it committed", inFlightUnlisted, len(observed))
t.Logf("s4: %d listings while in flight did not show it; %d showed it published", inFlightUnlisted, len(observed))
var created snapshotInfo
if err := json.Unmarshal([]byte(r.out), &created); err != nil || created.Name != "s4" {
t.Fatalf("snapshot s4 answer: %v\n%s", err, r.out)
@@ -377,20 +375,26 @@ func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
if len(final) != 1 {
t.Fatalf("s4 not listed after its snapshot returned: %+v", final)
}
for _, o := range append(observed, final[0]) {
if o.State != "active" || o.CutLSN != created.CutLSN || o.HeadGen != created.HeadGen || o.ChunkCount != created.ChunkCount {
t.Fatalf("s4 listed as %+v; its creation answered %+v", o, created)
for _, o := range observed {
if o.Root != final[0].Root {
t.Fatalf("s4 listed as %+v while in flight, then as %+v: a listed snapshot changed", o, final[0])
}
}
// A refused snapshot is not a snapshot.
// A snapshot of a restore target that is not fully local is taken, and
// names the source's chunks, so a restore from it is refused.
env.restoreAttached(t, "v1", "s1", "v2")
out, errOut, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status, "--name", "x")
if code == 0 || !strings.Contains(out+errOut, "restore_incomplete") {
t.Fatalf("snapshot of a restore volume not yet independent: exit %d, want restore_incomplete\n%s\n%s", code, out, errOut)
if st := kzReadStats(t, env.hosts["n-v2"]); st.AbsentChunks == 0 {
t.Fatalf("setup: v2 holds every chunk already; want a restore target not fully local")
}
if l := env.snapshots(t, "v2", ""); len(l) != 0 {
t.Fatalf("a refused snapshot left %+v in the list", l)
env.snapshot(t, "n-v2", "v2", "x")
if l := env.snapshots(t, "v2", ""); len(l) != 1 || l[0].Name != "x" {
t.Fatalf("v2's snapshot x is not listed: %+v", l)
}
out, errOut, code := env.h.run(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v2", "--snapshot", "x", "--target", "v3",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
if code == 0 || !strings.Contains(out, `"code":"not_admitted"`) || !strings.Contains(out, "names another volume's chunks") {
t.Fatalf("restore from a restore target's snapshot: exit %d, want not_admitted naming another volume's chunks\n%s\n%s", code, out, errOut)
}
}
@@ -418,14 +422,13 @@ func (env *handoffEnv) lastCutUploads(t *testing.T, hostID, vol string) int {
func (env *handoffEnv) restoreInto(t *testing.T, src, snap, target string) {
t.Helper()
b := env.hosts["n-"+target]
env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target,
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", src, "--snapshot", snap, "--target", target,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target))
poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool {
return volumeFrontendReady(b.status, target)
})
env.h.command(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", b.status)
}
// requireEdges reads, through the host, a block in a chunk no test writes and
@@ -495,36 +498,35 @@ func volumeFrontendReady(statusAddr, vol string) bool {
return frontendReady(b)
}
// waitIndependent polls the restore status of target until the restore
// driver reports its phase independent (what the status says; it is not a
// separate measurement of which keys hold the chunks). 120 s bounds the
// observation: every query runs within what is left of it, and a success
// seen after it does not count. A query cancelled at the bound may take up
// to runCLI's 5 s WaitDelay more to clean up.
func (env *handoffEnv) waitIndependent(t *testing.T, target string) {
// hydrate makes every chunk of target local and checks that none is left
// absent. v1 has no background fill: a restore target fetches a chunk from
// its source's snapshot only when the guest touches it, so this reads one
// block of every chunk (which brings the whole chunk local), then waits for
// the chunk status to show no chunk absent. A restored volume keeps its
// references to the source's snapshot; hydration only makes it read locally.
func (env *handoffEnv) hydrate(t *testing.T, target string) {
t.Helper()
const bound = 120 * time.Second
b := env.hosts["n-"+target]
c := dialNVMe(t, b.nvme, plannedHandoffNQN)
// A read fetches its chunk only when the block read is not local: a
// block the guest wrote is served locally and fills nothing. So read
// each chunk's last block, which no ladder image writes (ladderImage
// writes offsets 0, 37, 74, ... in a chunk).
for lba := uint64(ladderChunkBlocks - 1); lba <= ladderLastBlock; lba += ladderChunkBlocks {
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
c.read(t, lba, 4096)
}
c.close()
const bound = 60 * time.Second
end := time.Now().Add(bound)
ctx, cancel := context.WithDeadline(context.Background(), end)
defer cancel()
last := ""
last := -1
for time.Now().Before(end) {
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status")
var st struct {
Phase string `json:"phase"`
if last = kzReadStats(t, b).AbsentChunks; last == 0 {
return
}
if err == nil && code == 0 && json.Unmarshal([]byte(out), &st) == nil {
if st.Phase == "failed" {
t.Fatalf("restore of %s failed: %s", target, out)
}
if st.Phase == "independent" && time.Now().Before(end) {
return
}
}
last = out + errOut
time.Sleep(200 * time.Millisecond)
}
t.Fatalf("%s never became independent within %v; last status: %s", target, bound, last)
t.Fatalf("%s: every chunk was read, yet %d are still absent after %v", target, last, bound)
}
// runCLI runs sw-block under ctx and returns its output and exit status. It
@@ -625,7 +627,7 @@ func TestSnapshotLadderC1FullRestore(t *testing.T) {
later := mergeImages(ladderImage("c1later", []uint64{1, 20}, 8), ladderImage("c1new", []uint64{9, 33}, 3))
env.writeImage(t, "s1", later)
env.restoreInto(t, "v1", "full", "v2")
env.waitIndependent(t, "v2")
env.hydrate(t, "v2")
env.requireImage(t, "n-v2", img, later)
}
@@ -645,19 +647,20 @@ func TestSnapshotLadderC2IncrementalRestore(t *testing.T) {
env.snapshot(t, "s1", "v1", "s3")
env.restoreInto(t, "v1", "s2", "v2")
env.waitIndependent(t, "v2")
env.hydrate(t, "v2")
env.requireImage(t, "n-v2", mergeImages(img1, img2), img3) // nothing written after s2, chunk 30 included
env.restoreInto(t, "v1", "s3", "v3")
env.waitIndependent(t, "v3")
env.hydrate(t, "v3")
env.requireImage(t, "n-v3", mergeImages(img1, img2, img3))
}
// TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume,
// once its status says independent, is written and snapshotted itself, then
// written again; that snapshot holds its first writes and not the later
// ones, and the source's snapshot, also written past, still restores
// unchanged. Every write to the restored volume comes after it is
// independent.
// once every chunk is local, is written and snapshotted itself, then
// written again. Its snapshot still names the source's chunks for the
// chunks it did not write (filling makes bytes local; it does not take the
// source's chunks over), so a restore from it is refused, naming another
// volume's chunks. The restored volume reads its own image, and the
// source's snapshot, also written past, still restores unchanged.
func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) {
env := startLadderEnv(t, "v2", "v3", "v4")
src := ladderImage("c3src", []uint64{0, 3}, 4)
@@ -667,17 +670,20 @@ func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) {
env.writeImage(t, "s1", srcLater)
env.restoreInto(t, "v1", "base", "v2")
env.waitIndependent(t, "v2")
env.hydrate(t, "v2")
own := ladderImage("c3own", []uint64{3, 11}, 3)
env.writeImage(t, "n-v2", own)
env.snapshot(t, "n-v2", "v2", "mine")
ownLater := ladderImage("c3ownlater", []uint64{0, 11, 25}, 2)
env.writeImage(t, "n-v2", ownLater)
env.restoreInto(t, "v2", "mine", "v3")
env.waitIndependent(t, "v3")
env.requireImage(t, "n-v3", mergeImages(src, own), ownLater, srcLater)
out, errOut, code := env.h.run(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v2", "--snapshot", "mine", "--target", "v3",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
if code == 0 || !strings.Contains(out, `"code":"not_admitted"`) || !strings.Contains(out, "names another volume's chunks") {
t.Fatalf("restore from the restored volume's snapshot: exit %d, want not_admitted naming another volume's chunks\n%s\n%s", code, out, errOut)
}
env.requireImage(t, "n-v2", mergeImages(src, own, ownLater), srcLater)
env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged
env.waitIndependent(t, "v4")
env.hydrate(t, "v4")
env.requireImage(t, "n-v4", src, srcLater, own, ownLater)
}
@@ -31,7 +31,7 @@ func TestSystemdFirstStartDuringAFilerOutageThenResetFailedServes(t *testing.T)
t.Fatal("systemd qualification needs root")
}
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
b := env.hosts["n-v2"]
@@ -1,61 +0,0 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"testing"
"time"
)
// TestProcedureRetireTemplateSource runs the template-holder procedure:
// fork the seed, publish the template on the holder, fork a consumer, then
// seal/revoke/ACK and delete the original source. No GC grace is advanced;
// the final ordinary pass proves its command and reads, not reclamation.
func TestProcedureRetireTemplateSource(t *testing.T) {
env := startHandoffEnvWith(t, 1, []string{"template-holder", "consumer"})
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
source := env.start(t, "blockvolume-source", "s1")
e := env.adopt(t, source, "s1")
const template = "template-holder"
want := map[uint64][]byte{5: pattern("template-seed!!!")}
env.writeBlock(t, "s1", 5, want[5])
env.snapshot(t, "s1", "v1", "seed")
for _, step := range []struct{ source, snapshot, target string }{
{"v1", "seed", template}, {template, "template-v1", "consumer"},
} {
env.h.command(t, "ops", "chunk", "fork", "--source", step.source, "--snapshot", step.snapshot,
"--target", step.target, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
"--request-id", "fork-"+step.target)
env.startTarget(t, step.target, "blockvolume-"+step.target)
env.requireBlocks(t, "n-"+step.target, 0, 16, want)
env.requireEdges(t, "n-"+step.target)
if step.target == template {
env.snapshot(t, "n-"+template, template, "template-v1")
}
}
g := env.seal(t, "s1", e)
env.revoke(t, e, g)
// The process must ACK and exit naturally; a signal would skip the ACK.
if err := source.wait(30 * time.Second); err != nil {
t.Fatalf("source did not exit naturally after revocation: %v", err)
}
env.waitAck(t, e, g)
env.deleteSnapshot(t, "v1", "seed")
out, stderr, code := env.volumeDelete(t, "delete-template-source")
requireDeleteCompleted(t, out, stderr, code, false)
env.requireDeletedForGood(t, "delete-template-source")
check := func() {
for _, vol := range []string{template, "consumer"} {
env.h.command(t, "ops", "chunk", "verify", "--volume", vol, "--all-snapshots", "--depth", "data", "--timeout", "2m",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
env.requireBlocks(t, "n-"+vol, 0, 16, want)
env.requireEdges(t, "n-"+vol)
}
env.requireSnapshotNames(t, template, "template-v1")
}
check()
env.h.command(t, "ops", "chunk", "gc", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
"--master", env.h.masterAddr, "--apply")
check()
t.Logf("template source retired; %s/template-v1 and consumer read unchanged after a default-grace GC pass", template)
}
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Small-file-system harness for TestHeadroomRefusesARestoreAndAForkTargetThenServesThem.
# Small-file-system harness for TestHeadroomRefusesRestoreTargetsThenServesThem.
# Root only, on a disposable host; it formats only a loop device over a private
# sparse file under WORKDIR.
#
@@ -16,7 +16,7 @@
# Example (from the repository root, as root):
# mkdir /tmp/headroom && cmd/blockvolume/testdata/headroom-small-fs.sh /tmp/headroom -- \
# env CHUNKSTORE_WEED=/path/to/weed go test -count=1 -tags 'subprocess chunkstore_integration' \
# -run '^TestHeadroomRefusesARestoreAndAForkTargetThenServesThem$' -timeout 15m ./cmd/blockvolume/
# -run '^TestHeadroomRefusesRestoreTargetsThenServesThem$' -timeout 15m ./cmd/blockvolume/
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "root required" >&2; exit 2; }
work=$(realpath "${1:?existing empty work dir}")
@@ -3,7 +3,9 @@
package main_test
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
@@ -22,58 +24,165 @@ func (env *handoffEnv) volumeDelete(t *testing.T, request string) (string, strin
"--master", env.h.masterAddr, "--request-id", request)
}
// requireDeleteCompleted checks step 4's answer: admitted, committed, HEAD
// marked, completed; and replayed when it is a rerun of a completed delete.
func requireDeleteCompleted(t *testing.T, out, errOut string, code int, rerun bool) {
// deletePastPrintedHorizon follows volume-lifecycle steps 2-4. The first
// refusal proves the lease is still live; the timestamp only schedules
// retries. The CLI verdict decides success. All retries keep the same id and
// the first T+5s deadline, even if another lease appears (which fails the test).
func (env *handoffEnv) deletePastPrintedHorizon(t *testing.T, volume, request string, requireLive bool) (string, string, int) {
t.Helper()
var res struct {
Admitted, Committed, HeadMarked, Completed, Replayed bool
call := func(ctx context.Context) (string, string, int) {
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "volume-delete", "--volume", volume,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
"--master", env.h.masterAddr, "--request-id", request)
if err != nil {
t.Fatalf("volume-delete %s: %v", volume, err)
}
return out, errOut, code
}
if code != 0 || json.Unmarshal([]byte(out), &res) != nil || !res.Admitted || !res.Committed || !res.HeadMarked || !res.Completed || res.Replayed != rerun {
t.Fatalf("volume-delete: exit %d %s %s; want admitted, committed, headMarked, completed, replayed %v", code, out, errOut, rerun)
first, stop := context.WithTimeout(context.Background(), 15*time.Second)
defer stop()
out, errOut, code := call(first)
until, err := deleteLeaseHorizon(out, code)
if err != nil {
if requireLive {
t.Fatalf("first delete must refuse the live lease: %v; %s %s", err, out, errOut)
}
return out, errOut, code
}
if wait := time.Until(until); wait < 0 || wait > 90*time.Second {
t.Fatalf("first refusal horizon must be upcoming and within 90s, got %s: %s", until, out)
}
ctx, cancel := context.WithDeadline(context.Background(), until.Add(5*time.Second))
defer cancel()
timer := time.NewTimer(time.Until(until))
defer timer.Stop()
for {
select {
case <-ctx.Done():
t.Fatalf("delete did not resolve by original horizon + 5s: %s %s", out, errOut)
case <-timer.C:
}
out, errOut, code = call(ctx)
next, err := deleteLeaseHorizon(out, code)
if err != nil {
return out, errOut, code
}
if !next.Equal(until) {
t.Fatalf("lease horizon changed from %s to %s; refusing to widen deadline", until, next)
}
timer.Reset(100 * time.Millisecond)
}
}
// headShown returns HEAD's state and chunk count from `ops chunk show`.
// deleteLeaseHorizon accepts only the documented typed CLI refusal, never
// a matching stderr fragment or a successful exit with an error-shaped body.
func deleteLeaseHorizon(out string, code int) (time.Time, error) {
var body struct {
Code string `json:"code"`
Message string `json:"message"`
}
if code != 1 {
return time.Time{}, fmt.Errorf("exit %d is not refusal", code)
}
if err := json.Unmarshal([]byte(out), &body); err != nil {
return time.Time{}, err
}
if body.Code != "not_admitted" {
return time.Time{}, fmt.Errorf("code %q is not not_admitted", body.Code)
}
_, rest, ok := strings.Cut(body.Message, "live until ")
if !ok {
return time.Time{}, fmt.Errorf("missing lease horizon")
}
fields := strings.Fields(rest)
if len(fields) == 0 {
return time.Time{}, fmt.Errorf("empty lease horizon")
}
return time.Parse(time.RFC3339Nano, strings.TrimSuffix(fields[0], ":"))
}
// The CLI error body, rather than a substring in combined output, is the
// authority for retry timing. Every refusal class stays distinguishable.
func TestDeleteLeaseHorizonRequiresTypedRefusal(t *testing.T) {
const valid = `{"code":"not_admitted","message":"workspace delete: live until 2026-11-26T13:00:00.125Z: lease expiry plus clock-skew margin has not elapsed"}`
for _, tc := range []struct {
name, out string
code int
ok bool
}{
{"typed horizon", valid, 1, true},
{"successful exit cannot refuse", valid, 0, false},
{"usage failure", valid, 2, false},
{"plain stderr is not evidence", "not_admitted: live until 2026-11-26T13:00:00.125Z", 1, false},
{"dependent refusal", `{"code":"snapshot_has_dependents","message":"snapshot s1"}`, 1, false},
{"uncertain lease", `{"code":"not_admitted","message":"restart required"}`, 1, false},
{"missing time", `{"code":"not_admitted","message":"live until "}`, 1, false},
{"invalid time", `{"code":"not_admitted","message":"live until tomorrow: refused"}`, 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
until, err := deleteLeaseHorizon(tc.out, tc.code)
if (err == nil) != tc.ok {
t.Fatalf("horizon %s error %v, want valid=%v", until, err, tc.ok)
}
if tc.ok && until.Format(time.RFC3339Nano) != "2026-11-26T13:00:00.125Z" {
t.Fatalf("wrong horizon %s", until)
}
})
}
}
// requireDeleteCompleted checks step 4's documented state:"deleted" result
// (volume-lifecycle.md, "Delete a volume", step 4). Retries use the same
// request id and must complete again; the CLI reports no replayed flag.
func requireDeleteCompleted(t *testing.T, out, errOut string, code int) {
t.Helper()
if code != 0 || !handoffDeleteCompleted(out) {
t.Fatalf("volume-delete: exit %d %s %s; want a volume directory and state deleted", code, out, errOut)
}
}
// headShown reads head.State and independently counts stored pool objects.
// volume-lifecycle.md step 4 specifies that show has no chunkCount field;
// its object-listing alternative preserves the checks that nothing was
// removed on refusal and no chunks remain after completion.
func (env *handoffEnv) headShown(t *testing.T) (string, int) {
t.Helper()
out, _ := env.h.command(t, env.chunkShow()...)
var body struct {
Head *struct {
State string `json:"state"`
ChunkCount int `json:"chunkCount"`
} `json:"head"`
var head struct {
State string `json:"state"`
}
if err := json.Unmarshal([]byte(out), &body); err != nil || body.Head == nil {
out := env.headOf(t, "v1")
if err := json.Unmarshal([]byte(out), &head); err != nil {
t.Fatalf("chunk show: %v %s", err, out)
}
return body.Head.State, body.Head.ChunkCount
return head.State, env.poolObjects(t, "v1")
}
// requireDeletedForGood checks the page's end state ("state": "deleted",
// "chunkCount": 0) and that a rerun with the same request id completes
// again.
// requireDeletedForGood checks the page's deleted HEAD and empty pool,
// then repeats the delete with the same request id and checks both again.
func (env *handoffEnv) requireDeletedForGood(t *testing.T, request string) {
t.Helper()
if state, n := env.headShown(t); state != "deleted" || n != 0 {
t.Fatalf("chunk show after the delete: state %q, chunkCount %d; want deleted, 0", state, n)
t.Fatalf("after the delete: HEAD state %q, pool objects %d; want deleted, 0", state, n)
}
out, errOut, code := env.volumeDelete(t, request)
requireDeleteCompleted(t, out, errOut, code, true)
requireDeleteCompleted(t, out, errOut, code)
if state, n := env.headShown(t); state != "deleted" || n != 0 {
t.Fatalf("after the repeated delete: HEAD state %q, pool objects %d; want deleted, 0", state, n)
}
}
// TestProcedureDeleteAVolume: the page's steps. A volume with a snapshot is
// sealed, revoked (blockvolume sends the ACK and exits 0 by itself) and its
// ACK seen; volume-delete is refused while the snapshot exists, with nothing
// deleted; the snapshot is deleted; volume-delete then answers admitted,
// committed, headMarked, completed, `chunk show` shows HEAD deleted with no
// chunks, and a rerun with the same request id completes again.
// TestProcedureDeleteAVolume: ACK does not bypass the lease horizon; a
// restored-volume dependent blocks deletion, while ordinary snapshots do not.
// Refusals preserve HEAD/pool; completion empties the pool and replays by id.
func TestProcedureDeleteAVolume(t *testing.T) {
env := startHandoffEnv(t, 1)
env := startHandoffEnvWith(t, 1, []string{"v2"})
holder := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, holder, "s1")
env.writeBlock(t, "s1", 0, pattern("delete-a-volume!"))
env.snapshot(t, "s1", "v1", "s1")
env.snapshot(t, "s1", "v1", "plain")
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1",
"--snapshot", "s1", "--target", "v2", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
g := env.seal(t, "s1", e)
env.revoke(t, e, g)
@@ -83,53 +192,94 @@ func TestProcedureDeleteAVolume(t *testing.T) {
env.waitAck(t, e, g)
state0, n0 := env.headShown(t)
out, errOut, code := env.volumeDelete(t, "del-v1")
if code == 0 || !strings.Contains(out+errOut, "has snapshots (s1)") {
t.Fatalf("volume-delete with a snapshot: exit %d %s %s; want refused, naming s1", code, out, errOut)
out, errOut, code := env.deletePastPrintedHorizon(t, "v1", "del-v1", true)
var refusal struct {
Code string `json:"code"`
Message string `json:"message"`
}
if err := json.Unmarshal([]byte(out), &refusal); err != nil || code != 1 || refusal.Code != "snapshot_has_dependents" || !strings.Contains(refusal.Message, `snapshot "s1"`) {
t.Fatalf("volume-delete with a dependent: exit %d %s %s; want typed snapshot_has_dependents naming s1", code, out, errOut)
}
if state, n := env.headShown(t); state != "detached" || state != state0 || n != n0 || n == 0 {
t.Fatalf("after the refused delete HEAD is %q with %d chunks; want it as before (%q, %d chunks): nothing deleted", state, n, state0, n0)
}
env.deleteSnapshot(t, "v1", "s1")
// v2 never started; delete it through the public API (and its own horizon,
// if the master granted a line). This releases s1's dependent.
out, errOut, code = env.deletePastPrintedHorizon(t, "v2", "del-v2", false)
requireDeleteCompleted(t, out, errOut, code)
if state, n := env.headOf(t, "v2"), env.poolObjects(t, "v2"); !strings.Contains(state, `"state":"deleted"`) || n != 0 {
t.Fatalf("restored target not deleted: HEAD %s pool %d", state, n)
}
// Both snapshots still exist, now without dependents: plain snapshots
// must be removed by the volume delete itself, not by this fixture.
snapshots, _ := env.h.command(t, "ops", "chunk", "snapshots", "--master", env.h.masterAddr,
"--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
var names []struct {
Name string `json:"name"`
Dependents []string `json:"dependents"`
}
if err := json.Unmarshal([]byte(snapshots), &names); err != nil {
t.Fatal(err)
}
seen := map[string]bool{}
for _, snap := range names {
if len(snap.Dependents) != 0 {
t.Fatalf("dependent not released: %s", snapshots)
}
seen[snap.Name] = true
}
if !seen["s1"] || !seen["plain"] {
t.Fatalf("plain snapshots disappeared before volume-delete: %s", snapshots)
}
out, errOut, code = env.volumeDelete(t, "del-v1")
requireDeleteCompleted(t, out, errOut, code, false)
requireDeleteCompleted(t, out, errOut, code)
env.requireDeletedForGood(t, "del-v1")
}
// TestProcedureDeleteAfterASignalStop: the page's recovery. The volume is
// sealed and blockvolume is then stopped with SIGTERM, so the ACK is
// skipped: volume-delete is refused (live authority requires a clean
// revocation ACK) and nothing is deleted. blockvolume is started again with
// the same flags and local root; it is revoked and sends the ACK (exit 0 by
// itself); volume-delete then completes, HEAD is deleted with no chunks, and
// a rerun with the same request id completes again.
// TestProcedureDeleteAfterASignalStop: a sealed holder stopped by SIGTERM
// stays down. The first delete refuses the live lease and changes nothing;
// the same request completes after its printed horizon without a restart or
// ACK. A retry completes again, and a late start cannot claim or serve.
func TestProcedureDeleteAfterASignalStop(t *testing.T) {
env := startHandoffEnv(t, 1)
holder := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, holder, "s1")
env.writeBlock(t, "s1", 0, pattern("delete-after-sig"))
g := env.seal(t, "s1", e)
env.seal(t, "s1", e)
holder.term(t, 30*time.Second)
stopped := func() {
t.Helper()
select {
case <-holder.done:
default:
t.Fatal("signal-stopped holder is still running")
}
if listening(env.hosts["s1"].status) {
t.Fatal("signal-stopped holder listened again before deletion")
}
}
stopped()
state0, n0 := env.headShown(t)
out, errOut, code := env.volumeDelete(t, "del-v1")
if code == 0 || !strings.Contains(out+errOut, "live authority requires clean revocation ACK") {
t.Fatalf("volume-delete after a signal stop: exit %d %s %s; want refused for the missing ACK", code, out, errOut)
if _, err := deleteLeaseHorizon(out, code); err != nil {
t.Fatalf("volume-delete after signal stop: exit %d %s %s; want typed live-until refusal: %v", code, out, errOut, err)
}
if state, n := env.headShown(t); state != "detached" || state != state0 || n != n0 || n == 0 {
t.Fatalf("after the refused delete HEAD is %q with %d chunks; want it as before (%q, %d chunks): nothing deleted", state, n, state0, n0)
t.Fatalf("refused delete changed HEAD/pool: %q %d; before %q %d", state, n, state0, n0)
}
again := env.start(t, "blockvolume-s1-again", "s1")
poll(t, 60*time.Second, "the restarted holder never listened on its status address", func() bool {
return listening(env.hosts["s1"].status)
})
env.revoke(t, e, g)
if err := again.wait(60 * time.Second); err != nil {
t.Fatalf("the restarted s1 after the revocation: %v; want a clean exit by itself", err)
}
env.waitAck(t, e, g)
out, errOut, code = env.volumeDelete(t, "del-v1")
requireDeleteCompleted(t, out, errOut, code, false)
stopped()
out, errOut, code = env.deletePastPrintedHorizon(t, "v1", "del-v1", true)
requireDeleteCompleted(t, out, errOut, code)
stopped()
env.requireDeletedForGood(t, "del-v1")
late := env.start(t, "blockvolume-s1-late", "s1")
err := late.wait(60 * time.Second)
served := late.has("blockvolume: backend admits I/O: starting the frontends") || volumeFrontendReady(env.hosts["s1"].status, "v1")
keepFullLog(t, late)
if err == nil || strings.Contains(fmt.Sprint(err), "still running") || served {
t.Fatalf("late start after deletion must exit without serving: exit=%v served=%v", err, served)
}
if state, n := env.headShown(t); state != "deleted" || n != 0 {
t.Fatalf("late start changed deleted HEAD/pool: %q %d", state, n)
}
}
@@ -0,0 +1,22 @@
//go:build subprocess && chunkstore_integration
package main_test
import "testing"
// TestWeedPortPairsAvoidTheEphemeralRange: no port of a weed port pair lies in
// the host's range for outgoing connections' source ports, where any
// connection could take it between w4FreePortPair's free check and weed's bind
// (a filer's gRPC port inside a host's 43255-47350 failed to bind that way).
func TestWeedPortPairsAvoidTheEphemeralRange(t *testing.T) {
lo, hi := ephemeralPorts()
used := map[int]bool{}
for i := 0; i < 100; i++ {
p := w4FreePortPair(t, used)
for _, q := range []int{p, p + 10000} {
if q >= lo && q <= hi {
t.Fatalf("pair %d/%d: port %d is in the ephemeral range %d-%d", p, p+10000, q, lo, hi)
}
}
}
}
@@ -37,13 +37,32 @@ func testListenHost() string {
return "127.0.0.1"
}
// ephemeralPorts is the host's range for outgoing connections' source ports
// (Linux ip_local_port_range; the Linux default when unreadable). A port in it
// can be taken by any outgoing connection between the free check and weed's
// bind, so a port pair never uses it.
func ephemeralPorts() (int, int) {
lo, hi := 32768, 60999
if b, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil {
var a, z int
if n, _ := fmt.Sscan(string(b), &a, &z); n == 2 && a > 0 && z >= a {
lo, hi = a, z
}
}
return lo, hi
}
func w4FreePortPair(t *testing.T, used map[int]bool) int {
t.Helper()
lo, hi := ephemeralPorts()
for i := 0; i < 200; i++ {
p := 20000 + rand.Intn(20000)
if used[p] || used[p+10000] {
continue
}
if (p >= lo && p <= hi) || (p+10000 >= lo && p+10000 <= hi) {
continue
}
ok := true
for _, q := range []int{p, p + 10000} {
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q))
@@ -91,6 +110,10 @@ func startWorkspaceWeedAt(t *testing.T, dir string) *w4WeedCluster {
// VolumeSizeLimitMB each (the default holds about 8 GiB of chunks).
type w4WeedOpts struct {
VolumeSizeLimitMB, VolumeMax int
// A fault-injection front keeps the advertised filer endpoint unchanged.
// The one real filer binds a private loopback address; no second filer is registered.
FilerBind string
FilerFront func(*w4WeedCluster)
}
func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedCluster {
@@ -137,8 +160,17 @@ func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedClust
run("master", "master", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000")
w4WaitTCP(t, c.master, 20*time.Second)
run("volume", "volume", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax))
run("filer", "filer", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"))
filerArgs := []string{"filer", "-ip=" + testListenHost(), fmt.Sprintf("-port=%d", fp), "-master=" + c.master, "-defaultStoreDir=" + filepath.Join(dir, "f")}
if o.FilerBind != "" {
filerArgs = append(filerArgs, "-ip.bind="+o.FilerBind)
c.filerHTTP = net.JoinHostPort(o.FilerBind, fmt.Sprint(fp))
c.filerGRPC = net.JoinHostPort(o.FilerBind, fmt.Sprint(fp+10000))
}
run("filer", filerArgs...)
w4WaitTCP(t, c.filerGRPC, 30*time.Second)
if o.FilerFront != nil {
o.FilerFront(c)
}
// Wait until an assign succeeds (volume registered, volumes growable).
cl := c.client(t, "/swblock/vols/probe")
@@ -30,7 +30,7 @@ import (
// forbids removing those files.
func TestWrongGeometryCureAsWritten(t *testing.T) {
env := startSourceWithSnapshot(t, "v2")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2",
env.h.command(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v1", "--snapshot", "s1", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
plantStore(t, filepath.Join("testdata", "onezero-wrong-geometry-store.txt"), env.hosts["n-v2"].root)
// The planted files are byte for byte the captured ones.
@@ -95,8 +95,13 @@ func startSourceWithSnapshot(t *testing.T, targets ...string) *handoffEnv {
// headOf is the first line of `sw-block ops chunk show --volume v`.
func (env *handoffEnv) headOf(t *testing.T, v string) string {
out, _, _ := env.h.run(t, "ops", "chunk", "show", "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
return firstLine(out)
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", v, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
head, err := handoffHeadJSON(out)
if err != nil {
t.Fatalf("show HEAD for %s: %v\n%s", v, err, out)
}
return head
}
func listTree(root string) string {
@@ -0,0 +1,278 @@
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// The process-level integration tests (cmd/blockvolume, behind build tags)
// call this command by argument list: they compile without these tags in
// CI, so an invocation the CLI no longer accepts (a removed subcommand, a
// renamed or newly required flag) would pass compile and fail only on a
// lab run. Every literal `ops ...` invocation in them is run through this
// CLI's own argument handling here, each in a child process killed at its
// deadline. Variable values become placeholders; in the child the master
// resolves every name and the filer dial and the restore RPC answer
// errGuardPast, which a command reaches only after all its argument checks.
// Other calls meet addresses nothing listens on. A refusal of the arguments
// fails this test, and so does a call that neither answers nor fails
// within the deadline: waiting is not proof that the arguments passed.
func TestIntegrationTestInvocationsParse(t *testing.T) {
invocations := literalOpsInvocations(t, filepath.Join("..", "blockvolume"))
if len(invocations) == 0 {
t.Fatal("no ops invocations found in the integration tests")
}
for _, inv := range invocations {
inv := inv
if len(inv.args) < 2 {
t.Fatalf("%s: an ops invocation without a subcommand", inv.where)
}
t.Run(inv.where, func(t *testing.T) {
if verdict, out := guardInvocation(t, inv.args); verdict != guardPast {
t.Fatalf("sw-block %s\n%s: %s", strings.Join(inv.args, " "), verdict, out)
}
})
}
}
// The guard's own controls: argument lists whose missing flag is checked
// only after the volume names resolve must be refused, and a complete one
// must pass.
func TestIntegrationInvocationGuardReachesLateFlagChecks(t *testing.T) {
for _, c := range []struct {
args []string
want string
}{
{[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1"}, guardRefused},
{[]string{"ops", "chunk", "snapshot-delete", "--master", "127.0.0.1:1", "--volume", "v1", "--name", "s1"}, guardRefused},
{[]string{"ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardRefused},
{[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1", "--chunk-filer", "127.0.0.1:1"}, guardPast},
{[]string{"ops", "chunk", "restore", "--master", "127.0.0.1:1", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardPast},
} {
if verdict, out := guardInvocation(t, c.args); verdict != c.want {
t.Errorf("sw-block %s: %s, want %s: %s", strings.Join(c.args, " "), verdict, c.want, out)
}
}
}
const (
guardPast = "past its arguments"
guardRefused = "refused its arguments"
guardTimeout = "still running at the deadline"
guardOther = "failed for another reason"
)
// errGuardPast is what the child's filer dial and restore RPC answer.
var errGuardPast = errors.New("invocation guard: past its arguments")
const guardArgsEnv = "SWB_INVOCATION_GUARD_ARGS"
// guardInvocation runs args in a child process of this test binary and
// classifies its output.
func guardInvocation(t *testing.T, args []string) (string, string) {
t.Helper()
enc, err := json.Marshal(args)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestIntegrationInvocationChild$", "-test.count=1")
cmd.Dir = t.TempDir() // whatever a call writes lands here, never in the source tree
cmd.Env = append(os.Environ(), guardArgsEnv+"="+string(enc))
cmd.WaitDelay = time.Second
raw, _ := cmd.CombinedOutput()
out := string(raw)
switch {
case ctx.Err() != nil:
return guardTimeout, out
case strings.Contains(out, errGuardPast.Error()):
return guardPast, firstLine(out, errGuardPast.Error())
}
for _, refusal := range []string{`"code":"bad_request"`, "unknown subcommand", "unknown command", "flag provided but not defined", "invalid value", "is required"} {
if strings.Contains(out, refusal) {
return guardRefused, firstLine(out, refusal)
}
}
if strings.Contains(out, "rpc error") || strings.Contains(out, "dial tcp") || strings.Contains(out, "connection refused") {
return guardPast, "the placeholder address refused the call"
}
return guardOther, out
}
// TestIntegrationInvocationChild is the child process: it runs only with
// guardArgsEnv set.
func TestIntegrationInvocationChild(t *testing.T) {
enc := os.Getenv(guardArgsEnv)
if enc == "" {
t.Skip("the invocation guard's child process")
}
var args []string
if err := json.Unmarshal([]byte(enc), &args); err != nil {
t.Fatal(err)
}
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil }
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return nil, nil, errGuardPast }
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
return nil, errGuardPast
}
var stdout, stderr bytes.Buffer
code := run(args, &stdout, &stderr)
fmt.Printf("exit %d\n%s%s", code, stdout.String(), stderr.String())
}
type opsInvocation struct {
where string
args []string
}
// literalOpsInvocations returns every `<x>.command(t, "ops", ...)`, `<x>.run(t, "ops", ...)` and
// `runCLI(ctx, h, "ops", ...)` call in
// dir's test files whose arguments are listed (not spread from a slice),
// with each non-literal argument replaced by a placeholder for its flag.
func literalOpsInvocations(t *testing.T, dir string) []opsInvocation {
t.Helper()
files, err := filepath.Glob(filepath.Join(dir, "*_test.go"))
if err != nil {
t.Fatal(err)
}
var out []opsInvocation
fset := token.NewFileSet()
for _, f := range files {
src, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
file, err := parser.ParseFile(fset, f, src, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(file, func(n ast.Node) bool {
var elems []ast.Expr
switch x := n.(type) {
case *ast.CallExpr:
if x.Ellipsis != token.NoPos || len(x.Args) < 2 {
return true
}
from := opsArg(x)
if from < 0 {
return true
}
elems = x.Args[from:]
case *ast.CompositeLit:
// a prepared argument list, []string{"ops", ...}, that a
// harness call spreads
if len(x.Elts) < 2 || literal(x.Elts[0]) != "ops" {
return true
}
elems = x.Elts
default:
return true
}
var args []string
for _, a := range elems {
if v := literal(a); v != "" || isStringLit(a) {
args = append(args, v)
continue
}
args = append(args, placeholder(args, len(args)))
}
pos := fset.Position(n.Pos())
out = append(out, opsInvocation{where: filepath.Base(pos.Filename) + ":" + strconv.Itoa(pos.Line), args: args})
return true
})
}
return out
}
// opsArg is the index of the literal "ops" that starts the CLI argument
// list of a harness call: x.command(t, "ops", ...) or runCLI(ctx, h, "ops",
// ...); -1 for any other call.
func opsArg(call *ast.CallExpr) int {
name := ""
switch f := call.Fun.(type) {
case *ast.SelectorExpr:
name = f.Sel.Name
case *ast.Ident:
name = f.Name
}
at := map[string]int{"command": 1, "run": 1, "runCLI": 2}[name]
if at == 0 || len(call.Args) <= at || literal(call.Args[at]) != "ops" {
return -1
}
return at
}
func isStringLit(e ast.Expr) bool {
b, ok := e.(*ast.BasicLit)
return ok && b.Kind == token.STRING
}
func literal(e ast.Expr) string {
b, ok := e.(*ast.BasicLit)
if !ok || b.Kind != token.STRING {
return ""
}
v, err := strconv.Unquote(b.Value)
if err != nil {
return ""
}
return v
}
// placeholder is a value of the kind the preceding flag takes: an address
// nothing listens on, a number, a duration, or a name.
func placeholder(prev []string, at int) string {
name := "x" + strconv.Itoa(at) // distinct, so two variables never compare equal
if len(prev) == 0 {
return name
}
flag := strings.TrimLeft(prev[len(prev)-1], "-")
switch {
case strings.Contains(flag, "timeout") || strings.Contains(flag, "interval") || strings.Contains(flag, "wait"):
return "1s"
case strings.Contains(flag, "lsn") || strings.Contains(flag, "epoch") || strings.Contains(flag, "gen") || strings.Contains(flag, "count") || strings.Contains(flag, "bytes") || strings.Contains(flag, "size"):
return "1"
case strings.Contains(flag, "confirm"):
return volumeOf(prev) + "@1" // a forced move's confirmation names its volume and epoch
case strings.Contains(flag, "master") || strings.Contains(flag, "addr") || strings.Contains(flag, "filer") || strings.Contains(flag, "data") || strings.Contains(flag, "ctrl") || strings.Contains(flag, "endpoint"):
return "127.0.0.1:1"
}
return name
}
// volumeOf is the --volume value among args, or "".
func volumeOf(args []string) string {
for i := 0; i+1 < len(args); i++ {
if args[i] == "--volume" {
return args[i+1]
}
}
return ""
}
func firstLine(out, near string) string {
for _, l := range strings.Split(out, "\n") {
if strings.Contains(l, near) {
return l
}
}
return out
}