Compare commits

..
23 changed files with 173 additions and 2403 deletions

No files matched your search

+1 -2
View File
@@ -135,9 +135,8 @@ jobs:
docker cp "$container:/usr/local/bin/$binary" "$out/bin/$binary"
done
bash seaweed-block/scripts/refuse-lab-binary.sh "$out/bin/"*
cp seaweed-block/deploy/systemd/sw-block.tmpfiles.conf "$out/bin/sw-block.tmpfiles.conf"
asset="sw-block-${version}-linux-amd64.tar.gz"
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
tar -C "$out/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$version" == *-* ]]; then prerelease=true; fi
-4
View File
@@ -98,10 +98,6 @@ jobs:
python3 -B ../.github/block/scripts/doc-links-check-test.py
python3 -I ../.github/block/scripts/doc-links-check.py .
- name: Release binary archive contract
if: matrix.suite == 'unit'
run: python3 -I .github/scripts/release-binary-assets-test.py
- name: Runner disk is NVMe
# A self-hosted runner whose work, temp or Go cache directory sits on a
# SATA system disk times the process-level tests out under disk load;
-8
View File
@@ -97,11 +97,3 @@ TestWeedClustersSideBySideKeepTheirOwnFilerCensus
# Kubernetes state: a holder on a wiped state directory never comes up empty.
TestRF1HolderOnAWipedStateDirectoryRefusesStoreLost
TestRF3WipedPrimaryRefusesAndASurvivorServesItsData
# Non-root mini startup and owned cleanup controls.
TestMiniStartsWithoutRootAndNamesItsBinaries
TestMiniOwnedGroupCleanupStopsDescendants
TestMiniSettledCleanupDoesNotSignal
TestMiniCleanupFailStopAndSettlement
TestMiniContextAllowsChildShutdownGrace
TestMiniLockProofRequiresContention
@@ -7,41 +7,6 @@ REV = "a" * 40
DIGEST = "example.invalid/block@sha256:" + "b" * 64
class ReleaseAssets(unittest.TestCase):
def test_active_root_release_contains_tmpfiles(self):
repo = HERE.parents[2]
workflow = (repo / '.github/workflows/block-release.yml').read_text()
step = workflow.split(' - name: Publish matching binary tarball\n', 1)[1]
script = step.split(' run: |\n', 1)[1].split('\n - name:', 1)[0]
script = '\n'.join(line[10:] for line in script.splitlines())
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
tools = root / 'tools'; tools.mkdir()
image = root / 'image'; image.mkdir()
for name in ('blockmaster', 'blockvolume', 'sw-block'):
(image / name).write_bytes(('#!/bin/sh\necho '+name+' release\n').encode())
(image / name).chmod(0o755)
(tools / 'docker').write_text('''#!/usr/bin/env python3
import os,pathlib,shutil,sys
a=sys.argv[1:]
if a[0]=='create': print('owned-container')
elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',1)[1],a[2])
''')
(tools / 'gh').write_text('#!/bin/sh\nexit 0\n')
for tool in tools.iterdir(): tool.chmod(0o755)
env = dict(os.environ, PATH=str(tools)+os.pathsep+os.environ['PATH'],
IMAGE=str(image), RUNNER_TEMP=str(root), BLOCK_IMAGE='example/block',
BLOCK_DIGEST='sha256:'+'b'*64, GITHUB_REF_NAME='seaweed-block/v1.1.2',
GITHUB_REPOSITORY='example/block', NOTES=str(root/'notes'))
result = subprocess.run(['bash', '-c', script], cwd=repo, env=env,
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stderr)
with tarfile.open(root/'block-release/sw-block-v1.1.2-linux-amd64.tar.gz') as tar:
self.assertEqual(set(tar.getnames()), {'blockmaster', 'blockvolume', 'sw-block', 'sw-block.tmpfiles.conf'})
self.assertEqual(tar.extractfile('sw-block.tmpfiles.conf').read(),
(repo/'seaweed-block/deploy/systemd/sw-block.tmpfiles.conf').read_bytes())
subprocess.run(['sha256sum', '--check', 'SHA256SUMS'], cwd=root/'block-release',
check=True, capture_output=True)
def run_case(self, bad=None, mode="revision", existing=True, tag="v1.1.1",
docker_rm_rc=0, rm_rc=0, publish_rc=0):
with tempfile.TemporaryDirectory() as tmp:
@@ -58,7 +23,6 @@ elif a[0]=='cp': shutil.copy2(pathlib.Path(os.environ['IMAGE'])/a[1].rsplit('/',
else: self.fail("invalid fixture mode")
data=(f"#!/bin/sh\necho '{name} revision={revision} modified={modified}{suffix}'\nexit {status}\n").encode()
(image/name).write_bytes(data); (image/name).chmod(0o755); expected[name]=data
expected["sw-block.tmpfiles.conf"]=(HERE.parent.parent/"deploy"/"systemd"/"sw-block.tmpfiles.conf").read_bytes()
log=root/"calls.jsonl"; state=root/"release.json"; state.write_text(json.dumps({"prerelease":"-" not in tag}))
common="""#!/usr/bin/env python3
import json,os,pathlib,shutil,sys
+1 -3
View File
@@ -33,11 +33,9 @@ for binary in blockmaster blockvolume sw-block; do
exit 1
fi
done
# The tmpfiles.d entry that creates the host volume lock directory for the units.
cp -- "$(dirname -- "$0")/../../deploy/systemd/sw-block.tmpfiles.conf" "$work/bin/sw-block.tmpfiles.conf"
mkdir -p "$out"
asset="sw-block-${tag}-linux-amd64.tar.gz"
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block sw-block.tmpfiles.conf
tar -C "$work/bin" -czf "$out/$asset" blockmaster blockvolume sw-block
(cd "$out" && sha256sum "$asset" >SHA256SUMS)
prerelease=false
if [[ "$tag" == *-* ]]; then prerelease=true; fi
+8 -10
View File
@@ -116,25 +116,23 @@ TAG=v1.1.1
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/sw-block-$TAG-linux-amd64.tar.gz
curl -fsSLO https://github.com/seaweedfs/seaweed-block/releases/download/$TAG/SHA256SUMS
sha256sum -c --ignore-missing SHA256SUMS && tar -xzf sw-block-$TAG-linux-amd64.tar.gz
# v1.1.1 prerequisite: its child lookup uses PATH and its lock is host-wide.
export PATH="$PWD:$PATH"
sudo install -d -m 0755 /run/sw-block
sudo install -d -m 0700 -o "$(id -u)" -g "$(id -g)" /run/sw-block/locks
export PATH="$PWD:$PATH" # so the sw-block commands that mini prints run as shown
./blockvolume --version # must print the tag's commit
# blockvolume keeps one lock per volume here, so only one live process serves a volume on a host:
sudo install -d -m 0755 -o root -g root /run/sw-block
sudo install -d -m 0755 -o "$USER" -g "$(id -gn)" /run/sw-block/locks
./sw-block mini --dir ./swb-mini --weed /path/to/weed
```
From v1.1.2 `mini` needs no `sudo` to start: it keeps the volume lock under `--dir`, prints every command with the
absolute paths of `sw-block` and `weed`, and on a failed start prints the `--reuse` command that starts again on the
same `--dir`. With v1.1.1, see its [known issue](docs/releases/v1.1.1.md#known-issue-sw-block-mini-as-a-non-root-user-fixed-in-v112).
A failed start leaves `--dir` behind: start again with a new `--dir`, or on the same one with `--reuse`.
**What it shows today:**
- `mini` starts `weed mini`, `blockmaster` and one `blockvolume`: volume `v1`, 256 MiB, on loopback.
- It never runs `sudo` itself. It prints the `nvme connect` command that attaches `v1`, and the status, check and
snapshot commands. After the connect, `sudo nvme list` shows the disk's device (for example `/dev/nvme0n1`).
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. From v1.1.2 `mini`
takes no scheduled snapshot (with v1.1.1 a scheduled `sched-<time>` snapshot appears soon after the start). A
restore into a new volume does not run inside `mini` yet; use the standalone setup for it.
- Snapshots of `v1` work at once, through the `sw-block ops chunk snapshot` command it prints. A scheduled
`sched-<time>` snapshot also appears soon after the start. A restore into a new volume does not run inside `mini`
yet; use the standalone setup for it.
- To stop: unmount `v1`, run the `sudo nvme disconnect` that `mini` printed, then press Ctrl-C.
**Next:**
+4 -4
View File
@@ -129,8 +129,8 @@ type flags struct {
durableBlockSize uint
durableWALMultiBlockRecords bool
durableWALRecoveryTestDisableFlusher bool
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden, for
// tests and sw-block mini's one-user trial; refused under systemd).
// volumeLockDirTestOnly replaces durable.HostVolumeLockDir (hidden,
// test-only; refused under systemd).
volumeLockDirTestOnly string
// WAL retention window past checkpoint LSN. Zero = strict
@@ -333,7 +333,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error))
return flags{}, err
}
if f.volumeLockDirTestOnly != "" && os.Getenv("INVOCATION_ID") != "" {
return flags{}, fmt.Errorf("--%s is for tests and trial runs and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
return flags{}, fmt.Errorf("--%s is test-only and refused under systemd (INVOCATION_ID is set): the one-process-per-host guarantee needs %s", volumeLockDirTestOnlyFlag, durable.HostVolumeLockDir)
}
if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" {
return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode)
@@ -757,7 +757,7 @@ func runVolume(f flags, exits *processExit) int {
VolumeLockDirTestOnly: f.volumeLockDirTestOnly,
}
if f.volumeLockDirTestOnly != "" {
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is an override: one process per volume is enforced only among processes using it\n", f.volumeLockDirTestOnly)
fmt.Fprintf(os.Stderr, "blockvolume: volume lock directory %s is a test override: the one-process-per-host guarantee does not hold\n", f.volumeLockDirTestOnly)
}
var chunkErr error
var chunk chunkWiring
@@ -1,220 +0,0 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"context"
"fmt"
"math/rand"
"net"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
// sw-block mini starts as any user on a host without /run/sw-block: the
// holder takes its volume lock under --dir and serves, every sw-block and
// weed command mini prints names the binary by its absolute path, and no
// scheduled snapshot runs. A start that fails after --dir was made stops what
// it started and prints the --reuse command for the same --dir.
func TestMiniStartsWithoutRootAndNamesItsBinaries(t *testing.T) {
assertMiniUnprivileged(t)
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
t.Fatal("CHUNKSTORE_WEED must name the pinned real SeaweedFS binary")
}
var err error
weed, err = filepath.Abs(weed)
if err != nil {
t.Fatal(err)
}
// The real startup/output assertion must exercise the production hint,
// even when CI supplied an ordinary path. Both spaces and apostrophes need
// POSIX quoting; exec still receives the path as one argument.
quotedWeed := filepath.Join(t.TempDir(), "weed's tools")
if err := os.Symlink(weed, quotedWeed); err != nil {
t.Fatal(err)
}
weed = quotedWeed
bins := os.Getenv("SWBLOCK_TEST_BINS")
if bins == "" {
bins = t.TempDir()
for _, b := range []string{"blockmaster", "blockvolume", "sw-block"} {
miniGoBuild(t, filepath.Join(bins, b), "github.com/seaweedfs/seaweed-block/cmd/"+b)
}
}
bins, err = filepath.Abs(bins)
if err != nil {
t.Fatal(err)
}
cli := filepath.Join(bins, "sw-block")
shift := miniPortShift(t)
dir := filepath.Join(t.TempDir(), "mini")
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
p := startOwnedMini(t, ctx, cli, "mini", "--dir", dir, "--bin", bins, "--weed", weed, "--port-shift", fmt.Sprint(shift))
for !strings.Contains(p.output.String(), "sw-block mini: running") {
select {
case <-p.done:
t.Fatalf("mini did not reach running: %v\n%s", p.err, p.output.String())
case <-ctx.Done():
t.Fatalf("mini startup expired: %s", p.output.String())
case <-time.After(20 * time.Millisecond):
}
}
// The running line precedes the hints; await the last hint without reading
// a buffer concurrently with its writer.
for !strings.Contains(p.output.String(), miniHintWord(weed)+" shell -master=") {
select {
case <-p.done:
t.Fatalf("mini exited before its hints: %s", p.output.String())
case <-ctx.Done():
t.Fatalf("mini hints expired: %s", p.output.String())
case <-time.After(20 * time.Millisecond):
}
}
if err := miniLockConflict(filepath.Join(dir, "locks", "v1.lock")); err != nil {
t.Fatalf("serving holder does not own its trial lock: %v", err)
}
if err := p.signalLeader(syscall.SIGINT); err != nil {
t.Fatalf("could not deliver Ctrl-C: %v", err)
}
if err := p.join(t, 40*time.Second); err != nil {
t.Fatalf("mini after Ctrl-C: %v\n%s", err, p.output.String())
}
p.assertStopped(t) // before the safety-net cleanup: product shutdown owns this
t.Logf("sw-block mini output:\n%s", p.output.String())
if !exists(filepath.Join(dir, "locks", "v1.lock")) {
t.Fatalf("the holder's lock is not under --dir")
}
text := p.output.String()
if strings.Contains(text, "+ sw-block ") || strings.Contains(text, " sw-block ") {
t.Errorf("mini prints a sw-block command without its absolute path")
}
for _, want := range []string{" " + miniHintWord(cli) + " ops workspace show", " " + miniHintWord(cli) + " ops chunk snapshot", miniHintWord(weed) + " shell -master=", "mini takes no scheduled snapshot", miniHintWord(cli) + " mini --dir "} {
if !strings.Contains(text, want) {
t.Errorf("mini's output lacks %q", want)
}
}
// A start that fails after --dir exists names the --reuse command.
broken := t.TempDir()
for _, b := range []string{"blockmaster", "sw-block"} {
if err := os.Symlink(filepath.Join(bins, b), filepath.Join(broken, b)); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(broken, "blockvolume"), []byte("#!/bin/sh"+string(rune(10))+"echo refused >&2; exit 1"+string(rune(10))), 0o755); err != nil {
t.Fatal(err)
}
dir2 := filepath.Join(t.TempDir(), "mini")
ctx2, cancel2 := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel2()
p2 := startOwnedMini(t, ctx2, cli, "mini", "--dir", dir2, "--bin", broken, "--weed", weed, "--port-shift", fmt.Sprint(miniPortShift(t)))
err = p2.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second)
p2.assertNaturalExit(t)
b2 := p2.output.String()
t.Logf("failed start:\n%s", b2)
if err == nil || !strings.Contains(b2, "start again on it with") || !strings.Contains(b2, miniHintWord(cli)+" mini --dir "+miniHintWord(dir2)+" --reuse") {
t.Fatalf("a failed start: %v", err)
}
for _, binary := range []string{weed, filepath.Join(broken, "blockmaster"), filepath.Join(broken, "blockvolume")} {
if !strings.Contains(b2, "+ "+miniHintWord(binary)+" ") {
t.Fatalf("failed-start path did not reach %s: %s", binary, b2)
}
}
p2.assertStopped(t) // rejects a failed start which left weed/master running
}
func miniGoBuild(t *testing.T, out, pkg string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
p := startOwnedMini(t, ctx, "go", "build", "-o", out, pkg)
if err := p.join(t, 3*time.Minute+miniShutdownGrace+10*time.Second); err != nil {
t.Fatalf("build %s: %v\n%s", pkg, err, p.output.String())
}
p.assertStopped(t)
}
// miniPortShift picks a --port-shift whose every mini port (defaultMiniPorts
// in cmd/sw-block) is claimed host-wide and free now, as the other harnesses'
// ports are, so a parallel process-level shard never binds one of them.
func miniPortShift(t *testing.T) int {
t.Helper()
defaults := []int{9180, 9201, 9202, 9203, 4420, 9333, 19333, 9340, 19340, 8888, 18888, 12535, 22535}
for i := 0; i < 200; i++ {
shift := 3000 + rand.Intn(6000)
free := true
for _, p := range defaults {
if !claimHostPort(p + shift) {
free = false
break
}
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p+shift))
if err != nil {
free = false
break
}
ln.Close()
}
if free {
return shift
}
}
t.Fatal("no --port-shift with every mini port claimed and free")
return 0
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
// Expected command words follow the printed POSIX-shell contract.
func miniHintWord(s string) string {
if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@%+=:,./_-") == "" {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
func miniLockConflict(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN {
return nil
}
if err == nil {
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
return fmt.Errorf("lock was available")
}
return err
}
func TestMiniLockProofRequiresContention(t *testing.T) {
path := filepath.Join(t.TempDir(), "v1.lock")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if err := miniLockConflict(path); err == nil {
t.Fatal("unheld file passed the serving-lock proof")
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
t.Fatal(err)
}
if err := miniLockConflict(path); err != nil {
t.Fatalf("held lock failed proof: %v", err)
}
}
@@ -1,615 +0,0 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
"golang.org/x/sys/unix"
)
// Preconditions are assertions: a privileged run is not non-root evidence.
func assertMiniUnprivileged(t *testing.T) {
t.Helper()
if os.Getuid() == 0 || os.Geteuid() == 0 {
t.Fatal("non-root qualification must run without uid 0")
}
p := "/run/sw-block/locks"
// A read-only existing file can still be flocked without a directory write.
// Refuse qualification if it can even be opened; never mutate the host path.
lock, err := os.Open(filepath.Join(p, "v1.lock"))
if err == nil {
_ = lock.Close()
t.Fatal("existing host lock is readable; old host-lock path is usable")
}
if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
t.Fatalf("host lock file preflight: %v", err)
}
for {
_, err := os.Stat(p)
if err == nil {
break
}
if errors.Is(err, syscall.EACCES) || errors.Is(err, syscall.EPERM) {
t.Logf("non-root uid=%d euid=%d; host lock path %s is inaccessible: %v", os.Getuid(), os.Geteuid(), p, err)
return
}
if !errors.Is(err, os.ErrNotExist) {
t.Fatalf("host lock preflight: %v", err)
}
p = filepath.Dir(p)
}
if err := syscall.Access(p, 3); err == nil {
t.Fatalf("host lock path/ancestor %s is writable; non-root precondition is unproved", p)
} else if !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
t.Fatalf("host lock access preflight: %v", err)
}
t.Logf("non-root uid=%d euid=%d; host lock ancestor %s is not writable", os.Getuid(), os.Geteuid(), p)
}
type miniOutput struct {
mu sync.Mutex
b bytes.Buffer
}
func (b *miniOutput) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.b.Write(p)
}
func (b *miniOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.b.String() }
const miniFailStopExit = 86
func miniFailStop(t *testing.T, why string) {
fmt.Fprintf(os.Stderr, "%s: %s; stopping tests before directory cleanup\n", t.Name(), why)
os.Exit(miniFailStopExit)
}
type ownedMini struct {
cmd *exec.Cmd
done chan struct{}
err error
output miniOutput
stopOnce sync.Once
mu sync.Mutex
settled bool
leaderFD int
leaderKey string
dispatches atomic.Int64
watchdog atomic.Bool
// Only the isolated fail-stop controls replace the census or its window.
groupExists func() bool
census func() []int
censusWait time.Duration
captureLeader func(int) (miniProcInfo, error)
}
const miniShutdownGrace = 35 * time.Second // three 10-second child stops plus margin
// Probe before starting any workload. CLONE_PIDFD then obtains the child's
// immutable reference atomically with creation, before a cancellation can run.
func miniPidfdSupport() error {
fd, err := unix.PidfdOpen(os.Getpid(), 0)
if err != nil {
return err
}
defer unix.Close(fd)
return unix.PidfdSendSignal(fd, 0, nil, 0)
}
func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...string) *ownedMini {
t.Helper()
if err := miniPidfdSupport(); err != nil {
t.Fatalf("pidfd ownership unavailable before start: %v", err)
}
p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{}), leaderFD: -1}
p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, PidFD: &p.leaderFD}
p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output
// os/exec must not kill only the leader after a short WaitDelay. Our
// watchdog grants the full product shutdown window, then owns group cleanup.
p.cmd.Cancel = func() error { p.watchdog.Store(true); go p.stop(t); return nil }
p.mu.Lock() // a context cancellation cannot observe the unopened pidfd
if err := p.cmd.Start(); err != nil {
p.mu.Unlock()
t.Fatal(err)
}
if p.leaderFD < 0 {
p.mu.Unlock()
p.ownershipFailed(t, "atomic leader pidfd missing")
}
info, err := miniProc(p.cmd.Process.Pid)
if err != nil {
p.mu.Unlock()
p.ownershipFailed(t, fmt.Sprintf("cannot record leader incarnation: %v", err))
}
p.leaderKey = info.key
p.mu.Unlock()
go func() { p.err = p.cmd.Wait(); close(p.done) }()
t.Cleanup(func() { p.stop(t) })
return p
}
// No Wait goroutine exists yet: the unreaped direct child cannot have its
// PID recycled. Stop and reap it before failing closed with directories kept.
func (p *ownedMini) ownershipFailed(t *testing.T, why string) {
_ = p.cmd.Process.Kill()
p.cmd.WaitDelay = time.Second
reaped := make(chan struct{})
go func() { _ = p.cmd.Wait(); close(reaped) }()
select {
case <-reaped:
case <-time.After(5 * time.Second):
}
miniFailStop(t, why)
}
func (p *ownedMini) signalFD(fd int, sig unix.Signal) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.settled {
return os.ErrProcessDone
}
p.dispatches.Add(1)
return unix.PidfdSendSignal(fd, sig, nil, 0)
}
func (p *ownedMini) signalLeader(sig unix.Signal) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.settled {
return os.ErrProcessDone
}
p.dispatches.Add(1)
return unix.PidfdSendSignal(p.leaderFD, sig, nil, 0)
}
func (p *ownedMini) isSettled() bool { p.mu.Lock(); defer p.mu.Unlock(); return p.settled }
func (p *ownedMini) settle() {
p.mu.Lock()
defer p.mu.Unlock()
if !p.settled {
p.settled = true
if p.leaderFD >= 0 {
_ = unix.Close(p.leaderFD)
p.leaderFD = -1
}
}
}
func (p *ownedMini) join(t *testing.T, bound time.Duration) error {
t.Helper()
select {
case <-p.done:
return p.err
case <-time.After(bound):
miniFailStop(t, fmt.Sprintf("owned process did not join in %s", bound))
return nil
}
}
func (p *ownedMini) assertNaturalExit(t *testing.T) {
t.Helper()
if p.watchdog.Load() {
t.Fatal("watchdog intervened; failed-start cleanup was not completed by mini")
}
}
func (p *ownedMini) stop(t *testing.T) {
p.stopOnce.Do(func() {
if p.isSettled() {
return
}
_ = p.signalLeader(unix.SIGTERM)
select {
case <-p.done:
p.assertStopped(t)
return
case <-time.After(miniShutdownGrace):
}
p.stopGroup(t)
})
}
// Never signal a numeric PGID. While the original leader is stopped, its
// group identity cannot disappear; capture and stop each member by pidfd.
// After resuming, TERM/KILL use those immutable references even if a PID is
// recycled. Unknown late members or an exited leader with live residue cause
// fail-stop rather than guessing ownership and signaling an unrelated group.
func (p *ownedMini) stopGroup(t *testing.T) {
t.Helper()
if p.isSettled() {
return
}
select {
case <-p.done:
p.assertStopped(t)
return
default:
}
if err := p.signalLeader(unix.SIGSTOP); err != nil {
select {
case <-p.done:
p.assertStopped(t)
return
default:
miniFailStop(t, fmt.Sprintf("cannot stop owned leader: %v", err))
}
}
pgid := p.cmd.Process.Pid
leaderFD := p.leaderFD
refs := map[string]int{}
defer func() {
for _, fd := range refs {
if fd != leaderFD {
_ = unix.Close(fd)
}
}
}()
deadline := time.Now().Add(time.Second)
for {
select {
case <-p.done:
p.assertStopped(t)
return
default:
}
readLeader := miniProc
if p.captureLeader != nil {
readLeader = p.captureLeader
}
leader, err := readLeader(pgid)
if err != nil || leader.key != p.leaderKey || (leader.state != "T" && leader.state != "t") || unix.PidfdSendSignal(leaderFD, 0, nil, 0) != nil {
if time.Now().After(deadline) {
p.captureExpired(t, "leader incarnation not held during member capture")
return
}
time.Sleep(5 * time.Millisecond)
continue
}
refs[leader.key] = leaderFD
members := miniGroupMembers(t, pgid)
stopped := true
for _, m := range members {
fd, ok := refs[m.key]
if !ok {
fd, err = unix.PidfdOpen(m.pid, 0)
if err != nil {
if errors.Is(err, unix.ESRCH) {
stopped = false
continue
}
miniFailStop(t, fmt.Sprintf("cannot own descendant: %v", err))
}
current, err := miniProc(m.pid)
if err != nil || current.key != m.key || current.group != pgid {
_ = unix.Close(fd)
stopped = false
continue
}
refs[m.key] = fd
}
if m.state != "T" && m.state != "t" {
stopped = false
if err := p.signalFD(fd, unix.SIGSTOP); err != nil && !errors.Is(err, unix.ESRCH) {
miniFailStop(t, fmt.Sprintf("cannot stop descendant: %v", err))
}
}
}
if stopped {
break
}
if time.Now().After(deadline) {
p.captureExpired(t, "descendant capture did not quiesce")
return
}
time.Sleep(5 * time.Millisecond)
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGTERM)
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGCONT)
}
select {
case <-p.done:
case <-time.After(2 * time.Second):
}
for _, fd := range refs {
_ = p.signalFD(fd, unix.SIGKILL)
}
_ = p.join(t, 5*time.Second)
p.assertStopped(t)
}
// A leader that exits as the capture window closes settles through assertStopped.
func (p *ownedMini) captureExpired(t *testing.T, why string) {
t.Helper()
select {
case <-p.done:
p.assertStopped(t)
default:
miniFailStop(t, why)
}
}
func (p *ownedMini) assertStopped(t *testing.T) {
t.Helper()
wait := p.censusWait
if wait == 0 {
wait = 5 * time.Second
}
deadline := time.Now().Add(wait)
census := func() []int {
if p.census != nil {
return p.census()
}
return miniGroupLive(t, p.cmd.Process.Pid)
}
for {
live := census()
// A /proc listing is not atomic: a member can fork then disappear
// between list and stat. Signal 0 is only an existence query (never a
// numeric effect signal); ESRCH proves the entire group is now absent.
absent := false
if p.groupExists != nil {
absent = !p.groupExists()
} else {
err := unix.Kill(-p.cmd.Process.Pid, 0)
absent = errors.Is(err, unix.ESRCH)
}
// A member counted before ESRCH may have exited in between: count
// again, so only a member still listed holds the settlement.
if len(live) != 0 && absent {
live = census()
}
if len(live) == 0 && absent {
select {
case <-p.done:
p.settle()
return
default:
miniFailStop(t, "empty group but leader not joined")
}
}
if time.Now().After(deadline) {
if len(live) == 0 {
miniFailStop(t, "owned group still exists with no live member listed: a member the census missed, or zombies its new parent does not reap")
}
miniFailStop(t, fmt.Sprintf("owned group has live residue %v", live))
}
time.Sleep(5 * time.Millisecond)
}
}
type miniProcInfo struct {
pid, group int
state, key string
}
func miniProc(pid int) (miniProcInfo, error) {
b, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if err != nil {
return miniProcInfo{}, err
}
end := strings.LastIndexByte(string(b), ')')
if end < 0 {
return miniProcInfo{}, fmt.Errorf("invalid proc stat")
}
fields := strings.Fields(string(b[end+1:]))
if len(fields) < 20 {
return miniProcInfo{}, fmt.Errorf("short proc stat")
}
group, err := strconv.Atoi(fields[2])
if err != nil {
return miniProcInfo{}, err
}
return miniProcInfo{pid: pid, group: group, state: fields[0], key: strconv.Itoa(pid) + ":" + fields[19]}, nil
}
func miniGroupMembers(t *testing.T, pgid int) []miniProcInfo {
entries, err := os.ReadDir("/proc")
if err != nil {
miniFailStop(t, err.Error())
}
var members []miniProcInfo
for _, entry := range entries {
pid, err := strconv.Atoi(entry.Name())
if err != nil {
continue
}
info, err := miniProc(pid)
if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
continue
}
if err != nil {
miniFailStop(t, err.Error())
}
if info.group == pgid && info.state != "Z" && info.state != "X" {
members = append(members, info)
}
}
return members
}
func miniGroupLive(t *testing.T, pgid int) []int {
var live []int
for _, m := range miniGroupMembers(t, pgid) {
live = append(live, m.pid)
}
return live
}
// An intentionally TERM-ignoring descendant exercises the safety net itself.
func TestMiniOwnedGroupCleanupStopsDescendants(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap '' TERM; sleep 60 & echo ready; wait")
deadline := time.Now().Add(5 * time.Second)
for !strings.Contains(p.output.String(), "ready") {
if time.Now().After(deadline) {
t.Fatal("fixture did not start")
}
time.Sleep(10 * time.Millisecond)
}
if live := miniGroupLive(t, p.cmd.Process.Pid); len(live) < 2 {
t.Fatalf("descendant fixture not reached: %v", live)
}
p.stop(t)
select {
case <-p.done:
default:
t.Fatal("leader not joined")
}
}
// This real process settles normally before its registered cleanup runs. A
// later cleanup must not dispatch anything to its old group or descriptor.
func TestMiniSettledCleanupDoesNotSignal(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/true")
if err := p.join(t, 3*time.Second); err != nil {
t.Fatal(err)
}
p.assertStopped(t)
before := p.dispatches.Load()
p.stop(t)
if got := p.dispatches.Load(); got != before {
t.Fatalf("settled cleanup dispatched %d signals", got-before)
}
}
func TestMiniCleanupFailStopAndSettlement(t *testing.T) {
for _, mode := range []string{"join", "residue", "missed-member", "settled", "late-exit-settled", "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue", "natural", "watchdog"} {
t.Run(mode, func(t *testing.T) {
marker := filepath.Join(t.TempDir(), "cleanup-ran")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
t.Setenv("MINI_CLEANUP_CONTROL", mode)
t.Setenv("MINI_CLEANUP_MARKER", marker)
p := startOwnedMini(t, ctx, self, "-test.run=^TestMiniCleanupFailStopHelper$")
err = p.join(t, 3*time.Second)
p.assertStopped(t)
_, statErr := os.Stat(marker)
if mode == "settled" || mode == "late-exit-settled" || mode == "capture-settled" || mode == "capture-expired-settled" || mode == "natural" {
if err != nil || statErr != nil {
t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr)
}
} else if mode == "watchdog" {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(p.output.String(), "watchdog intervened") || statErr != nil {
t.Fatalf("watchdog cannot prove natural cleanup: err=%v marker=%v output=%s", err, statErr, p.output.String())
}
} else {
var exit *exec.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != miniFailStopExit || !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("fail-stop %s: err=%v marker=%v output=%s", mode, err, statErr, p.output.String())
}
}
})
}
}
func TestMiniCleanupFailStopHelper(t *testing.T) {
mode := os.Getenv("MINI_CLEANUP_CONTROL")
if mode == "" {
t.Skip("isolated fail-stop helper")
}
t.Cleanup(func() {
if err := os.WriteFile(os.Getenv("MINI_CLEANUP_MARKER"), []byte("cleanup ran"), 0o600); err != nil {
t.Error(err)
}
})
p := &ownedMini{done: make(chan struct{}), leaderFD: -1, censusWait: 10 * time.Millisecond, groupExists: func() bool { return false }}
switch mode {
case "join":
p.join(t, 10*time.Millisecond)
case "residue":
close(p.done)
p.census = func() []int { return []int{1234} }
p.assertStopped(t)
case "missed-member":
close(p.done)
p.census = func() []int { return nil }
p.groupExists = func() bool { return true }
p.assertStopped(t)
case "settled":
close(p.done)
p.census = func() []int { return nil }
p.assertStopped(t)
case "late-exit-settled":
close(p.done)
counted := false
p.census = func() []int {
if counted {
return nil
}
counted = true
time.Sleep(2 * p.censusWait) // the member exits as the window closes
return []int{1234}
}
p.assertStopped(t)
case "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue":
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sleep", "60")
p.censusWait = 10 * time.Millisecond
if strings.HasSuffix(mode, "-residue") {
p.census = func() []int { return []int{1234} }
p.groupExists = func() bool { return true }
}
p.captureLeader = func(int) (miniProcInfo, error) {
if strings.HasPrefix(mode, "capture-expired") {
time.Sleep(1100 * time.Millisecond) // past the one-second capture window
}
_ = p.signalLeader(unix.SIGKILL)
_ = p.join(t, time.Second)
return miniProcInfo{}, os.ErrNotExist
}
p.stopGroup(t)
case "natural", "watchdog":
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
bin, args := "/bin/false", []string{}
if mode == "watchdog" {
bin, args = "/bin/sleep", []string{"60"}
}
p := startOwnedMini(t, ctx, bin, args...)
if mode == "watchdog" {
cancel()
}
_ = p.join(t, time.Second)
p.assertStopped(t)
p.assertNaturalExit(t)
default:
t.Fatal("invalid control")
}
}
// A four-second shutdown exceeds the old WaitDelay. The context watchdog
// must let it finish rather than kill its leader before children are stopped.
func TestMiniContextAllowsChildShutdownGrace(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap 'sleep 4; echo graceful; exit 0' TERM; echo ready; while :; do sleep .05; done")
deadline := time.Now().Add(5 * time.Second)
for !strings.Contains(p.output.String(), "ready") {
if time.Now().After(deadline) {
t.Fatal("shutdown fixture not ready")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
_ = p.join(t, miniShutdownGrace+10*time.Second)
p.assertStopped(t)
if !strings.Contains(p.output.String(), "graceful") {
t.Fatalf("shutdown killed prematurely: %s", p.output.String())
}
}
@@ -6,8 +6,6 @@ import (
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// The test lock directory override is refused under systemd
@@ -52,42 +50,3 @@ func TestVolumeLockDirTestOnlyHiddenFromHelp(t *testing.T) {
t.Fatalf("--help lists the test override:\n%s", out)
}
}
// Without the override the lock directory stays the host one: the provider
// gets no override, so it uses durable.HostVolumeLockDir.
func TestVolumeLockDirDefaultIsTheHostDirectory(t *testing.T) {
t.Setenv("INVOCATION_ID", "")
f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore"))
if err != nil {
t.Fatal(err)
}
if f.volumeLockDirTestOnly != "" {
t.Fatalf("a default start overrides the lock directory: %q", f.volumeLockDirTestOnly)
}
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
}
}
// INV-WS-ONE-PROCESS-PER-HOST-001, the normal start: a start under systemd
// (INVOCATION_ID set, as every shipped unit runs) keeps the host-wide volume
// lock. Without the override it gets no lock directory of its own, so the
// provider uses the host one; with the hidden test-only override it is
// refused, naming the host lock directory it would have bypassed. Only a
// start outside systemd (a test, or mini, which drops INVOCATION_ID from its
// children and keeps data and lock under its --dir) may move the lock.
func TestNormalStartKeepsTheHostVolumeLock(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore")
t.Setenv("INVOCATION_ID", "0123456789abcdef")
f, err := parseFlags(append([]string(nil), base...))
if err != nil || f.volumeLockDirTestOnly != "" {
t.Fatalf("a unit start without the override: lock dir %q, err %v; want the host directory", f.volumeLockDirTestOnly, err)
}
if durable.HostVolumeLockDir != "/run/sw-block/locks" {
t.Fatalf("the host lock directory moved: %s", durable.HostVolumeLockDir)
}
_, err = parseFlags(append(append([]string(nil), base...), "--"+volumeLockDirTestOnlyFlag+"="+t.TempDir()))
if err == nil || !strings.Contains(err.Error(), durable.HostVolumeLockDir) {
t.Fatalf("a unit start with the override: %v; want a refusal naming %s", err, durable.HostVolumeLockDir)
}
}
+29 -125
View File
@@ -84,9 +84,6 @@ type miniConfig struct {
// Explicit names the flags given on the command line (fs.Visit); a
// --reuse refuses one that differs from the recorded run.
Explicit map[string]bool
// Self and WeedPath are the absolute paths of this sw-block and of the
// weed it runs, for the commands mini prints; empty in unit tests.
Self, WeedPath string
}
// miniRecord is what a fresh start records in <dir>/mini.json and --reuse
@@ -102,23 +99,6 @@ type miniRecord struct {
const miniRecordFile = "mini.json"
// Make an executable path absolute without collapsing symlink/.. components.
func miniExecutablePath(path string) (string, error) {
if filepath.IsAbs(path) {
return path, nil
}
volume := filepath.VolumeName(path)
base, err := filepath.Abs(volume + ".")
if err != nil {
return "", err
}
relative := strings.TrimPrefix(path, volume)
if len(relative) > 0 && os.IsPathSeparator(relative[0]) {
return filepath.VolumeName(base) + relative, nil
}
return base + string(os.PathSeparator) + relative, nil
}
func writeMiniRecord(dir string, r miniRecord) error {
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
@@ -139,20 +119,6 @@ func reuseMiniRecord(c *miniConfig, weedFound string) (string, error) {
if err := json.Unmarshal(b, &r); err != nil {
return "", fmt.Errorf("--reuse: %s/%s: %w", c.Dir, miniRecordFile, err)
}
if r.Weed != "" {
abs, err := miniExecutablePath(r.Weed)
if err != nil {
return "", fmt.Errorf("--reuse: resolve weed path: %w", err)
}
r.Weed = abs
}
if c.Weed != r.Weed && c.Weed != "" && r.Weed != "" {
now, errNow := os.Stat(c.Weed)
then, errThen := os.Stat(r.Weed)
if errNow == nil && errThen == nil && os.SameFile(now, then) {
c.Weed = r.Weed
}
}
differs := func(flag string, now, then any) error {
if c.Explicit[flag] && fmt.Sprint(now) != fmt.Sprint(then) {
return fmt.Errorf("--reuse: --%s %v differs from this dir's run (%v); drop it to reuse the run as recorded", flag, now, then)
@@ -221,16 +187,9 @@ func miniMasterArgs(c miniConfig, chunk bool) []string {
}
// miniVolumeArgs is blockvolume as swb_start runs it, plus, with a chunk
// store, the walstore-chunk settings and the volume's layout id. Its volume
// lock is under the run's dir, so mini needs no root and no tmpfiles.d entry
// (a trial override, which blockvolume refuses under systemd); with a chunk
// store it takes no scheduled snapshot (mini prints how to take one).
// store, the walstore-chunk settings and the volume's layout id.
func miniVolumeArgs(c miniConfig, chunk bool, layoutID string) []string {
a := append(miniVolumeSpec(c, chunk, layoutID).args(), "--volume-lock-dir-test-only", filepath.Join(c.Dir, "locks"))
if chunk {
a = append(a, "--chunk-snapshot-schedule", "off")
}
return a
return miniVolumeSpec(c, chunk, layoutID).args()
}
// miniVolumeSpec is mini's v1: the same settings volume start writes for a
@@ -310,25 +269,13 @@ type miniRun struct {
// start prints the command, then starts it with its output in <dir>/<name>.log.
func (r *miniRun) start(name, bin string, args []string) (*miniChild, error) {
words := []string{shQuote(bin)}
for _, a := range args {
words = append(words, shQuote(a))
}
fmt.Fprintf(r.out, "+ %s\n", strings.Join(words, " "))
fmt.Fprintf(r.out, "+ %s %s\n", bin, strings.Join(args, " "))
lf, err := os.Create(filepath.Join(r.cfg.Dir, name+".log"))
if err != nil {
return nil, err
}
cmd := exec.Command(bin, args...)
cmd.Stdout, cmd.Stderr, cmd.Stdin = lf, lf, nil
cmd.Env = []string{}
// mini's children are not systemd units even when mini runs under one;
// blockvolume refuses mini's lock directory while INVOCATION_ID is set.
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "INVOCATION_ID=") {
cmd.Env = append(cmd.Env, kv)
}
}
if err := cmd.Start(); err != nil {
lf.Close()
return nil, fmt.Errorf("start %s: %w", name, err)
@@ -375,30 +322,6 @@ func (r *miniRun) ready(ctx context.Context, c *miniChild, ports ...int) error {
}
}
// resolveLayoutID looks up volume's layout id through blockmaster,
// retrying while blockmaster registers it, bounded by miniResolveWait.
func (r *miniRun) resolveLayoutID(ctx context.Context, master, volume string) (string, error) {
deadline := time.Now().Add(miniResolveWait)
for {
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
id, err := resolveVolumeID(rctx, master, volume)
rcancel()
if err == nil {
return id.String(), nil
}
if d := r.dead(); d != nil {
return "", fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, volume, d.err)
}
if ctx.Err() != nil || time.Now().After(deadline) {
return "", fmt.Errorf("resolve %s's layout id: %v", volume, err)
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
}
// dead is the first child that has exited, if any.
func (r *miniRun) dead() *miniChild {
for _, c := range r.children {
@@ -491,26 +414,10 @@ func runMini(args []string, stdout, stderr io.Writer) int {
func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, error) {
weed := cfg.Weed
if weed == "" {
var err error
if weed, err = exec.LookPath("weed"); errors.Is(err, exec.ErrDot) {
if !cfg.Reuse {
return ops.VolumeStatusExitInvalid, fmt.Errorf("weed on PATH is in the current directory (%v); pass --weed %s to use it", err, shQuote("./"+weed))
}
weed = ""
}
weed, _ = exec.LookPath("weed")
} else if st, err := os.Stat(weed); err != nil || st.IsDir() {
return ops.VolumeStatusExitInvalid, fmt.Errorf("--weed %s not found", weed)
}
if weed != "" {
abs, err := miniExecutablePath(weed)
if err != nil {
return ops.VolumeStatusExitInvalid, fmt.Errorf("resolve weed path: %w", err)
}
weed = abs
if cfg.Weed != "" {
cfg.Weed = abs
}
}
// A reuse takes the recorded run (its binaries included) before any
// lookup; a fresh start finds the binaries next to sw-block by default.
if cfg.Reuse {
@@ -578,11 +485,7 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
return 1, err
}
}
if exe, err := os.Executable(); err == nil {
cfg.Self = exe
}
cfg.WeedPath = weed
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol"), filepath.Join(cfg.Dir, "locks")} {
for _, d := range []string{filepath.Join(cfg.Dir, "master"), filepath.Join(cfg.Dir, "vol")} {
if err := os.MkdirAll(d, 0o755); err != nil {
return 1, err
}
@@ -591,8 +494,6 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
defer r.stop()
fail := func(err error) (int, error) {
r.tail(20)
r.stop()
fmt.Fprintf(stderr, "sw-block mini: not started; logs in %s/*.log. After fixing the cause, start again on it with\n %s\nor remove %s and start fresh.\n", shQuote(cfg.Dir), miniResume(cfg), shQuote(cfg.Dir))
return 1, err
}
if chunk {
@@ -621,9 +522,26 @@ func mini(ctx context.Context, cfg miniConfig, stdout, stderr io.Writer) (int, e
}
layoutID := ""
if chunk {
fmt.Fprintf(stdout, "+ %s ops volume resolve --master %s %s\n", miniSelf(cfg), loopback(cfg.Ports.Master), miniVolume)
if layoutID, err = r.resolveLayoutID(ctx, loopback(cfg.Ports.Master), miniVolume); err != nil {
return fail(err)
fmt.Fprintf(stdout, "+ sw-block ops volume resolve --master %s %s\n", loopback(cfg.Ports.Master), miniVolume)
deadline := time.Now().Add(miniResolveWait)
for {
rctx, rcancel := context.WithTimeout(ctx, 5*time.Second)
id, err := resolveVolumeID(rctx, loopback(cfg.Ports.Master), miniVolume)
rcancel()
if err == nil {
layoutID = id.String()
break
}
if d := r.dead(); d != nil {
return fail(fmt.Errorf("%s exited while resolving %s's layout id: %v", d.name, miniVolume, d.err))
}
if ctx.Err() != nil || time.Now().After(deadline) {
return fail(fmt.Errorf("resolve %s's layout id: %v", miniVolume, err))
}
select {
case <-ctx.Done():
case <-time.After(time.Second):
}
}
}
vc, err := r.start("blockvolume", volume, miniVolumeArgs(cfg, chunk, layoutID))
@@ -683,18 +601,9 @@ func shQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// miniSelf is how a printed command names this sw-block: its absolute path
// when known, so the command runs from any directory.
func miniSelf(c miniConfig) string {
if c.Self == "" {
return "sw-block"
}
return shQuote(c.Self)
}
// miniResume is the command that starts the recorded run in c.Dir again.
func miniResume(c miniConfig) string {
return miniSelf(c) + " mini --dir " + shQuote(c.Dir) + " --reuse"
return "sw-block mini --dir " + shQuote(c.Dir) + " --reuse"
}
// miniNextSteps prints what to run next; mini runs none of it.
@@ -710,14 +619,9 @@ func miniNextSteps(w io.Writer, c miniConfig, chunk bool) {
return
}
cmds := miniCommands(c, chunk)
self := miniSelf(c)
fmt.Fprintf(w, "\nCheck the volume:\n %s %s\n %s %s\n", self, strings.Join(cmds[0], " "), self, strings.Join(cmds[1], " "))
fmt.Fprintf(w, "\nSnapshot (mini takes no scheduled snapshot):\n %s %s\n", self, strings.Join(cmds[2], " "))
weed := "weed"
if c.WeedPath != "" {
weed = shQuote(c.WeedPath)
}
fmt.Fprintf(w, "\nSeaweedFS itself: %s shell -master=%s\n", weed, loopback(c.Ports.WeedMaster))
fmt.Fprintf(w, "\nCheck the volume:\n sw-block %s\n sw-block %s\n", strings.Join(cmds[0], " "), strings.Join(cmds[1], " "))
fmt.Fprintf(w, "\nSnapshot:\n sw-block %s\n", strings.Join(cmds[2], " "))
fmt.Fprintf(w, "\nSeaweedFS itself: weed shell -master=%s\n", loopback(c.Ports.WeedMaster))
}
// miniBeforeStop reminds the user, before the target goes away, to have
+4 -142
View File
@@ -3,7 +3,6 @@ package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
@@ -58,9 +57,6 @@ func fakeMiniChild(mode string) int {
term := make(chan os.Signal, 1)
signal.Notify(term, syscall.SIGTERM)
if mode == "die-"+name {
if marker := os.Getenv("SWB_MINI_FAKE_RAN"); marker != "" {
_ = os.WriteFile(marker, []byte(name), 0o644)
}
time.Sleep(500 * time.Millisecond)
return 9
}
@@ -149,9 +145,7 @@ func TestMiniWalstoreFlagsAreThePage(t *testing.T) {
}
}
for f := range got {
// mini keeps the volume lock under --dir, so it needs no root
// (the page's unit uses the host lock directory).
if _, ok := page[f]; !ok && f != "--volume-lock-dir-test-only" {
if _, ok := page[f]; !ok {
t.Errorf("%s: mini passes %s; the page's swb_start does not", c.binary, f)
}
}
@@ -334,7 +328,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
}
})
waitOutput(t, out, "sw-block mini: running")
for _, want := range []string{"+ " + shQuote(filepath.Join(c.Bin, "blockmaster")) + " ", "+ " + shQuote(filepath.Join(c.Bin, "blockvolume")) + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
for _, want := range []string{"+ " + filepath.Join(c.Bin, "blockmaster") + " ", "+ " + filepath.Join(c.Bin, "blockvolume") + " ", "sudo nvme connect -t tcp -a 127.0.0.1 -s " + strconv.Itoa(c.Ports.NVMe) + " -n nqn.test:v1", "sudo nvme disconnect -n nqn.test:v1",
"sw-block mini: no chunk store: snapshots unavailable", "trial setup: one host, loopback, no authentication"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("output lacks %q:\n%s", want, out.String())
@@ -350,12 +344,7 @@ func TestMiniInterruptStopsEveryChild(t *testing.T) {
case <-time.After(30 * time.Second):
t.Fatal("mini did not stop")
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
resume := miniResume(miniConfig{Dir: c.Dir, Self: self})
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + resume + "\n"} {
for _, want := range []string{"if v1 is connected: unmount it, then sudo nvme disconnect -n nqn.test:v1", "The data stays in " + c.Dir, " " + miniResume(c) + "\n"} {
if !strings.Contains(out.String(), want) {
t.Fatalf("at stop, output lacks %q:\n%s", want, out.String())
}
@@ -453,8 +442,7 @@ func wantChunkCommands(dir, id string) map[string][]string {
"--data-addr", "127.0.0.1:9201", "--ctrl-addr", "127.0.0.1:9202", "--status-addr", "127.0.0.1:9203",
"--durable-root", filepath.Join(dir, "vol"), "--durable-impl", "walstore-chunk", "--durable-blocks", "65536", "--durable-blocksize", "4096",
"--chunk-filer", "127.0.0.1:18888", "--chunk-path", "/swblock/chunks", "--chunk-control-endpoint", "--workspace-lease", "--layout-id", id,
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1",
"--volume-lock-dir-test-only", filepath.Join(dir, "locks"), "--chunk-snapshot-schedule", "off"},
"--nvme-listen", "127.0.0.1:4420", "--nvme-subsysnqn", "nqn.2026-05.io.seaweedfs:v1"},
}
}
@@ -589,52 +577,6 @@ func TestMiniWeedDyingDuringStartupStopsTheRest(t *testing.T) {
}
}
func TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("signals and listening children: Linux")
}
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
ran := filepath.Join(t.TempDir(), "ran")
t.Setenv("SWB_MINI_FAKE_RAN", ran)
bin := fakeBin(t)
abs := filepath.Join(bin, "weed")
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
rel, err := filepath.Rel(cwd, abs)
if err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out := &syncBuf{}
code, err := mini(ctx, c, out, io.Discard)
if code == 0 || err == nil {
t.Fatalf("fixture must reach the dying weed: code=%d err=%v", code, err)
}
b, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatal(err)
}
var record miniRecord
if err := json.Unmarshal(b, &record); err != nil {
t.Fatal(err)
}
selected, selectedErr := os.Stat(abs)
recorded, recordedErr := os.Stat(record.Weed)
if selectedErr != nil || recordedErr != nil || !filepath.IsAbs(record.Weed) || !os.SameFile(selected, recorded) {
t.Errorf("record weed=%q changed selected executable %q", record.Weed, abs)
}
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
t.Errorf("relative weed command: %s", out.String())
}
if _, err := os.Stat(ran); err != nil {
t.Errorf("the selected weed did not run: %v", err)
}
}
// --reuse starts the recorded run again: its size, ports, mode (its weed)
// and NQN, whatever the defaults are; a flag that differs from the record
// is refused, and so are a recorded weed that is gone and a walstore run
@@ -858,83 +800,3 @@ func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) {
t.Fatalf("control: the unquoted line reached the dir too (exit %d)", code)
}
}
// mini started from a systemd service's process tree (a CI runner unit, a
// terminal server) inherits INVOCATION_ID; blockvolume refuses the lock-dir
// override under it, so mini's children must start without it.
func TestMiniChildrenStartWithoutInvocationID(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix child environment and signals")
}
t.Setenv("INVOCATION_ID", "0123456789abcdef")
dir := t.TempDir()
r := &miniRun{cfg: miniConfig{Dir: dir}, out: io.Discard, log: io.Discard}
c, err := r.start("env", "/bin/sh", []string{"-c", `echo "id=${INVOCATION_ID-unset}"`})
if err != nil {
t.Fatal(err)
}
joined := false
stop := func() {
if joined {
return
}
_ = c.cmd.Process.Signal(syscall.SIGTERM)
select {
case <-c.done:
joined = true
return
case <-time.After(2 * time.Second):
}
_ = c.cmd.Process.Kill()
select {
case <-c.done:
joined = true
case <-time.After(2 * time.Second):
fmt.Fprintln(os.Stderr, "mini child did not join; stopping tests before directory cleanup")
os.Exit(86)
}
}
t.Cleanup(stop)
select {
case <-c.done:
joined = true
case <-time.After(2 * time.Second):
stop()
t.Fatal("mini environment child did not finish")
}
b, err := os.ReadFile(filepath.Join(dir, "env.log"))
if err != nil {
t.Fatal(err)
}
if got := strings.TrimSpace(string(b)); got != "id=unset" {
t.Fatalf("mini's child saw %q", got)
}
}
// An empty filtered environment must be explicit: nil would inherit again.
func TestMiniOnlyInvocationIDDoesNotLeak(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix environment child")
}
saved := os.Environ()
t.Cleanup(func() {
os.Clearenv()
for _, kv := range saved {
key, value, _ := strings.Cut(kv, "=")
_ = os.Setenv(key, value)
}
})
os.Clearenv()
TestMiniChildrenStartWithoutInvocationID(t)
}
// Assert the actual weed-hint call site, not only the quoting helper. This
// stays sensitive if formatting is correct but the hint stops calling it.
func TestMiniProductionWeedHintQuotesItsExecutable(t *testing.T) {
var out bytes.Buffer
miniNextSteps(&out, miniConfig{WeedPath: "/tmp/weed's tools/weed"}, true)
const want = `SeaweedFS itself: '/tmp/weed'\''s tools/weed' shell -master=`
if !strings.Contains(out.String(), want) {
t.Fatalf("production weed hint lacks %q:\n%s", want, out.String())
}
}
@@ -1,219 +0,0 @@
package main
import (
"context"
"encoding/json"
"io"
"net"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestMiniWeedSymlinkParentKeepsSelectedExecutable(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix symlink and child-process fixture")
}
t.Setenv("SWB_MINI_FAKE_CHILD", "die-weed")
bin := fakeBin(t)
root := t.TempDir()
for _, dir := range []string{"tools", "releases/v2"} {
if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
t.Fatal(err)
}
}
selected := filepath.Join(root, "releases", "weed")
if err := os.Symlink(filepath.Join(bin, "weed"), selected); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "tools", "weed"), []byte("wrong executable"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "releases", "v2"), filepath.Join(root, "tools", "current")); err != nil {
t.Fatal(err)
}
t.Chdir(root)
rel := "tools/current/../weed"
want, err := os.Stat(selected)
if err != nil {
t.Fatal(err)
}
check := func(t *testing.T, path string) {
t.Helper()
got, err := os.Stat(path)
if err != nil || !filepath.IsAbs(path) || !os.SameFile(want, got) {
t.Fatalf("selected executable changed: path=%q stat=%v", path, err)
}
}
t.Run("fresh", func(t *testing.T) {
ran := filepath.Join(t.TempDir(), "ran")
t.Setenv("SWB_MINI_FAKE_RAN", ran)
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), Bin: bin, Weed: rel, NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out := &syncBuf{}
_, _ = mini(ctx, c, out, io.Discard)
data, err := os.ReadFile(filepath.Join(c.Dir, miniRecordFile))
if err != nil {
t.Fatalf("did not reach record publication: %v; %s", err, out.String())
}
var record miniRecord
if err := json.Unmarshal(data, &record); err != nil {
t.Fatal(err)
}
check(t, record.Weed)
if !strings.Contains(out.String(), "+ "+shQuote(record.Weed)+" ") {
t.Fatalf("selected executable was not launched: %s", out.String())
}
if _, err := os.Stat(ran); err != nil {
t.Fatalf("the selected weed did not run: %v", err)
}
})
t.Run("legacy", func(t *testing.T) {
dir := t.TempDir()
if err := writeMiniRecord(dir, miniRecord{Weed: rel, Bin: bin, SizeBytes: 1 << 20, NQN: "n"}); err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: dir}
weed, err := reuseMiniRecord(&c, "")
if err != nil {
t.Fatal(err)
}
check(t, weed)
})
}
func TestMiniRefusesWeedFoundThroughDotInPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
t.Setenv("PATH", ".")
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
code, err := mini(context.Background(), c, io.Discard, io.Discard)
if code == 0 || err == nil || !strings.Contains(err.Error(), "current directory") {
t.Fatalf("weed found only through . in PATH: code %d err %v; want a refusal", code, err)
}
if _, err := os.Stat(c.Dir); !os.IsNotExist(err) {
t.Fatalf("refused start created %s: %v", c.Dir, err)
}
}
func TestMiniReuseAcceptsSameWeedFromAnotherDirectory(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix paths")
}
root := t.TempDir()
for _, d := range []string{"a", "b", "bin"} {
if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(root, "bin", "weed"), []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "bin", "other"), []byte("x"), 0o755); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
recorded := filepath.Join(root, "a") + "/../bin/weed"
if err := writeMiniRecord(dir, miniRecord{Weed: recorded, Bin: t.TempDir(), SizeBytes: 1 << 20, NQN: "n"}); err != nil {
t.Fatal(err)
}
t.Chdir(filepath.Join(root, "b"))
weedNow := func(t *testing.T, rel string) (string, error) {
t.Helper()
abs, err := miniExecutablePath(rel)
if err != nil {
t.Fatal(err)
}
c := miniConfig{Dir: dir, Weed: abs, Explicit: map[string]bool{"weed": true}}
return reuseMiniRecord(&c, abs)
}
if weed, err := weedNow(t, "../bin/weed"); err != nil || weed != recorded {
t.Fatalf("same weed through another cwd: weed %q err %v; want the recorded %q", weed, err, recorded)
}
if _, err := weedNow(t, "../bin/other"); err == nil || !strings.Contains(err.Error(), "differs") {
t.Fatalf("a different executable: err %v; want a refusal", err)
}
}
func TestMiniStartTraceQuotesPathsWithSpaces(t *testing.T) {
dir := filepath.Join(t.TempDir(), "my tools")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
out := &syncBuf{}
r := &miniRun{cfg: miniConfig{Dir: dir}, out: out}
if _, err := r.start("weed", filepath.Join(dir, "absent"), []string{"mini", "-dir=" + dir}); err == nil {
t.Fatal("an absent executable started")
}
want := "+ " + shQuote(filepath.Join(dir, "absent")) + " mini " + shQuote("-dir="+dir) + "\n"
if got := out.String(); got != want || !strings.Contains(got, "'") {
t.Fatalf("start trace %q; want %q", got, want)
}
}
func TestMiniReuseIgnoresWeedFoundThroughDotInPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
bin := fakeBin(t)
cwd := t.TempDir()
if err := os.WriteFile(filepath.Join(cwd, "weed"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(cwd)
t.Setenv("PATH", ".")
for name, recorded := range map[string]string{"chunk": filepath.Join(bin, "weed"), "walstore": ""} {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
if err := writeMiniRecord(dir, miniRecord{SizeBytes: 1 << 20, NQN: "n", Bin: bin, Weed: recorded}); err != nil {
t.Fatal(err)
}
ports := freePorts(t)
l, err := net.Listen("tcp", loopback(ports.NVMe))
if err != nil {
t.Fatal(err)
}
defer l.Close()
c := miniConfig{Dir: dir, NQN: "n", SizeBytes: 1 << 20, Ports: ports, Reuse: true, Explicit: map[string]bool{}}
code, err := mini(context.Background(), c, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "in use") {
t.Fatalf("--reuse with ./weed only through . in PATH: code %d err %v; want the recorded run (then the busy port)", code, err)
}
})
}
}
// The refusal's hint is a pastable shell word: a relative PATH entry with a
// space ("my tools") prints its --weed path quoted, as mini's other printed
// commands are.
func TestMiniDotWeedHintQuotesAPathWithASpace(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix PATH lookup")
}
dir := t.TempDir()
tools := filepath.Join(dir, "my tools")
if err := os.MkdirAll(tools, 0o755); err != nil {
t.Fatal(err)
}
nl := string(rune(10))
if err := os.WriteFile(filepath.Join(tools, "weed"), []byte("#!/bin/sh"+nl+"exit 0"+nl), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
t.Setenv("PATH", "my tools")
c := miniConfig{Dir: filepath.Join(t.TempDir(), "run"), NQN: "n", SizeBytes: 1 << 20, Ports: freePorts(t)}
_, err := mini(context.Background(), c, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "pass --weed './my tools/weed' to use it") {
t.Fatalf("weed found through a relative PATH entry with a space: %v; want the quoted --weed hint", err)
}
}
+4 -5
View File
@@ -401,8 +401,8 @@ stateDiagram-v2
Drained --> Acked: revocation acknowledged with the HEAD gen
}
state "HEAD holder" as H {
[*] --> Attaching: this process took the volume lock (host lock, or a mini trial's own lock dir)
[*] --> Refused: another live process holds that volume lock
[*] --> Attaching: this process took the volume's host lock
[*] --> Refused: another live process holds the volume's host lock
Attaching --> Claiming: fresh or same-holder local root
Attaching --> Refused: existing root, HEAD published by another holder or above its durable LSN
Claiming --> Cooling: replace generation (or exclusive create), same image
@@ -423,7 +423,7 @@ stateDiagram-v2
| StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` |
| StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` |
| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent; a call that got no answer (`DeadlineExceeded`, `Unavailable`) is made again until the lease deadline, any other answer is final | `core/host/volume/workspace_lease.go` `drain`, `retryableAckError` | `INV-WS-REVOKE-ACK-001`, `INV-WS-REVOKE-ACK-RETRY-001` |
| (start) | Attaching, Refused | normal starts take the volume's host lock `/run/sw-block/locks/<volume id>.lock` before the store opens (a mini trial's blockvolume instead uses the run's `--dir/locks`, also when mini runs under systemd, since mini drops `INVOCATION_ID` from its children); held by another live process, or its directory or file cannot be created or opened, refuses (`storage.ErrWALStoreLocked`, `ErrVolumeLockDirUnavailable`) | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (from `ensureHandle`) | `INV-WS-ONE-PROCESS-PER-HOST-001` |
| (start) | Attaching, Refused | the volume's host lock `/run/sw-block/locks/<volume id>.lock` is taken before the store opens; held by another live process, or its directory or file cannot be created or opened, refuses (`storage.ErrWALStoreLocked`, `ErrVolumeLockDirUnavailable`) | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` (from `ensureHandle`) | `INV-WS-ONE-PROCESS-PER-HOST-001` |
| Attaching | Refused | a local root from another claim or behind HEAD's position (`layout.ErrStaleLocalRoot`): final typed refusal with a cure, no serving or retry | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `provider_chunk.go` `recoverChunk`, `chunkAuthorityWait` | `INV-WS-STALE-LOCAL-ROOT-001` |
| (startup) | Refused | The agreed leader lists another filer or several; or all configured masters cannot agree and confirm exactly the target within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` |
| (startup) | (startup), chunk guard on or off | on only if the filer definitely refuses the probe's mismatched chunk-condition update of a disposable HEAD; then every store the catalog opens sends the chunk condition. Any other answer leaves it off (page re-read only) and refuses nothing. sw-block metadata writers run the same probe within their --timeout | `core/frontend/chunkstore/startup_head_probe.go` `checkConditionalHead`, `probeChunkCondition`, `ProbeChunkGuard`; `cmd/sw-block/chunk_b.go` `bCatalog` | `INV-WS-CHUNK-CONDITION-PROBE-001` |
@@ -1131,7 +1131,7 @@ Notes:
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new B holder claims HEAD at its issued epoch only after the local root is validated against the HEAD it updates; an older epoch or another holder at the same epoch is refused, and guest writes stay closed until assignment and claim. | M9 Start → Claim → Serving | `core/frontend/chunkstore/layout/start.go` `Start`; `core/frontend/durable/provider_layout.go` `startLayoutRoot` | `TestStart_ValidatesAgainstTheHeadItUpdates`, `TestStart_Refusals` (`core/frontend/chunkstore/layout/start_test.go`); `TestStart_TheClaimRechecksTheSeedRule` (`core/frontend/chunkstore/layout/start_seed_test.go`); `TestFreshStoreRefusesWriteBeforeAssignmentThenPublishesAfterClaim` (`core/frontend/durable/provider_restore_schedule_test.go`) | `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-CLAIM-001` | ACTIVE |
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An old or rolled-back local root is refused by `layout.Start` before serving; synchronous and deferred attach end without retry and report the typed stale-root error and cure. A fresh root at its own epoch likewise ends with `ErrMissingLocalRoot` and its cure. | M4 Claiming → Refused | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_chunk.go` `recoverChunk`, `chunkAuthorityWait`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestFinalLayoutStartRefusalTable` (`core/frontend/durable/provider_layout_test.go`, `provider_layout_start_class_test.go`) | — | ACTIVE |
| `INV-WS-ONE-PROCESS-PER-HOST-001` | Normal starts exclude a second process from a volume's local data with a host lock until store close. Mini puts both data and lock under --dir via the hidden test-only override, refused under INVOCATION_ID. Normal/systemd starts keep host-wide exclusion. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd`, `TestNormalStartKeepsTheHostVolumeLock` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
| `INV-CHUNK-LEASE-REQUIRED-001` | Blockvolume refuses walstore-chunk startup without --workspace-lease before any host or store is opened. The refusal names concurrent acknowledging writers and acknowledged-write loss after a forced move; plain walstore startup is unchanged. | M4 startup → Refused | `cmd/blockvolume/main.go` `parseFlags` | `TestChunkVolumeRequiresWorkspaceLeaseBeforeStart` | — | ACTIVE |
| `INV-WS-CONDITIONAL-HEAD-001` | Catalog startup requires a wrong-generation conditional update of a disposable HEAD to be definitely refused and leave its bytes and generation unchanged. Unknown probe outcomes refuse admission; cleanup failures only warn with the leftover path. No volume HEAD is used. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal`, `TestConditionalHeadNextStartCleansCrashLeftovers`, `TestConditionalHeadSweepWaitsAndLeavesNewProbes`, `TestCatalogStartupDoesNotWaitForUndeletableProbe`, `TestLayoutIdentityWriterAndReaders` | — | ACTIVE |
| `INV-WS-CHUNK-CONDITION-PROBE-001` | Catalog startup and sw-block metadata writers turn the chunk guard on only if the filer definitely refuses a mismatched chunk-condition update of a disposable HEAD; any other answer leaves the page re-read as the only check. No version string is read; the startup log and /status/chunk name it. | M4 startup | `core/frontend/chunkstore/startup_head_probe.go` `probeChunkCondition`, `ProbeChunkGuard`; `catalog_b.go` `Store`, `MetadataGuard`, `Usage`; `cmd/sw-block/chunk_b.go` `bCatalog` | `TestTheStartupProbeTurnsTheChunkGuardOnOnlyForAFilerThatEnforcesIt` (`core/frontend/chunkstore/startup_chunk_condition_probe_test.go`), `TestAFailedChunkGuardProbeLeavesTheGuardOff` (`core/frontend/chunkstore/chunk_guard_report_test.go`), `TestCatalogStartupRequiresWrongGenerationHeadRefusal` (`core/frontend/chunkstore/startup_head_probe_test.go`), `TestStatusServer_StatusChunkUsage` (`core/host/volume/status_chunk_test.go`), `TestOpsChunkWritingCatalogRunsTheChunkConditionProbe`, `TestOpsChunkWritingCatalogProbeIsBoundedByTheTimeout` (`cmd/sw-block/chunk_guard_probe_test.go`) | MetaABA r2, checked outside the repository: guard on = `safe_chunks_equal`; the fallback is the re-read, which a chunk still queued for deletion defeats (`mut_reread_delayed`) | ACTIVE |
@@ -1304,7 +1304,6 @@ Notes:
| `INV-CLI-DELETE-RETRY-001` | Only the final lease barrier after a committed volume-delete reservation permits retryable true/exit 75 at its horizon. A live-holder Reserve refusal requires stopping the volume first (not_admitted, non-retryable, exit 1). No lease guard is bypassed. | M9 delete admission result projection | `cmd/sw-block/chunk_volume_delete.go` `authorityErr`; `cmd/sw-block/chunk.go` `chunkResult` | `TestVolumeDeleteAdmissionRetryAnswer`; `TestOpsChunkVolumeDeleteRefusalSaysNothingWasPersisted` | MoveAdmission.DelRead; MoveAdmission.DelMark (unchanged guards) | STUB |
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-UNSENT-REQUEST-001` | An observed operation's initial typed dial failure sends no admission and is remote_unavailable (75) through the shared classifier. A lost answer after send, or a dial failure while polling an admitted handle, retains outcome_unknown. | CLI pre-admission error projection; no server transition | `cmd/sw-block/cut_progress_poll.go` `chunkObserveHandle`; `chunkTransportFailure`, `chunkFail` | `TestPlainDetachRefusedDialIsRemoteUnavailable`, `TestPlainDetachLostAnswerAfterSendStaysUnknown`, `TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown`, `TestOpsChunk_ErrorsAreJSONOnStdout` | CutTime Poll/CliGiveUp boundary; pre-admission transport proof | ACTIVE |
| `INV-CLI-MINI-EXECUTABLE-001` | Mini records and launches the executable selected by --weed without changing symlink/.. resolution; fresh and legacy runs use an absolute path. | TrialLauncher path wiring, no protocol transition | `cmd/sw-block/mini.go` `miniExecutablePath`, `mini`, `reuseMiniRecord` | `TestMiniWeedSymlinkParentKeepsSelectedExecutable`, `TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely` (`cmd/sw-block`); `TestMiniCleanupFailStopAndSettlement` (`cmd/blockvolume`: failed-start proof rejects watchdog intervention; settled capture completes and live residue refuses cleanup) | NONE (path selection and test ownership only; fresh Linux qualification pending) | STUB |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI preserves admission evidence and definite domain/certificate answers. Possibly-sent requests require replay/poll. Incomplete verify never exits 3; non-retryable server answers never exit 75. Absent snapshot delete is snapshot_not_found. | M9 client error projection; M4 census refusal, no transition change | `core/rpc/answer` `Lookup`; `cmd/sw-block/chunk_answer.go` `chunkAnswer`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt`; `TestLinkNeverTurnsASentRequestIntoSafeResend`; `TestChunkHTTPPostLostAnswerIsUnknown`; `TestCommandFamilyTransportGrid`; `TestLocalCredentialsFailBeforeDialWithTypedPolicy`; `TestHTTPCancellationBeforeDispatchKeepsOperationPhase`; `TestDeclaredDomainCodesHaveRegistryRows`; `TestOwnedClientTransportsKeepAdmissionEvidence`; `TestPresentationFailsClosedForUnknownContract`; `TestUnsentRPCWithMixedPeerFailuresIsRetryable`; `TestRPCPeerCertificateFailureDoesNotHideHandshakeTimeout`; `TestRPCSucceedsOnGoodPeerAfterBadCertificate`; `TestPeerCertificateProofRequiresEveryFreshCompletedAttempt`; `TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification`; `TestTypedRemoteUnavailableRespectsRetryable`; `TestNonRetryableServerAnswerNeverInvitesTemporaryRetry`; `TestVerifyStartCheckLostAnswerNeverLooksLikeFindings`; `TestVerifyIncompleteTransportPreservesPartialProgress`; `TestOpsFailoverUsesSharedDefiniteExitProjection`; `TestBlobHTTPAnswerSurvivesLayoutFetch`; `TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint`; `TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST`; `TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST`; `TestHTTPOwnedTransportDoesNotInheritRegisteredDefault`; `TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure`; `TestObservedTLSForwardsPerCallAuthorityValidation`; `TestChunkCensusPreflightPreservesOpaqueContextCause`; `TestSingleFilerReviewPreservesDefiniteAndCallerWinner`; `TestReviewContextAndDefiniteAnswerPrecedence`; `TestReviewOldPickerCannotBorrowNewPeerGeneration`; `TestReviewContractProjectionAndReadOnlyRecovery`; `TestReviewAdmittedPollTLSFailureKeepsOperationRecoverable`; `TestReviewPickerCannotReplaceCustomCallerDeadline`; `TestReviewSelectedTLSCannotReplaceCallerCompletion`; `TestReviewHTTPStatusOverridesNestedTransport`; `TestReviewVerifyPreservesServerRetryRefusal`; `TestReviewInitialPostBodyFailurePreservesStatus`; `TestReviewForceMovePreservesServerPolicyExit`; `TestReviewFailoverDomainAnswerRequiresRecovery`; `TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID`; `TestSnapshotOperationCLIInterruptedTLSKeepsUnknownAndHandle`; `TestReviewCompleteBodyKeepsStatusAndAdmission`; `TestReviewInvalidAdmissionKeepsOriginalRequest`; `TestReviewUnsafeSnapshotLocationKeepsOriginalUnknown`; `TestReviewAdmittedMissingResultKeepsUnknown`; `TestCutBusyHasItsOwnLegacyExitClass`; `TestCutCLIBusyIsDistinctAndDoesNotStartAnotherCut` | SnapOps.Poll; CutTime.Poll; CutTime.CliGiveUp (result projection; no new transition) | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE |
+21 -3
View File
@@ -236,9 +236,6 @@ retains the earlier isolation guidance.
`install`, not `mv`: with SELinux, a file moved from a home directory keeps its home label and systemd may refuse
to run it.
blockvolume's volume locks are always in `/run/sw-block/locks` under the units. Only `sw-block mini`, a one-user
trial, keeps them under its own `--dir`; blockvolume refuses that override under systemd.
Do **not** enable `sw-blockvolume.service`. It is the single-volume example for the `--topology` setup, which cannot
serve a walstore-chunk volume. This manual runs each volume as the template unit `sw-blockvolume@<volume>.service`,
which `sw-block volume start` creates (section 3). `sw-blockmaster.service` is enabled in section 2.
@@ -250,6 +247,27 @@ holder is not supported. (The v1.0.2 notes' "CLI last" applied to upgrades withi
**Authentication.** For production, set up mutual TLS for the control API ([authenticate the control
API](operator-guide.md#authenticate-the-control-api)). The examples here run on loopback without it.
**Network trust.** blockmaster's control API authenticates callers with mutual TLS and authorizes them by role
(viewer, operator, admin, node) when `--tls-cert`, `--tls-key`, `--tls-client-ca`, `--role-file` and `--audit-log`
are all set. The audit log records volume create and delete, failback, workspace binding registration, placement, move and
revoke, format finalize and host retirement before they run, and refuses such a call when it cannot record it; other
calls by people are recorded after they run, as far as the log allows. Without these flags blockmaster accepts only loopback connections. Nothing else is encrypted, and only
the iSCSI target authenticates its clients:
- the volume host's status and chunk control HTTP endpoints have no authentication and listen on loopback unless
`--allow-external-status-bind` is set, which a volume host that authenticates to blockmaster (`--master-tls-cert`)
refuses;
- the replication channel between replicas (replicated volumes, preview) has no authentication;
- the connection to the SeaweedFS filer and volume servers has no authentication of its own: anyone who can reach
the filer can read or change any volume's metadata and chunks, which are stored unencrypted;
- the NVMe/TCP target has no authentication and listens on loopback unless `--allow-external-nvme-bind` is set;
- the iSCSI target listens off loopback only with `--allow-external-iscsi-bind`, which requires CHAP
(`--iscsi-chap-username`, `--iscsi-chap-secret`) for normal sessions; discovery sessions are not authenticated, so
any initiator that reaches the port can list the target name and portal; on loopback CHAP is optional; its traffic
is not encrypted.
Run these on a trusted network only, and keep blockmaster's key files, role file and audit log readable only by its
service user.
## 2. Cluster spec and blockmaster
blockmaster needs two things: a cluster spec and a lifecycle store. The cluster spec lists the nodes, and each volume
+1 -4
View File
@@ -4,10 +4,7 @@ v1.1.1 is released (2026-12-04).
v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored format.
## Known issue: `sw-block mini` as a non-root user (fixed in v1.1.2)
v1.1.2's `mini` keeps the volume lock under `--dir`, needs no `sudo` to start, prints absolute paths, and names the
`--reuse` command after a failed start. With v1.1.1:
## Known issue: `sw-block mini` as a non-root user
- `blockvolume` keeps one lock per volume under `/run/sw-block/locks`, which a non-root user cannot create. On a
fresh host `mini` starts `weed` and `blockmaster`, then stops when `blockvolume` cannot take its lock. Create the
@@ -500,9 +500,6 @@ sw-block mini --dir ./swb-mini # blockmaster and blockvolume next to sw
- If you connected v1, unmount it and run `sudo nvme disconnect -n <nqn>` **before** stopping mini. Otherwise a mounted filesystem sits on a stopped target while the kernel retries for 3 minutes. mini prints this with the connect command and again when it stops.
- The data stays in `--dir`; `sw-block mini --dir <dir> --reuse` (printed at stop, quoted for the shell) starts it again, with that run's size, ports, mode and NQN (recorded in `<dir>/mini.json`; a flag that differs is refused).
- **It is a trial setup:** one host, loopback, no authentication.
- **No root:** blockvolume's volume lock is in `<dir>/locks` (`--volume-lock-dir-test-only`, a hidden override that blockvolume refuses under systemd), so mini starts as any user without the tmpfiles.d entry. Every command it prints names sw-block and weed by their absolute paths.
- **Snapshots:** mini runs `v1` with `--chunk-snapshot-schedule off` and prints the command that takes one; the units' daily schedule is not part of a trial.
- **A failed start** stops what it started and prints the `--reuse` command that starts again on the same `--dir` (or remove the directory and start fresh).
- **Refusals:** it refuses a `--dir` that already exists, unless you pass `--reuse` to start again on it, and refuses a port that is already in use. `--port-shift N` moves every port by N, for a host where a default port is taken.
- **Size:** `--size` sets v1's size (default `256MiB`). Volumes above the release maximum are refused by blockmaster as usual.
+4 -4
View File
@@ -83,11 +83,11 @@ cmd/sw-block/main.go runOpsGenerateHelmValues context.WithTimeout 1 per-call NON
cmd/sw-block/main.go loadObservationVolume context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
cmd/sw-block/mini.go miniRun.ready time.Now().Add 1 per-call NONE: no model row maps this file yet mini cluster start wait
cmd/sw-block/mini.go miniRun.ready time.After 1 control-timer NONE: no model row maps this file yet start-wait poll
cmd/sw-block/mini.go miniRun.resolveLayoutID time.Now().Add 1 per-call NONE: no model row maps this file yet mini cluster resolve wait
cmd/sw-block/mini.go miniRun.resolveLayoutID context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
cmd/sw-block/mini.go miniRun.resolveLayoutID time.After 1 control-timer NONE: no model row maps this file yet resolve-wait poll
cmd/sw-block/mini.go miniRun.stop time.After 1 per-call NONE: no model row maps this file yet mini cluster stop wait
cmd/sw-block/mini.go mini time.After 1 control-timer NONE: no model row maps this file yet trial child-health poll
cmd/sw-block/mini.go mini time.Now().Add 1 per-call NONE: no model row maps this file yet mini cluster resolve wait
cmd/sw-block/mini.go mini context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
cmd/sw-block/mini.go mini time.After 1 control-timer NONE: no model row maps this file yet resolve-wait poll
cmd/sw-block/mini.go mini time.After 2 control-timer NONE: no model row maps this file yet resolve-wait poll
cmd/sw-block/shell.go inspectionShell.execute context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
cmd/sw-block/shell_check.go inspectionShell.check context.WithTimeout 1 per-call NONE: no model row maps this file yet one CLI request (operator --timeout)
cmd/sw-block/snapshot_operation.go chunkObserveSnapshot context.WithTimeout 1 per-call SnapOps.Send one CLI request (operator --timeout)
Can't render this file because it contains an unexpected character in line 50 and column 123.
+32 -509
View File
@@ -487,36 +487,32 @@ impl DiskLocation {
let base = volume_file_name(&self.directory, collection, vid);
let dat_path = format!("{}.dat", base);
// Custom ratio and source size come from the encode's own .vif; the
// server holds no cluster EC config in memory.
let Ok(encode_info) = ec_encode_vif(
// Custom ratio comes from the volume's own .vif; the server holds no
// cluster EC config in memory.
let data_shards = ec_data_shards_from_vif(
&self.directory,
&self.idx_directory,
&self.store_dirs,
collection,
vid,
) else {
);
if data_shards == 0 {
warn!(
volume_id = vid.0,
"sibling .vif files disagree on the encode; keeping EC shards"
);
return true;
};
let data_shards = encode_info
.as_ref()
.and_then(|vi| vi.ec_shard_config.as_ref())
.map(|c| c.data_shards as usize)
.filter(|&ds| ds > 0)
.unwrap_or(DATA_SHARDS_COUNT);
}
// On-disk .dat: an empty <= superblock one is a stub; a transient stat
// error keeps the shards rather than deleting.
let mut dat_size: i64 = -1;
let mut expected_shard_size: Option<i64> = None;
let dat_exists = match fs::metadata(&dat_path) {
Ok(meta) if meta.len() > SUPER_BLOCK_SIZE as u64 => {
dat_size = meta.len() as i64;
expected_shard_size = Some(calculate_expected_shard_size(dat_size, data_shards));
expected_shard_size = Some(calculate_expected_shard_size(
meta.len() as i64,
data_shards,
));
true
}
Ok(_) => false,
@@ -573,33 +569,6 @@ impl DiskLocation {
if shard_count == 0 {
return false;
}
// Shards that are exactly the full encode of the source size the .vif
// records, under an .ecx indexing nothing past that size, were made
// from that source. A .dat of any other size is not it (e.g. a replica
// that kept taking writes), so its size says nothing about these
// shards: keep them, and leave the .dat unloaded so it cannot collide
// with the EC volume. The .ecx check catches a re-encode interrupted
// under an earlier encode's .vif: it writes the .ecx of the grown .dat
// before the shards.
let recorded = encode_info.as_ref().map_or(0, |vi| vi.dat_file_size);
if recorded > 0
&& dat_size != recorded
&& actual_shard_size == Some(calculate_expected_shard_size(recorded, data_shards))
&& !self.ecx_indexes_past(
collection,
vid,
encode_needle_version(&encode_info),
recorded,
)
{
warn!(
volume_id = vid.0,
dat_size,
recorded,
".dat size differs from the encode source size the .vif records; keeping the EC shards and leaving the .dat in place untouched"
);
return true;
}
if let (Some(actual), Some(expected)) = (actual_shard_size, expected_shard_size)
&& actual < expected
{
@@ -614,36 +583,6 @@ impl DiskLocation {
true
}
/// Whether the .ecx the mount would open for (collection, vid) -- the data
/// dir's when non-empty, else the idx dir's -- indexes a live needle
/// ending past `size`. A missing or unreadable file reports false: a
/// doubt keeps the shards. A torn tail is what an interrupted write
/// leaves, so the whole entries before it still count. Mirrors Go's
/// ecxIndexesPast.
fn ecx_indexes_past(
&self,
collection: &str,
vid: VolumeId,
version: Version,
size: i64,
) -> bool {
let mut ecx = format!("{}.ecx", volume_file_name(&self.directory, collection, vid));
if self.idx_directory != self.directory
&& !crate::storage::erasure_coding::ec_volume::is_usable_ecx_file(&ecx)
{
ecx = format!(
"{}.ecx",
volume_file_name(&self.idx_directory, collection, vid)
);
}
crate::storage::erasure_coding::ec_decoder::ecx_needle_extent(
&ecx,
version,
&HashSet::new(),
)
.is_ok_and(|extent| extent > size)
}
/// Remove all EC-related files for a volume.
/// `pub(crate)` so the Store-level cross-disk passes in
/// `store_ec_reconcile.rs` can call it to scrub partial EC artefacts
@@ -1525,6 +1464,9 @@ fn calculate_expected_shard_size(dat_file_size: i64, data_shards: usize) -> i64
shard_size
}
/// Resolve the EC data-shard count from the volume's own `.vif` (the volume
/// server never holds the cluster EC config in memory), checking the data dir
/// then the idx dir. Falls back to the default ratio when no EC `.vif` is found.
/// Remove a file, treating a missing file as success but propagating real errors
/// (permissions, disk full). Mirrors Go's removeFileIfExists so a teardown failure
/// surfaces instead of silently leaving stale artifacts.
@@ -1535,47 +1477,26 @@ fn rm_if_present(path: String) -> io::Result<()> {
}
}
/// The needle version the encode's `.vif` records, as the mount reads it,
/// defaulting to the current version when unset. Mirrors Go's
/// encodeNeedleVersion.
fn encode_needle_version(info: &Option<VifVolumeInfo>) -> Version {
match info.as_ref().map_or(0, |vi| vi.version) {
0 => Version::current(),
v => Version(v as u8),
}
}
/// The `.vif` describing the encode of an EC volume: the first with an EC
/// shard config in the data dir, the idx dir, then the sibling data dir the
/// mount takes it from under a shared idx dir. Without one it falls back to
/// the first `.vif` found in the data or idx dir. Err when sibling `.vif`
/// files disagree on the run. Mirrors Go's ecEncodeVolumeInfo.
fn ec_encode_vif(
fn ec_data_shards_from_vif(
directory: &str,
idx_directory: &str,
store_dirs: &[String],
collection: &str,
vid: VolumeId,
) -> Result<Option<VifVolumeInfo>, ()> {
let has_ec_config = |vi: &VifVolumeInfo| {
vi.ec_shard_config
.as_ref()
.is_some_and(|c| c.data_shards > 0)
};
let mut fallback: Option<VifVolumeInfo> = None;
) -> usize {
for dir in [directory, idx_directory] {
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
if let Some(vi) = fs::read_to_string(&vif)
if let Some(ds) = fs::read_to_string(&vif)
.ok()
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
.and_then(|vi| vi.ec_shard_config)
.map(|c| c.data_shards as usize)
&& ds > 0
{
if has_ec_config(&vi) {
return Ok(Some(vi));
}
fallback.get_or_insert(vi);
return ds;
}
if directory == idx_directory {
return Ok(fallback);
break;
}
}
match crate::storage::erasure_coding::ec_volume::sibling_ec_config_vif(
@@ -1584,10 +1505,18 @@ fn ec_encode_vif(
store_dirs,
collection,
vid,
)? {
Some(vi) if has_ec_config(&vi) => Ok(Some(vi)),
_ => Ok(fallback),
) {
Err(()) => return 0,
Ok(Some(vi)) => {
if let Some(ds) = vi.ec_shard_config.map(|c| c.data_shards as usize)
&& ds > 0
{
return ds;
}
}
Ok(None) => {}
}
DATA_SHARDS_COUNT
}
/// Parse a volume filename like "collection_42.dat" or "42.dat" into (collection, VolumeId).
@@ -1949,412 +1878,6 @@ mod tests {
);
}
fn write_ec_vif(base: &str, dat_file_size: i64) {
let vif = VifVolumeInfo {
version: 3,
dat_file_size,
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
..Default::default()
}),
..Default::default()
};
fs::write(
format!("{}.vif", base),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
}
fn write_sized(path: &str, size: i64) {
fs::File::create(path)
.unwrap()
.set_len(size as u64)
.unwrap();
}
// An .ecx with one live needle ending at `end` in a current-version .dat.
fn write_ecx_ending_at(base: &str, end: i64) {
write_ecx_ending_at_version(base, end, Version::current());
}
fn write_ecx_ending_at_version(base: &str, end: i64, version: Version) {
let size = Size(1000);
let offset = end - crate::storage::needle::needle::get_actual_size(size, version);
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_entry_to_bytes(
&mut entry,
NeedleId(1),
Offset::from_actual_offset(offset),
size,
);
fs::write(format!("{}.ecx", base), entry).unwrap();
}
// A .dat of `size` whose superblock names the current needle version.
fn write_sized_dat(path: &str, size: i64) {
use std::io::Write;
let mut f = fs::File::create(path).unwrap();
f.write_all(&[Version::current().0]).unwrap();
f.set_len(size as u64).unwrap();
}
fn test_location(dir: &str) -> DiskLocation {
DiskLocation::new(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap()
}
// A .dat larger than the source the .vif records sits beside a full-size
// shard of that encode: it is not the shards' source, so the shards stay,
// the .dat is not loaded, and nothing on disk is touched.
#[test]
fn test_load_existing_foreign_dat_beside_ec_shards_keeps_both() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let vid = VolumeId(74);
{
let mut loc = test_location(dir);
loc.create_volume(vid, NeedleMapKind::InMemory, &VolumeSpec::default())
.unwrap();
loc.close();
}
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&base, source_size);
let shard_size = calculate_expected_shard_size(source_size, ds);
write_sized(&format!("{}.ec09", base), shard_size);
// The .ecx indexes a needle ending exactly at the source size.
write_ecx_ending_at(&base, source_size);
write_sized(&format!("{}.ecj", base), 0);
// Grown past the source by later writes: its full encode would be
// larger than the shard, which used to read as an interrupted encode.
let foreign_size = source_size + 10 * 1024 * 1024;
assert!(calculate_expected_shard_size(foreign_size, ds) > shard_size);
fs::OpenOptions::new()
.write(true)
.open(format!("{}.dat", base))
.unwrap()
.set_len(foreign_size as u64)
.unwrap();
let exts = [".dat", ".idx", ".vif", ".ecx", ".ecj", ".ec09"];
let sizes: Vec<u64> = exts
.iter()
.map(|e| fs::metadata(format!("{}{}", base, e)).unwrap().len())
.collect();
let vif_before = fs::read(format!("{}.vif", base)).unwrap();
let mut loc = test_location(dir);
assert!(
loc.validate_ec_volume("", vid),
"shards whose .vif names a different source size than the .dat must be kept",
);
loc.load_existing_volumes(NeedleMapKind::InMemory).unwrap();
assert!(
loc.find_volume(vid).is_none(),
"a .dat that is not the encode source was loaded beside its EC shards",
);
for (e, size) in exts.iter().zip(sizes) {
let meta = fs::metadata(format!("{}{}", base, e))
.unwrap_or_else(|err| panic!("{} is gone: {}", e, err));
assert_eq!(meta.len(), size, "{} size changed", e);
}
assert_eq!(fs::read(format!("{}.vif", base)).unwrap(), vif_before);
}
// The .dat matches the recorded source size and the shards are short of its
// full encode: an interrupted local encode, still reclaimed.
#[test]
fn test_validate_ec_volume_interrupted_encode_with_recorded_size_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(75));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let dat_size = 30 * 1024 * 1024i64;
write_sized(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, dat_size);
let partial = calculate_expected_shard_size(dat_size, ds) / 3;
for i in 0..total {
write_sized(&format!("{}.ec{:02}", base, i), partial);
}
assert!(
!loc.validate_ec_volume("", VolumeId(75)),
"partial shards beside the recorded source .dat should be reclaimable",
);
}
// The .vif is written after the shards, so an interrupted re-encode of a
// volume that was once EC-decoded still has the old encode's .vif. Shards
// that are not that encode's full size are not described by it: reclaim.
#[test]
fn test_validate_ec_volume_interrupted_re_encode_with_stale_vif_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(76));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
let partial = calculate_expected_shard_size(dat_size, ds) / 2;
assert_ne!(partial, calculate_expected_shard_size(old_source_size, ds));
for i in 0..total {
write_sized(&format!("{}.ec{:02}", base, i), partial);
}
assert!(
!loc.validate_ec_volume("", VolumeId(76)),
"partial shards of an interrupted re-encode must not be kept for a stale .vif",
);
}
// Under a shared -dir.idx the encode's .vif can sit on a sibling data
// disk, where the mount also takes it from. The recorded source size must
// be read from there too, or the shards fall back to the .dat size check.
#[test]
fn test_validate_ec_volume_foreign_dat_keeps_shards_with_sibling_vif() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_str().unwrap();
let (data_a, data_b, idx) = (
format!("{root}/a"),
format!("{root}/b"),
format!("{root}/idx"),
);
for d in [&data_a, &data_b, &idx] {
fs::create_dir_all(d).unwrap();
}
let mut loc = DiskLocation::new(
&data_a,
&idx,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
loc.store_dirs = vec![data_a.clone(), data_b.clone()];
let vid = VolumeId(78);
let base_a = volume_file_name(&data_a, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&volume_file_name(&data_b, "", vid), source_size);
write_sized(&format!("{}.ecx", volume_file_name(&idx, "", vid)), 0);
write_sized(
&format!("{}.ec09", base_a),
calculate_expected_shard_size(source_size, ds),
);
write_sized(&format!("{}.dat", base_a), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"the sibling .vif's source size was ignored and the shards would be deleted",
);
}
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
// with every partial shard exactly as long as that earlier encode's full
// shards. The re-encode wrote the .ecx of the grown .dat first, so it
// indexes needles past the recorded size: the shards are not that
// encode's, and the complete .dat is reclaimed.
#[test]
fn test_validate_ec_volume_interrupted_re_encode_matching_stale_length_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(79);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized_dat(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
write_ecx_ending_at(&base, dat_size);
for i in 0..total {
write_sized(
&format!("{}.ec{:02}", base, i),
calculate_expected_shard_size(old_source_size, ds),
);
}
assert!(
!loc.validate_ec_volume("", vid),
"a stale .vif was trusted for partial shards under an .ecx of the grown .dat",
);
// The same shards under an .ecx that stays within the recorded size
// are that encode's: keep them.
write_ecx_ending_at(&base, old_source_size);
assert!(
loc.validate_ec_volume("", vid),
"shards whose .ecx and length match the recorded source must be kept",
);
}
// Only the .ecx the mount opens speaks for the shards: a non-empty
// data-dir .ecx within the recorded size wins over an older shared-idx
// .ecx pointing past it, and the shards stay.
#[test]
fn test_validate_ec_volume_checks_the_ecx_the_mount_opens() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_str().unwrap();
let (data, idx) = (format!("{root}/data"), format!("{root}/idx"));
for d in [&data, &idx] {
fs::create_dir_all(d).unwrap();
}
let loc = DiskLocation::new(
&data,
&idx,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
let vid = VolumeId(80);
let base = volume_file_name(&data, "", vid);
let idx_base = volume_file_name(&idx, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&base, source_size);
write_ecx_ending_at(&base, source_size);
write_ecx_ending_at(&idx_base, source_size + 20 * 1024 * 1024);
write_sized(
&format!("{}.ec09", base),
calculate_expected_shard_size(source_size, ds),
);
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"an .ecx the mount ignores decided against the shards",
);
// With no data-dir .ecx the mount opens the shared one, which indexes
// past the recorded size: the old rule applies and reclaims.
fs::remove_file(format!("{}.ecx", base)).unwrap();
assert!(
!loc.validate_ec_volume("", vid),
"the shared .ecx the mount opens was not checked",
);
}
// The .ecx extent is sized with the needle version the encode's .vif
// records, as the mount reads it, not the version of the foreign .dat.
#[test]
fn test_validate_ec_volume_sizes_the_ecx_with_the_encode_version() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(81);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
let vif = VifVolumeInfo {
version: 2,
dat_file_size: source_size,
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
..Default::default()
}),
..Default::default()
};
fs::write(
format!("{}.vif", base),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
// Ends exactly at the source under version 2; version 3 would put it
// 8 bytes past.
write_ecx_ending_at_version(&base, source_size, Version(2));
write_sized(
&format!("{}.ec09", base),
calculate_expected_shard_size(source_size, ds),
);
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"the .ecx was sized with the foreign .dat's needle version, not the encode's",
);
}
// An interrupted write leaves a torn .ecx tail; the whole entries before
// it still show the re-encode's .ecx indexing past the stale recorded size.
#[test]
fn test_validate_ec_volume_torn_ecx_tail_still_reclaims_re_encode() {
use std::io::Write;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(82);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized_dat(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
write_ecx_ending_at(&base, dat_size);
fs::OpenOptions::new()
.append(true)
.open(format!("{}.ecx", base))
.unwrap()
.write_all(&[1, 2, 3])
.unwrap();
for i in 0..total {
write_sized(
&format!("{}.ec{:02}", base, i),
calculate_expected_shard_size(old_source_size, ds),
);
}
assert!(
!loc.validate_ec_volume("", vid),
"a torn .ecx tail hid the entries past the stale recorded size",
);
}
// A .vif without a recorded source size keeps the old size check against
// the .dat, in both directions.
#[test]
fn test_validate_ec_volume_no_recorded_size_keeps_old_rule() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(77));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
write_ec_vif(&base, 0);
write_sized(
&format!("{}.ec00", base),
calculate_expected_shard_size(30 * 1024 * 1024, ds),
);
write_sized(&format!("{}.dat", base), 40 * 1024 * 1024);
assert!(
!loc.validate_ec_volume("", VolumeId(77)),
"without a recorded size, shards smaller than the .dat's full encode should be reclaimable",
);
write_sized(&format!("{}.dat", base), 30 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", VolumeId(77)),
"without a recorded size, shards matching the .dat's full encode must be kept",
);
}
// The per-disk generation reader behind the fenced EC teardown: a present .vif
// yields its generation (or 0 with no EC config), a missing .vif is unreadable
// (preserved, fail-safe), and the idx dir is a fallback for the split-disk layout.
@@ -48,30 +48,28 @@ pub fn find_dat_file_size_with_dirs(
ec00.read_exact(&mut sb_buf)?;
let version = Version(sb_buf[0]);
// At least the superblock size
let extent = ecx_needle_extent(&format!("{}.ecx", ecx_base), version, deleted)?;
Ok(extent.max(SUPER_BLOCK_SIZE as i64))
}
// Start with at least the superblock size
let mut dat_size: i64 = SUPER_BLOCK_SIZE as i64;
/// Where the furthest live needle indexed by the `.ecx` at `ecx_path` ends in
/// the source `.dat`, or 0 when it indexes none. Needles in `deleted` count as
/// deleted. Mirrors Go's EcxNeedleExtent.
pub fn ecx_needle_extent(
ecx_path: &str,
version: Version,
deleted: &HashSet<NeedleId>,
) -> io::Result<i64> {
let ecx_data = std::fs::read(ecx_path)?;
let (entries, _) = ecx_data.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>();
let mut extent = 0i64;
for entry in entries {
let (key, offset, size) = idx_entry_from_bytes(entry);
// Scan .ecx entries
let ecx_path = format!("{}.ecx", ecx_base);
let ecx_data = std::fs::read(&ecx_path)?;
let entry_count = ecx_data.len() / NEEDLE_MAP_ENTRY_SIZE;
for i in 0..entry_count {
let start = i * NEEDLE_MAP_ENTRY_SIZE;
let (key, offset, size) =
idx_entry_from_bytes(&ecx_data[start..start + NEEDLE_MAP_ENTRY_SIZE]);
if size.is_deleted() || deleted.contains(&key) {
continue;
}
extent = extent.max(offset.to_actual_offset() + get_actual_size(size, version));
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
if entry_stop > dat_size {
dat_size = entry_stop;
}
}
Ok(extent)
Ok(dat_size)
}
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
+40 -82
View File
@@ -1,9 +1,7 @@
package storage
import (
"errors"
"fmt"
"io"
"os"
"path"
"regexp"
@@ -14,7 +12,6 @@ import (
"slices"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
@@ -660,27 +657,22 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
datFileName := baseFileName + ".dat"
// Custom ratio and source size come from the encode's own .vif; the
// server holds no cluster EC config in memory.
encodeInfo, ambiguous := l.ecEncodeVolumeInfo(collection, vid)
if ambiguous {
// Custom ratio comes from the volume's own .vif; the server holds no
// cluster EC config in memory.
dataShards := l.ecDataShardsFromVif(collection, vid)
if dataShards == 0 {
glog.Warningf("EC volume %d: sibling .vif files disagree on the encode; keeping EC shards", vid)
return true
}
dataShards := erasure_coding.DataShardsCount
if ds := encodeInfo.GetEcShardConfig().GetDataShards(); ds > 0 {
dataShards = int(ds)
}
// On-disk .dat size, or -1 when absent (an empty <= superblock .dat is a
// stub). A transient stat error keeps the shards rather than deleting.
var datSize, expectedShardSize int64 = -1, -1
var expectedShardSize int64 = -1
datExists := false
if datFileInfo, err := os.Stat(datFileName); err == nil {
if datFileInfo.Size() > int64(super_block.SuperBlockSize) {
datExists = true
datSize = datFileInfo.Size()
expectedShardSize = calculateExpectedShardSize(datSize, dataShards)
expectedShardSize = calculateExpectedShardSize(datFileInfo.Size(), dataShards)
}
} else if !os.IsNotExist(err) {
glog.Warningf("EC volume %d: cannot stat .dat %s (%v); keeping EC shards", vid, datFileName, err)
@@ -720,20 +712,6 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
if shardCount == 0 {
return false
}
// Shards that are exactly the full encode of the source size the .vif
// records, under an .ecx indexing nothing past that size, were made from
// that source. A .dat of any other size is not it (e.g. a replica that
// kept taking writes), so its size says nothing about these shards: keep
// them, and leave the .dat unloaded so it cannot collide with the EC
// volume. The .ecx check catches a re-encode interrupted under an earlier
// encode's .vif: it writes the .ecx of the grown .dat before the shards.
if recorded := encodeInfo.GetDatFileSize(); recorded > 0 && datSize != recorded &&
actualShardSize == calculateExpectedShardSize(recorded, dataShards) &&
!l.ecxIndexesPast(collection, vid, encodeNeedleVersion(encodeInfo), recorded) {
glog.Warningf("EC volume %d: .dat is %d bytes but the .vif records an encode source of %d bytes; keeping the EC shards and leaving the .dat in place untouched",
vid, datSize, recorded)
return true
}
if expectedShardSize > 0 && actualShardSize > 0 && actualShardSize < expectedShardSize {
glog.Warningf("EC volume %d: %d shards of %d bytes are smaller than the .dat's full encode (%d bytes); reclaiming the complete .dat",
vid, shardCount, actualShardSize, expectedShardSize)
@@ -742,72 +720,52 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
return true
}
// ecxIndexesPast reports whether the .ecx the mount would open for
// (collection, vid) -- the data dir's when non-empty, else the idx dir's --
// indexes a live needle ending past size. A missing or unreadable file
// reports false: a doubt keeps the shards. A torn tail is what an
// interrupted write leaves, so the whole entries before it still count.
func (l *DiskLocation) ecxIndexesPast(collection string, vid needle.VolumeId, version needle.Version, size int64) bool {
ecxBase := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
if fi, err := os.Stat(ecxBase + ".ecx"); (err != nil || fi.Size() == 0) && l.IdxDirectory != l.Directory {
ecxBase = erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid))
}
extent, err := erasure_coding.EcxNeedleExtent(ecxBase, version)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return false
}
return extent > size
}
// encodeNeedleVersion is the needle version the encode's .vif records, as the
// mount reads it, defaulting to the current version when unset.
func encodeNeedleVersion(info *volume_server_pb.VolumeInfo) needle.Version {
if v := info.GetVersion(); v > 0 {
return needle.Version(v)
}
return needle.GetCurrentVersion()
}
// ecEncodeVolumeInfo returns the .vif describing the encode of an EC volume:
// the first with an EC shard config in the data dir, the idx dir, then the
// sibling data dir the mount takes it from under a shared idx dir. Without
// one it falls back to the first .vif found in the data or idx dir, which
// may be nil. ambiguous is set when sibling .vif files disagree on the run.
func (l *DiskLocation) ecEncodeVolumeInfo(collection string, vid needle.VolumeId) (info *volume_server_pb.VolumeInfo, ambiguous bool) {
var fallback *volume_server_pb.VolumeInfo
load := func(vifName string) *volume_server_pb.VolumeInfo {
vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName)
if !found {
return nil
}
if fallback == nil {
fallback = vi
}
if vi.GetEcShardConfig().GetDataShards() > 0 {
return vi
}
return nil
}
// ecDataShardsFromVif resolves the data-shard count for an EC volume from
// its own .vif (EcShardConfig), checking the data dir, the idx dir, then the
// sibling data dir the mount takes the .vif from under a shared idx dir. The
// .vif is the source of truth for custom ratios on the volume server, which
// never holds the cluster EC config in memory. Falls back to the default
// ratio when the .vif carries no EC shard config.
func (l *DiskLocation) ecDataShardsFromVif(collection string, vid needle.VolumeId) int {
// At most two dirs to check; avoid slice/map allocations on this
// per-volume startup path.
if l.Directory != "" {
if vi := load(erasure_coding.EcShardFileName(collection, l.Directory, int(vid)) + ".vif"); vi != nil {
return vi, false
if ds := ecDataShardsFromVifDir(collection, l.Directory, vid); ds > 0 {
return ds
}
}
if l.IdxDirectory != "" && l.IdxDirectory != l.Directory {
if vi := load(erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid)) + ".vif"); vi != nil {
return vi, false
if ds := ecDataShardsFromVifDir(collection, l.IdxDirectory, vid); ds > 0 {
return ds
}
vif, ambiguous := erasure_coding.SiblingEcConfigVif(collection, vid, l.Directory, l.IdxDirectory, l.storeDirs)
if ambiguous {
return nil, true
return 0
}
if vif != "" {
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vif); found && vi.GetEcShardConfig().GetDataShards() > 0 {
return vi, false
if ds := ecDataShardsFromVifPath(vif); ds > 0 {
return ds
}
}
}
return fallback, false
return erasure_coding.DataShardsCount
}
// ecDataShardsFromVifDir returns the .vif EcShardConfig data-shard count for
// (collection, vid) under dir, or 0 when absent / not custom.
func ecDataShardsFromVifDir(collection, dir string, vid needle.VolumeId) int {
return ecDataShardsFromVifPath(erasure_coding.EcShardFileName(collection, dir, int(vid)) + ".vif")
}
// ecDataShardsFromVifPath returns the EcShardConfig data-shard count recorded
// in one .vif, or 0 when absent / not custom.
func ecDataShardsFromVifPath(vifName string) int {
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName); found && vi.EcShardConfig != nil {
if ds := int(vi.EcShardConfig.DataShards); ds > 0 {
return ds
}
}
return 0
}
// removeEcVolumeFiles removes all EC-related files for a volume
@@ -5,13 +5,8 @@ import (
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
)
func writeSizedFile(t *testing.T, path string, size int64) {
@@ -106,331 +101,3 @@ func TestValidateEcVolume_TransientStatErrorKeeps(t *testing.T) {
t.Fatal("validateEcVolume returned delete on a transient stat error; must keep on ambiguity")
}
}
func writeEcVif(t *testing.T, base string, datFileSize int64) {
t.Helper()
vi := &volume_server_pb.VolumeInfo{
Version: uint32(needle.GetCurrentVersion()),
DatFileSize: datFileSize,
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: uint32(erasure_coding.DataShardsCount),
ParityShards: uint32(erasure_coding.ParityShardsCount),
},
}
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
t.Fatalf("save .vif: %v", err)
}
}
// A .dat larger than the source the .vif records sits beside a full-size
// shard of that encode: it is not the shards' source, so the shards stay, the
// .dat is not loaded, and nothing on disk is touched.
func TestLoadExistingVolume_ForeignDatBesideEcShardsKeepsBoth(t *testing.T) {
store := newTestStore(t, 1)
l := store.Locations[0]
const vid = needle.VolumeId(74)
mountTestVolume(t, l, vid, "")
l.UnloadVolume(vid)
base := erasure_coding.EcShardFileName("", l.Directory, int(vid))
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, base, sourceSize)
shardSize := calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount)
writeSizedFile(t, base+erasure_coding.ToExt(9), shardSize)
// The .ecx indexes a needle ending exactly at the source size.
writeEcxEndingAt(t, base, sourceSize)
writeSizedFile(t, base+".ecj", 0)
// Grown past the source by later writes: its full encode would be larger
// than the shard, which used to read as an interrupted local encode.
foreignSize := sourceSize + 10*1024*1024
if calculateExpectedShardSize(foreignSize, erasure_coding.DataShardsCount) <= shardSize {
t.Fatal("test setup: the foreign .dat must encode to larger shards")
}
if err := os.Truncate(base+".dat", foreignSize); err != nil {
t.Fatal(err)
}
want := map[string]int64{}
for _, ext := range []string{".dat", ".idx", ".vif", ".ecx", ".ecj", erasure_coding.ToExt(9)} {
fi, err := os.Stat(base + ext)
if err != nil {
t.Fatalf("stat %s: %v", ext, err)
}
want[ext] = fi.Size()
}
vifBefore, err := os.ReadFile(base + ".vif")
if err != nil {
t.Fatal(err)
}
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume would delete shards whose .vif names a different source size than the .dat beside them")
}
l.loadExistingVolume(filepath.Base(base)+".idx", NeedleMapInMemory, true, 0, 0, false)
if _, found := l.FindVolume(vid); found {
t.Fatal("a .dat that is not the encode source was loaded beside its EC shards")
}
for ext, size := range want {
fi, err := os.Stat(base + ext)
if err != nil {
t.Fatalf("%s is gone: %v", ext, err)
}
if fi.Size() != size {
t.Fatalf("%s size changed: %d -> %d", ext, size, fi.Size())
}
}
if vifAfter, _ := os.ReadFile(base + ".vif"); string(vifAfter) != string(vifBefore) {
t.Fatal(".vif was rewritten")
}
}
// The .dat matches the recorded source size and the shards are short of its
// full encode: an interrupted local encode, still reclaimed.
func TestValidateEcVolume_InterruptedEncodeWithRecordedSizeReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 75)
datSize := int64(30 * 1024 * 1024)
writeSizedFile(t, base+".dat", datSize)
writeEcVif(t, base, datSize)
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 3
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
}
if l.validateEcVolume("", 75) {
t.Fatal("validateEcVolume kept partial shards beside the recorded source .dat")
}
}
// The .vif is written after the shards, so an interrupted re-encode of a
// volume that was once EC-decoded still has the old encode's .vif. Shards that
// are not that encode's full size are not described by it: reclaim as before.
func TestValidateEcVolume_InterruptedReEncodeWithStaleVifReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 76)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedFile(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 2
if partialShardSize == calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount) {
t.Fatal("test setup: partial shards must not match the stale encode's size")
}
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
}
if l.validateEcVolume("", 76) {
t.Fatal("validateEcVolume kept partial shards of an interrupted re-encode because of a stale .vif")
}
}
// A .vif without a recorded source size keeps the old size check against the
// .dat, in both directions.
func TestValidateEcVolume_NoRecordedSizeKeepsOldRule(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 77)
shardSize := calculateExpectedShardSize(30*1024*1024, erasure_coding.DataShardsCount)
writeEcVif(t, base, 0)
writeSizedFile(t, base+erasure_coding.ToExt(0), shardSize)
writeSizedFile(t, base+".dat", 40*1024*1024)
if l.validateEcVolume("", 77) {
t.Fatal("without a recorded size, shards smaller than the .dat's full encode should be reclaimable")
}
writeSizedFile(t, base+".dat", 30*1024*1024)
if !l.validateEcVolume("", 77) {
t.Fatal("without a recorded size, shards matching the .dat's full encode must be kept")
}
}
// Under a shared -dir.idx the encode's .vif can sit on a sibling data disk,
// where the mount also takes it from. The recorded source size must be read
// from there too, or the shards fall back to the .dat size check and go.
func TestValidateEcVolume_ForeignDatKeepsShardsWithSiblingVif(t *testing.T) {
root := t.TempDir()
dataA, dataB, idx := filepath.Join(root, "a"), filepath.Join(root, "b"), filepath.Join(root, "idx")
for _, d := range []string{dataA, dataB, idx} {
if err := os.Mkdir(d, 0o755); err != nil {
t.Fatal(err)
}
}
l := newTestDiskLocation(dataA)
l.IdxDirectory = idx
l.storeDirs = []string{dataA, dataB}
const vid = 78
baseA := erasure_coding.EcShardFileName("", dataA, vid)
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, erasure_coding.EcShardFileName("", dataB, vid), sourceSize)
writeSizedFile(t, erasure_coding.EcShardFileName("", idx, vid)+".ecx", 0)
writeSizedFile(t, baseA+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedFile(t, baseA+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume ignored the sibling .vif's source size and would delete the shards")
}
}
// writeEcxEndingAt writes an .ecx with one live needle ending at end in a
// current-version .dat.
func writeEcxEndingAt(t *testing.T, base string, end int64) {
t.Helper()
writeEcxEndingAtVersion(t, base, end, needle.GetCurrentVersion())
}
func writeEcxEndingAtVersion(t *testing.T, base string, end int64, version needle.Version) {
t.Helper()
size := types.Size(1000)
offset := end - needle.GetActualSize(size, version)
entry := needle_map.ToBytes(1, types.ToOffset(offset), size)
if err := os.WriteFile(base+".ecx", entry, 0o644); err != nil {
t.Fatalf("write .ecx: %v", err)
}
}
// writeSizedDat writes a .dat of size whose superblock names the current
// needle version.
func writeSizedDat(t *testing.T, path string, size int64) {
t.Helper()
writeSizedFile(t, path, size)
f, err := os.OpenFile(path, os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteAt([]byte{byte(needle.GetCurrentVersion())}, 0); err != nil {
t.Fatal(err)
}
}
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
// with every partial shard exactly as long as that earlier encode's full
// shards. The re-encode wrote the .ecx of the grown .dat first, so it indexes
// needles past the recorded size: the shards are not that encode's, and the
// complete .dat is reclaimed.
func TestValidateEcVolume_InterruptedReEncodeMatchingStaleLengthReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 79
base := erasure_coding.EcShardFileName("", l.Directory, vid)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedDat(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
writeEcxEndingAt(t, base, datSize)
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
}
if l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume trusted a stale .vif for partial shards under an .ecx of the grown .dat")
}
// The same shards under an .ecx that stays within the recorded size are
// that encode's: keep them.
writeEcxEndingAt(t, base, oldSourceSize)
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume dropped shards whose .ecx and length match the recorded source")
}
}
// Only the .ecx the mount opens speaks for the shards: a non-empty data-dir
// .ecx within the recorded size wins over an older shared-idx .ecx pointing
// past it, and the shards stay.
func TestValidateEcVolume_ChecksTheEcxTheMountOpens(t *testing.T) {
root := t.TempDir()
data, idx := filepath.Join(root, "data"), filepath.Join(root, "idx")
for _, d := range []string{data, idx} {
if err := os.Mkdir(d, 0o755); err != nil {
t.Fatal(err)
}
}
l := newTestDiskLocation(data)
l.IdxDirectory = idx
const vid = 80
base := erasure_coding.EcShardFileName("", data, vid)
idxBase := erasure_coding.EcShardFileName("", idx, vid)
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, base, sourceSize)
writeEcxEndingAt(t, base, sourceSize)
writeEcxEndingAt(t, idxBase, sourceSize+20*1024*1024)
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("an .ecx the mount ignores decided against the shards")
}
// With no data-dir .ecx the mount opens the shared one, which indexes
// past the recorded size: the old rule applies and reclaims.
if err := os.Remove(base + ".ecx"); err != nil {
t.Fatal(err)
}
if l.validateEcVolume("", vid) {
t.Fatal("the shared .ecx the mount opens was not checked")
}
}
// The .ecx extent is sized with the needle version the encode's .vif records,
// as the mount reads it, not the version of the foreign .dat beside it.
func TestValidateEcVolume_SizesTheEcxWithTheEncodeVersion(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 81
base := erasure_coding.EcShardFileName("", l.Directory, vid)
sourceSize := int64(30 * 1024 * 1024)
vi := &volume_server_pb.VolumeInfo{
Version: uint32(needle.Version2),
DatFileSize: sourceSize,
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: uint32(erasure_coding.DataShardsCount),
ParityShards: uint32(erasure_coding.ParityShardsCount),
},
}
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
t.Fatal(err)
}
// Ends exactly at the source under version 2; version 3 would put it
// 8 bytes past.
writeEcxEndingAtVersion(t, base, sourceSize, needle.Version2)
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("the .ecx was sized with the foreign .dat's needle version, not the encode's")
}
}
// An interrupted write leaves a torn .ecx tail; the whole entries before it
// still show the re-encode's .ecx indexing past the stale recorded size.
func TestValidateEcVolume_TornEcxTailStillReclaimsReEncode(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 82
base := erasure_coding.EcShardFileName("", l.Directory, vid)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedDat(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
writeEcxEndingAt(t, base, datSize)
f, err := os.OpenFile(base+".ecx", os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write([]byte{1, 2, 3}); err != nil {
t.Fatal(err)
}
f.Close()
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
}
if l.validateEcVolume("", vid) {
t.Fatal("a torn .ecx tail hid the entries past the stale recorded size")
}
}
+7 -12
View File
@@ -109,25 +109,20 @@ func FindDatFileSize(shard0FileName, indexBaseFileName string) (datSize int64, e
// when all needles are deleted (see issue #7748).
datSize = int64(super_block.SuperBlockSize)
extent, err := EcxNeedleExtent(indexBaseFileName, version)
if extent > datSize {
datSize = extent
}
return
}
// EcxNeedleExtent returns where the furthest live needle indexed by
// indexBaseFileName.ecx ends in the source .dat, or 0 when it indexes none.
func EcxNeedleExtent(indexBaseFileName string, version needle.Version) (extent int64, err error) {
err = iterateEcxFile(indexBaseFileName, func(key types.NeedleId, offset types.Offset, size types.Size) error {
if size.IsDeleted() {
return nil
}
if end := offset.ToActualOffset() + needle.GetActualSize(size, version); end > extent {
extent = end
entryStopOffset := offset.ToActualOffset() + needle.GetActualSize(size, version)
if datSize < entryStopOffset {
datSize = entryStopOffset
}
return nil
})
return
}