diff --git a/seaweed-block/cmd/blockvolume/head_size_integration_test.go b/seaweed-block/cmd/blockvolume/head_size_integration_test.go index 0fb5d2fa14..8ebd6ecd7a 100644 --- a/seaweed-block/cmd/blockvolume/head_size_integration_test.go +++ b/seaweed-block/cmd/blockvolume/head_size_integration_test.go @@ -270,7 +270,7 @@ func headSzLoopbackAddr(t *testing.T) string { for i := 0; i < 500; i++ { lo, hi := testPortSpan(10000, 20000) p := lo + rand.Intn(hi-lo) - if handoffPorts.used[p] { + if handoffPorts.used[p] || !claimHostPort(p) { continue } addr := fmt.Sprintf("127.0.0.1:%d", p) diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index ecb21f52c9..e1c6614ed2 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -520,7 +520,7 @@ func handoffAddress(t *testing.T) string { for i := 0; i < 500; i++ { lo, hi := testPortSpan(10000, 20000) p := lo + rand.Intn(hi-lo) - if handoffPorts.used[p] { + if handoffPorts.used[p] || !claimHostPort(p) { continue } addr := fmt.Sprintf("%s:%d", testListenHost(), p) @@ -646,6 +646,19 @@ func (d *daemon) line(s string) string { func (d *daemon) has(s string) bool { return d.line(s) != "" } +// tail is the last n lines of the child's log, for a failure report. +func (d *daemon) tail(n int) string { + b, err := os.ReadFile(d.log) + if err != nil { + return "(log unreadable: " + err.Error() + ")" + } + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + if len(lines) > n { + lines = lines[len(lines)-n:] + } + return strings.Join(lines, "\n") +} + // waitLog waits for a log line containing s and returns it. A child that // exits first fails the test at once. func (d *daemon) waitLog(t *testing.T, timeout time.Duration, s string) string { @@ -660,11 +673,11 @@ func (d *daemon) waitLog(t *testing.T, timeout time.Duration, s string) string { if l := d.line(s); l != "" { return l } - t.Fatalf("%s exited (%v) before logging %q", d.name, d.err, s) + t.Fatalf("%s exited (%v) before logging %q; its log ends:\n%s", d.name, d.err, s, d.tail(40)) default: } if time.Now().After(end) { - t.Fatalf("%s did not log %q within %s", d.name, s, timeout) + t.Fatalf("%s did not log %q within %s; its log ends:\n%s", d.name, s, timeout, d.tail(40)) } time.Sleep(100 * time.Millisecond) } diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go new file mode 100644 index 0000000000..dbc6922137 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_other_test.go @@ -0,0 +1,7 @@ +//go:build !unix + +package main_test + +// claimHostPort: the process-level tests run on Linux only; elsewhere every +// port is this process's to probe. +func claimHostPort(p int) bool { return true } diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_test.go new file mode 100644 index 0000000000..8d2e1c93e1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_test.go @@ -0,0 +1,144 @@ +//go:build unix + +package main_test + +import ( + "bufio" + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "testing" + "time" +) + +// claimChild runs this test binary again as a claim helper: mode "hold" +// claims the port, prints "held" (or "refused"), and keeps the claim until +// its stdin closes; mode "try" claims and exits 0 (taken) or 3 (refused). +// The parent never claims, so its own claim map stays empty across -count. +const claimChildEnv = "SWBLOCK_TEST_PORT_CLAIM_CHILD" + +func TestMain(m *testing.M) { + if mode := os.Getenv(claimChildEnv); mode != "" { + p, _ := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_CLAIM_PORT")) + switch mode { + case "hold": + if !claimHostPort(p) { + os.Stdout.WriteString("refused\n") + os.Exit(3) + } + os.Stdout.WriteString("held\n") + _, _ = bufio.NewReader(os.Stdin).ReadString('\n') // until the parent closes stdin + os.Exit(0) + case "try": + if claimHostPort(p) { + os.Exit(0) + } + os.Exit(3) + } + os.Exit(2) + } + os.Exit(m.Run()) +} + +// claimEnv is the environment of a claim helper for port p in dir. +func claimEnv(mode, dir string, p int) []string { + return append(os.Environ(), claimChildEnv+"="+mode, "SWBLOCK_TEST_PORT_CLAIM_PORT="+strconv.Itoa(p), "SWBLOCK_TEST_PORT_CLAIMS="+dir) +} + +// tryClaim runs a "try" helper with a local deadline and returns its exit +// code. +func tryClaim(t *testing.T, dir string, p int) int { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0]) + cmd.Env = claimEnv("try", dir, p) + err := cmd.Run() + if ctx.Err() != nil { + t.Fatalf("the claim helper did not finish: %v", ctx.Err()) + } + if ee, ok := err.(*exec.ExitError); ok { + return ee.ExitCode() + } + if err != nil { + t.Fatal(err) + } + return 0 +} + +// holdClaim starts a "hold" helper and waits until it holds the port; the +// returned release closes its stdin and reaps it, within a deadline. +func holdClaim(t *testing.T, dir string, p int) (release func()) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + cmd := exec.CommandContext(ctx, os.Args[0]) + cmd.Env = claimEnv("hold", dir, p) + in, err := cmd.StdinPipe() + if err != nil { + cancel() + t.Fatal(err) + } + out, err := cmd.StdoutPipe() + if err != nil { + cancel() + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + cancel() + t.Fatal(err) + } + released := false + release = func() { + if released { + return + } + released = true + in.Close() + _ = cmd.Wait() // bounded by ctx: a hung helper is killed at its deadline + cancel() + } + t.Cleanup(release) + line, err := bufio.NewReader(out).ReadString('\n') + if err != nil || line != "held\n" { + release() + t.Fatalf("the holder did not take the port: %q %v", line, err) + } + return release +} + +// A port held by one process is refused to another on the same host, and +// taken once the holder has exited. +func TestHostPortClaimKeepsTwoProcessesApart(t *testing.T) { + dir := t.TempDir() + const p = 15151 + release := holdClaim(t, dir, p) + if code := tryClaim(t, dir, p); code != 3 { + t.Fatalf("a second process took a held port (exit %d)", code) + } + release() + if code := tryClaim(t, dir, p); code != 0 { + t.Fatalf("the port was not free after its holder exited (exit %d)", code) + } +} + +// A lock file left by another runner user, readable but not writable (0444), +// is still claimable: flock needs no write access. Held, it still keeps a +// second process out. +func TestHostPortClaimOnAReadOnlyLockFile(t *testing.T) { + dir := t.TempDir() + const p = 15252 + name := filepath.Join(dir, strconv.Itoa(p)+".lock") + if err := os.WriteFile(name, nil, 0o444); err != nil { + t.Fatal(err) + } + if err := os.Chmod(name, 0o444); err != nil { + t.Fatal(err) + } + release := holdClaim(t, dir, p) + if code := tryClaim(t, dir, p); code != 3 { + t.Fatalf("a second process took a port held through a read-only lock file (exit %d)", code) + } + release() +} diff --git a/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go b/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go new file mode 100644 index 0000000000..e4aceaa903 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/test_port_claim_unix_test.go @@ -0,0 +1,83 @@ +//go:build unix + +package main_test + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "syscall" +) + +// hostPortClaims holds, for this test process's life, an exclusive flock on +// one file per port it handed out. Two test processes on one host (two CI +// jobs on one machine, each with its own shards) then never hand out the +// same port: the per-shard slice keeps shards of one job apart, the claim +// keeps jobs apart. The kernel drops a claim when its process exits. +var hostPortClaims struct { + sync.Mutex + files map[int]*os.File + reported bool // a claim error other than "held" was reported once +} + +// testPortClaimDir is the host-wide directory of port claims: +// SWBLOCK_TEST_PORT_CLAIMS, else /tmp/swblock-test-port-claims (not TMPDIR, +// which differs per shard and per job). +func testPortClaimDir() string { + if d := os.Getenv("SWBLOCK_TEST_PORT_CLAIMS"); d != "" { + return d + } + return "/tmp/swblock-test-port-claims" +} + +// claimHostPort takes port p for this process, host-wide; false when another +// process holds it. Only "would block" means held: any other error (the +// directory or file cannot be opened) is reported once, with its path, and +// the port is left to the caller's listen probe, as without claims. +func claimHostPort(p int) bool { + hostPortClaims.Lock() + defer hostPortClaims.Unlock() + if hostPortClaims.files == nil { + hostPortClaims.files = map[int]*os.File{} + } + if _, ok := hostPortClaims.files[p]; ok { + return false // already handed out by this process + } + f, err := flockPortFile(testPortClaimDir(), p) + switch { + case err == nil: + hostPortClaims.files[p] = f + return true + case errors.Is(err, syscall.EWOULDBLOCK): + return false + default: + if !hostPortClaims.reported { + hostPortClaims.reported = true + fmt.Fprintf(os.Stderr, "test port claims off: %v\n", err) + } + return true + } +} + +// flockPortFile opens dir/
.lock read-only (creating it if needed) and +// takes an exclusive, non-blocking flock on it; the open file holds the +// claim. flock needs no write access, so a lock file another runner user +// created stays claimable. +func flockPortFile(dir string, p int) (*os.File, error) { + if err := os.MkdirAll(dir, 0o777); err != nil { + return nil, err + } + _ = os.Chmod(dir, 0o777) // shared by every runner user on the host + name := filepath.Join(dir, fmt.Sprintf("%d.lock", p)) + f, err := os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0o444) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + f.Close() + return nil, err + } + return f, nil +} diff --git a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go index 18c1a72693..c603903c5a 100644 --- a/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go +++ b/seaweed-block/cmd/blockvolume/workspace_weed_integration_test.go @@ -66,6 +66,9 @@ func w4FreePortPair(t *testing.T, used map[int]bool) int { if (p >= lo && p <= hi) || (p+10000 >= lo && p+10000 <= hi) { continue } + if !claimHostPort(p) || !claimHostPort(p+10000) { + continue + } ok := true for _, q := range []int{p, p + 10000} { l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q))