mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
test: real-filer harnesses start again on fresh ports outside the ephemeral range (#1037)
Merge note (pull_request_target spec-trace workflow has a startup_failure on every branch since 2026-12-02 22:45Z, so its checks run locally): - Test run 47279939755 succeeded (go test (linux), process-level tests (real binaries)) on head 6399499f against main f639e70e, the current main head. - spec-trace-check.sh and public-text-check.sh, run with the main branch's scripts against this head and body: both exit 0.
This commit is contained in:
1 parent
a868d616a0
commit
402db30aef
13 files changed
+524
-280
No files matched your search
@@ -1,7 +0,0 @@
|
||||
//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 }
|
||||
@@ -1,39 +1,10 @@
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// testPortSpan narrows a port range [lo, hi) to this test process's share
|
||||
// when several process-level test binaries run in parallel on one host
|
||||
// (CI shards): SWBLOCK_TEST_PORT_SHARD=k of SWBLOCK_TEST_PORT_SHARDS=n
|
||||
// (1 <= k <= n) gets the k-th of n equal slices, so two shards never draw
|
||||
// the same port. Unset or invalid, the whole range.
|
||||
func testPortSpan(lo, hi int) (int, int) {
|
||||
n, errN := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARDS"))
|
||||
k, errK := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARD"))
|
||||
if errN != nil || errK != nil || n < 2 || k < 1 || k > n || hi-lo < n {
|
||||
return lo, hi
|
||||
}
|
||||
w := (hi - lo) / n
|
||||
return lo + (k-1)*w, lo + k*w
|
||||
}
|
||||
|
||||
// weedPairRange is the range [20000, hi) of a weed server's HTTP port p,
|
||||
// whose gRPC port is p+10000, given the host's ephemeral range starting at
|
||||
// ephemeralLo: every gRPC port stays below the ephemeral range when that
|
||||
// leaves room, and every HTTP port stays below every gRPC port (hi <= 30000),
|
||||
// so slicing the HTTP range per shard keeps both kinds of port apart.
|
||||
func weedPairRange(ephemeralLo int) (int, int) {
|
||||
hi := 30000
|
||||
if ephemeralLo-10000 > 20000 && ephemeralLo-10000 < hi {
|
||||
hi = ephemeralLo - 10000
|
||||
}
|
||||
return 20000, hi
|
||||
}
|
||||
|
||||
func TestWeedPairSlicesNeverMeetAcrossShards(t *testing.T) {
|
||||
t.Setenv("SWBLOCK_TEST_PORT_SHARDS", "4")
|
||||
for _, eph := range []int{28000, 32768, 40000, 50000, 61000} {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package main_test
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/internal/weedtest"
|
||||
|
||||
// The harness's ports come from internal/weedtest, which every
|
||||
// process-level harness on a host shares: outside the ephemeral range,
|
||||
// sliced per CI shard and claimed host-wide.
|
||||
|
||||
func claimHostPort(p int) bool { return weedtest.Claim(p) }
|
||||
func testPortSpan(lo, hi int) (int, int) { return weedtest.Span(lo, hi) }
|
||||
func weedPairRange(ephemeralLo int) (int, int) { return weedtest.WeedPairRange(ephemeralLo) }
|
||||
func ephemeralPorts() (int, int) { return weedtest.EphemeralRange() }
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/internal/weedtest"
|
||||
"math"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -42,54 +42,13 @@ func testListenHost() string {
|
||||
return "127.0.0.1"
|
||||
}
|
||||
|
||||
// ephemeralPorts is the host's range for outgoing connections' source ports
|
||||
// (Linux ip_local_port_range; the Linux default when unreadable). A port in it
|
||||
// can be taken by any outgoing connection between the free check and weed's
|
||||
// bind, so a port pair never uses it.
|
||||
func ephemeralPorts() (int, int) {
|
||||
lo, hi := 32768, 60999
|
||||
if b, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil {
|
||||
var a, z int
|
||||
if n, _ := fmt.Sscan(string(b), &a, &z); n == 2 && a > 0 && z >= a {
|
||||
lo, hi = a, z
|
||||
}
|
||||
}
|
||||
return lo, hi
|
||||
}
|
||||
|
||||
func w4FreePortPair(t *testing.T, used map[int]bool) int {
|
||||
t.Helper()
|
||||
lo, hi := ephemeralPorts()
|
||||
// A CI shard draws its HTTP ports from its own slice of weedPairRange;
|
||||
// their gRPC ports (+10000) then never meet another shard's.
|
||||
sLo, sHi := testPortSpan(weedPairRange(lo))
|
||||
for i := 0; i < 200; i++ {
|
||||
p := sLo + rand.Intn(sHi-sLo)
|
||||
if used[p] || used[p+10000] {
|
||||
continue
|
||||
}
|
||||
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))
|
||||
if err != nil {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
l.Close()
|
||||
}
|
||||
if ok {
|
||||
used[p], used[p+10000] = true, true
|
||||
return p
|
||||
}
|
||||
p, ok := weedtest.FreeWeedPair(testListenHost(), used)
|
||||
if !ok {
|
||||
t.Fatal("no free port pair")
|
||||
}
|
||||
t.Fatal("no free port pair")
|
||||
return 0
|
||||
return p
|
||||
}
|
||||
|
||||
func w4WaitTCP(t *testing.T, addr string, d time.Duration) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
//go:build chunkstore_integration
|
||||
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/internal/weedtest"
|
||||
)
|
||||
|
||||
// A weed start whose filer cannot bind its gRPC port (another process on the
|
||||
// host holds it, as an outgoing connection's source port can) is discarded
|
||||
// as soon as the filer exits, and the cluster is started again on fresh
|
||||
// ports; that start serves.
|
||||
func TestIntegration_WeedStartsAgainOnFreshPortsWhenTheFilerCannotBind(t *testing.T) {
|
||||
pick := weedtest.PickPair
|
||||
t.Cleanup(func() { weedtest.PickPair = pick })
|
||||
held := 0
|
||||
weedtest.PickPair = func(t testing.TB, used map[int]bool, role string) int {
|
||||
p := pick(t, used, role)
|
||||
if role == "filer" && held == 0 {
|
||||
held = p + 10000
|
||||
weedtest.HoldWithoutListening(t, held)
|
||||
}
|
||||
return p
|
||||
}
|
||||
start := time.Now()
|
||||
c := startWeed(t)
|
||||
if held == 0 {
|
||||
t.Fatal("the first start did not pick a filer pair")
|
||||
}
|
||||
if len(c.Starts) < 2 {
|
||||
t.Fatalf("the cluster came up on its first start although its filer gRPC port %d was held", held)
|
||||
}
|
||||
// The held port went to the first start that picked a filer pair, which
|
||||
// need not be the first start (one can fail before its filer starts):
|
||||
// some discarded start's filer must have failed to bind it.
|
||||
bound := false
|
||||
for _, dir := range c.Starts[:len(c.Starts)-1] {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "filer.log"))
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound = bound || strings.Contains(string(b), "address already in use")
|
||||
}
|
||||
if !bound {
|
||||
t.Fatalf("no discarded start's filer failed to bind the held port %d (starts %v)", held, c.Starts)
|
||||
}
|
||||
if c.filerGRPC == fmt.Sprintf("127.0.0.1:%d", held) {
|
||||
t.Fatalf("the cluster kept the held filer gRPC port %d", held)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := c.client(t, "/swblock/vols/fresh-ports").Put(ctx, []byte("after the second start")); err != nil {
|
||||
t.Fatalf("the cluster started again on fresh ports does not accept a write: %v", err)
|
||||
}
|
||||
t.Logf("filer gRPC port %d was held; start %d served after %v", held, len(c.Starts), time.Since(start).Round(time.Second))
|
||||
}
|
||||
@@ -8,58 +8,16 @@ package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/internal/weedtest"
|
||||
)
|
||||
|
||||
type weedCluster struct {
|
||||
master, filerHTTP, filerGRPC string
|
||||
dir string
|
||||
weed string
|
||||
}
|
||||
|
||||
func freePortPair(t *testing.T, used map[int]bool) int {
|
||||
t.Helper()
|
||||
for i := 0; i < 200; i++ {
|
||||
p := 20000 + rand.Intn(20000)
|
||||
if used[p] || used[p+10000] {
|
||||
continue
|
||||
}
|
||||
ok := true
|
||||
for _, q := range []int{p, p + 10000} {
|
||||
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q))
|
||||
if err != nil {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
l.Close()
|
||||
}
|
||||
if ok {
|
||||
used[p], used[p+10000] = true, true
|
||||
return p
|
||||
}
|
||||
}
|
||||
t.Fatal("no free port pair")
|
||||
return 0
|
||||
}
|
||||
|
||||
func waitTCP(t *testing.T, addr string, d time.Duration) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(d)
|
||||
for time.Now().Before(deadline) {
|
||||
if c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s not listening after %v", addr, d)
|
||||
*weedtest.Cluster
|
||||
filerGRPC string
|
||||
}
|
||||
|
||||
func startWeed(t *testing.T) *weedCluster {
|
||||
@@ -76,81 +34,30 @@ func startWeedWith(t *testing.T, security string) *weedCluster {
|
||||
|
||||
// startWeedSized starts the cluster with the master's volume size limit
|
||||
// (MB) and the volume server's volume count (-max): the store holds at most
|
||||
// max x sizeMB.
|
||||
// max x sizeMB. A start that fails (a server cannot bind a port another
|
||||
// process took) is started again on fresh ports.
|
||||
func startWeedSized(t *testing.T, security string, sizeMB, max int) *weedCluster {
|
||||
t.Helper()
|
||||
weed := os.Getenv("CHUNKSTORE_WEED")
|
||||
if weed == "" {
|
||||
t.Skip("CHUNKSTORE_WEED not set")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
used := map[int]bool{}
|
||||
mp, vp, fp := freePortPair(t, used), freePortPair(t, used), freePortPair(t, used)
|
||||
c := &weedCluster{
|
||||
master: fmt.Sprintf("127.0.0.1:%d", mp),
|
||||
filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp),
|
||||
filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000),
|
||||
dir: dir,
|
||||
weed: weed,
|
||||
}
|
||||
run := func(name string, args ...string) {
|
||||
logf, err := os.Create(filepath.Join(dir, name+".log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(weed, args...)
|
||||
cmd.Stdout, cmd.Stderr = logf, logf
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start %s: %v", name, err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_, _ = cmd.Process.Wait()
|
||||
logf.Close()
|
||||
if t.Failed() {
|
||||
b, _ := os.ReadFile(logf.Name())
|
||||
if len(b) > 4000 {
|
||||
b = b[len(b)-4000:]
|
||||
}
|
||||
t.Logf("---- %s log tail ----\n%s", name, b)
|
||||
c := weedtest.Start(t, weed, t.TempDir(), weedtest.Options{
|
||||
SizeMB: sizeMB, Max: max, Security: security,
|
||||
// Ready once an assign succeeds (volume registered, volumes growable).
|
||||
Ready: func(filerGRPC string) error {
|
||||
cl, err := DialSWFS(SWFSConfig{FilerGRPC: filerGRPC, Collection: "swblock", AssignPath: "/swblock/vols/probe"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, d := range []string{"m", "v", "f"} {
|
||||
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if security != "" {
|
||||
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", sizeMB), "-defaultReplication=000")
|
||||
waitTCP(t, c.master, 20*time.Second)
|
||||
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", max))
|
||||
// Its own filer group: another cluster's filer that reaches this master
|
||||
// (a port pair picked alike) is not counted by this cluster's census.
|
||||
run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"), "-filerGroup="+fmt.Sprintf("swt%016x", rand.Uint64()))
|
||||
waitTCP(t, c.filerGRPC, 30*time.Second)
|
||||
|
||||
// Wait until an assign succeeds (volume registered, volumes growable).
|
||||
cl := c.client(t, "/swblock/vols/probe")
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
_, err := cl.Put(ctx, []byte("probe"))
|
||||
cancel()
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("cluster never accepted a write: %v", err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
return c
|
||||
defer cl.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, err = cl.Put(ctx, []byte("probe"))
|
||||
return err
|
||||
},
|
||||
})
|
||||
return &weedCluster{Cluster: c, filerGRPC: c.FilerGRPC}
|
||||
}
|
||||
|
||||
func (c *weedCluster) client(t *testing.T, assignPath string) *SWFS {
|
||||
|
||||
@@ -6,8 +6,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -19,95 +17,20 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/internal/weedtest"
|
||||
)
|
||||
|
||||
// The B arm uses a real filer so the child and parent observe the same HEAD.
|
||||
// Run with CHUNKSTORE_WEED=/path/to/weed and -tags chunkstore_integration.
|
||||
// A start that fails (a server cannot bind a port another process took) is
|
||||
// started again on fresh ports.
|
||||
func qd1LayoutWeed(t *testing.T) string {
|
||||
t.Helper()
|
||||
weed := os.Getenv("CHUNKSTORE_WEED")
|
||||
if weed == "" {
|
||||
t.Skip("CHUNKSTORE_WEED not set")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
used := map[int]bool{}
|
||||
port := func() int {
|
||||
t.Helper()
|
||||
for i := 0; i < 200; i++ {
|
||||
p := 20000 + rand.Intn(20000)
|
||||
if used[p] || used[p+10000] {
|
||||
continue
|
||||
}
|
||||
ok := true
|
||||
for _, n := range []int{p, p + 10000} {
|
||||
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", n))
|
||||
if err != nil {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
l.Close()
|
||||
}
|
||||
if ok {
|
||||
used[p], used[p+10000] = true, true
|
||||
return p
|
||||
}
|
||||
}
|
||||
t.Fatal("no free local port pair")
|
||||
return 0
|
||||
}
|
||||
mp, vp, fp := port(), port(), port()
|
||||
run := func(name string, args ...string) {
|
||||
t.Helper()
|
||||
f, err := os.Create(filepath.Join(dir, name+".log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(weed, args...)
|
||||
cmd.Dir, cmd.Stdout, cmd.Stderr = dir, f, f
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_, _ = cmd.Process.Wait()
|
||||
_ = f.Close()
|
||||
if t.Failed() {
|
||||
b, _ := os.ReadFile(f.Name())
|
||||
if len(b) > 4000 {
|
||||
b = b[len(b)-4000:]
|
||||
}
|
||||
t.Logf("%s log tail:\n%s", name, b)
|
||||
}
|
||||
})
|
||||
}
|
||||
wait := func(addr string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(30 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond)
|
||||
if err == nil {
|
||||
_ = c.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s did not start", addr)
|
||||
}
|
||||
for _, name := range []string{"m", "v", "f"} {
|
||||
if err := os.Mkdir(filepath.Join(dir, name), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
master := fmt.Sprintf("127.0.0.1:%d", mp)
|
||||
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
|
||||
wait(master)
|
||||
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+master, "-max=32")
|
||||
// Its own filer group: another cluster's filer that reaches this master
|
||||
// (a port pair picked alike) is not counted by this cluster's census.
|
||||
run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+master, "-defaultStoreDir="+filepath.Join(dir, "f"), "-filerGroup="+fmt.Sprintf("swt%016x", rand.Uint64()))
|
||||
grpc := fmt.Sprintf("127.0.0.1:%d", fp+10000)
|
||||
wait(grpc)
|
||||
return grpc
|
||||
return weedtest.Start(t, weed, t.TempDir(), weedtest.Options{SizeMB: 256, Max: 32}).FilerGRPC
|
||||
}
|
||||
|
||||
func qd1LayoutProvider(t *testing.T, root, grpc, base, idText string) (*durable.DurableProvider, *durable.StorageBackend) {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !unix
|
||||
|
||||
package weedtest
|
||||
|
||||
// Claim: the process-level tests run on Linux only; elsewhere every port is
|
||||
// this process's to probe.
|
||||
func Claim(p int) bool { return true }
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
//go:build unix
|
||||
|
||||
package main_test
|
||||
package weedtest
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -32,11 +32,11 @@ func testPortClaimDir() string {
|
||||
return "/tmp/swblock-test-port-claims"
|
||||
}
|
||||
|
||||
// claimHostPort takes port p for this process, host-wide; false when another
|
||||
// Claim 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 {
|
||||
func Claim(p int) bool {
|
||||
hostPortClaims.Lock()
|
||||
defer hostPortClaims.Unlock()
|
||||
if hostPortClaims.files == nil {
|
||||
@@ -0,0 +1,229 @@
|
||||
package weedtest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Starts is how many times a cluster that does not start (a server exits or
|
||||
// never listens, or the cluster is never ready) is started again on fresh
|
||||
// ports. A port pair is checked free and then released before weed binds
|
||||
// it; another process on the host (a concurrent job on a shared runner) can
|
||||
// take it in between. Each server's pair is picked just before that server
|
||||
// starts, which keeps that window short.
|
||||
var Starts = 3
|
||||
|
||||
// PickPair picks a server's port pair (role "master", "volume", "filer");
|
||||
// a test replaces it to make a start collide with another process.
|
||||
var PickPair = func(t testing.TB, used map[int]bool, role string) int {
|
||||
t.Helper()
|
||||
p, ok := FreeWeedPair(host, used)
|
||||
if !ok {
|
||||
t.Fatal("no free port pair")
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
const host = "127.0.0.1"
|
||||
|
||||
// Options shape a cluster: the master's volume size limit (MB), the volume
|
||||
// server's volume count (-max), the contents of a security.toml in the
|
||||
// cluster's directory ("" for none), and Ready, which reports whether the
|
||||
// started cluster serves (nil: its filer's gRPC port listens).
|
||||
type Options struct {
|
||||
SizeMB, Max int
|
||||
Security string
|
||||
Ready func(filerGRPC string) error
|
||||
}
|
||||
|
||||
// Cluster is one started weed cluster.
|
||||
type Cluster struct {
|
||||
Master, FilerHTTP, FilerGRPC string
|
||||
Dir string // this start's directory (server logs: <role>.log)
|
||||
Starts []string // the directory of every start, the discarded ones first
|
||||
procs []*proc
|
||||
}
|
||||
|
||||
type proc struct {
|
||||
role string
|
||||
log *os.File
|
||||
cmd *exec.Cmd
|
||||
done chan struct{}
|
||||
err error // the exit status, set before done closes
|
||||
discarded bool // its start was discarded and its log already reported
|
||||
}
|
||||
|
||||
// Start starts a cluster from the weed binary in dir, starting again on
|
||||
// fresh ports (Starts times in all) while a start fails; the last failure
|
||||
// fails t. The servers are stopped when t ends.
|
||||
func Start(t testing.TB, weed, dir string, o Options) *Cluster {
|
||||
t.Helper()
|
||||
var starts []string
|
||||
for attempt := 1; ; attempt++ {
|
||||
at := dir
|
||||
if attempt > 1 {
|
||||
at = filepath.Join(dir, fmt.Sprintf("start-%d", attempt))
|
||||
}
|
||||
starts = append(starts, at)
|
||||
c, err := startOnce(t, weed, at, o)
|
||||
c.Starts = starts
|
||||
if err == nil {
|
||||
return c
|
||||
}
|
||||
if attempt >= Starts {
|
||||
t.Fatalf("weed start %d of %d failed: %v", attempt, Starts, err)
|
||||
}
|
||||
t.Logf("weed start %d of %d failed, starting again on fresh ports: %v", attempt, Starts, err)
|
||||
c.discard(t)
|
||||
}
|
||||
}
|
||||
|
||||
func startOnce(t testing.TB, weed, dir string, o Options) (*Cluster, error) {
|
||||
t.Helper()
|
||||
c := &Cluster{Dir: dir}
|
||||
for _, d := range []string{"m", "v", "f"} {
|
||||
if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if o.Security != "" {
|
||||
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(o.Security), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
used := map[int]bool{}
|
||||
mp := PickPair(t, used, "master")
|
||||
c.Master = fmt.Sprintf("%s:%d", host, mp)
|
||||
m := c.start(t, weed, "master", "master", "-ip="+host, fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.SizeMB), "-defaultReplication=000")
|
||||
if err := c.listening(m, c.Master, 20*time.Second); err != nil {
|
||||
return c, err
|
||||
}
|
||||
vp := PickPair(t, used, "volume")
|
||||
c.start(t, weed, "volume", "volume", "-ip="+host, fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.Master, fmt.Sprintf("-max=%d", o.Max))
|
||||
fp := PickPair(t, used, "filer")
|
||||
c.FilerHTTP = fmt.Sprintf("%s:%d", host, fp)
|
||||
c.FilerGRPC = fmt.Sprintf("%s:%d", host, fp+10000)
|
||||
// Its own filer group: another cluster's filer that reaches this master
|
||||
// (a port pair picked alike) is not counted by this cluster's census.
|
||||
f := c.start(t, weed, "filer", "filer", "-ip="+host, fmt.Sprintf("-port=%d", fp), "-master="+c.Master, "-defaultStoreDir="+filepath.Join(dir, "f"), fmt.Sprintf("-filerGroup=swt%016x", rand.Uint64()))
|
||||
if err := c.listening(f, c.FilerGRPC, 30*time.Second); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if o.Ready != nil {
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for {
|
||||
err := o.Ready(c.FilerGRPC)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if e := c.exited(); e != nil {
|
||||
return c, fmt.Errorf("%w; not ready: %v", e, err)
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return c, fmt.Errorf("the cluster was not ready within 60s: %w", err)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
// A server that could not bind its port has exited by now, even when
|
||||
// another process answered on that port.
|
||||
return c, c.exited()
|
||||
}
|
||||
|
||||
// start launches one server of this start; it is stopped when t ends.
|
||||
func (c *Cluster) start(t testing.TB, weed, role string, args ...string) *proc {
|
||||
t.Helper()
|
||||
logf, err := os.Create(filepath.Join(c.Dir, role+".log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(weed, args...)
|
||||
cmd.Stdout, cmd.Stderr, cmd.Dir = logf, logf, c.Dir
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start weed %s: %v", role, err)
|
||||
}
|
||||
p := &proc{role: role, log: logf, cmd: cmd, done: make(chan struct{})}
|
||||
go func() {
|
||||
p.err = cmd.Wait()
|
||||
close(p.done)
|
||||
}()
|
||||
c.procs = append(c.procs, p)
|
||||
t.Cleanup(func() {
|
||||
if !p.stop() {
|
||||
t.Errorf("weed %s did not exit after kill", role)
|
||||
}
|
||||
p.log.Close()
|
||||
if t.Failed() && !p.discarded {
|
||||
t.Logf("---- %s log tail (%s) ----\n%s", role, c.Dir, p.tail())
|
||||
}
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
// listening waits until addr accepts a connection while p runs.
|
||||
func (c *Cluster) listening(p *proc, addr string, d time.Duration) error {
|
||||
deadline := time.Now().Add(d)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case <-p.done:
|
||||
return fmt.Errorf("weed %s exited (%v) before %s listened", p.role, p.err, addr)
|
||||
default:
|
||||
}
|
||||
if conn, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil {
|
||||
conn.Close()
|
||||
return nil
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("weed %s: %s not listening after %v", p.role, addr, d)
|
||||
}
|
||||
|
||||
// exited reports a server of this start that has already exited.
|
||||
func (c *Cluster) exited() error {
|
||||
for _, p := range c.procs {
|
||||
select {
|
||||
case <-p.done:
|
||||
return fmt.Errorf("weed %s exited (%v)", p.role, p.err)
|
||||
default:
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// discard stops a start that failed and logs each server's log tail.
|
||||
func (c *Cluster) discard(t testing.TB) {
|
||||
t.Helper()
|
||||
for _, p := range c.procs {
|
||||
if !p.stop() {
|
||||
t.Errorf("weed %s did not exit after kill", p.role)
|
||||
}
|
||||
p.discarded = true
|
||||
t.Logf("---- discarded start: %s log tail (%s) ----\n%s", p.role, c.Dir, p.tail())
|
||||
}
|
||||
}
|
||||
|
||||
// stop kills the server and waits for its exit; false when it did not exit
|
||||
// within 5 s.
|
||||
func (p *proc) stop() bool {
|
||||
_ = p.cmd.Process.Kill()
|
||||
select {
|
||||
case <-p.done:
|
||||
return true
|
||||
case <-time.After(5 * time.Second):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *proc) tail() []byte {
|
||||
b, _ := os.ReadFile(p.log.Name())
|
||||
if len(b) > 4000 {
|
||||
b = b[len(b)-4000:]
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package weedtest
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// HoldWithoutListening takes port as the source port of an open loopback
|
||||
// connection, as any outgoing connection on the host can: a server then
|
||||
// cannot bind it ("address already in use"), and nothing answers on it.
|
||||
// The hold ends when t ends.
|
||||
func HoldWithoutListening(t testing.TB, port int) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", net.JoinHostPort(host, "0"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
c, _ := ln.Accept()
|
||||
accepted <- c
|
||||
}()
|
||||
d := net.Dialer{LocalAddr: &net.TCPAddr{IP: net.ParseIP(host), Port: port}}
|
||||
conn, err := d.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
ln.Close()
|
||||
t.Fatalf("hold port %s: %v", strconv.Itoa(port), err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
conn.Close()
|
||||
ln.Close()
|
||||
if c := <-accepted; c != nil {
|
||||
c.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Package weedtest starts real weed clusters (master, volume, filer) for the
|
||||
// integration tests, and hands out the local TCP ports of every
|
||||
// process-level harness: outside the host's ephemeral range, claimed
|
||||
// host-wide, and probed free. Every harness on a host draws from it, so two
|
||||
// test binaries (two CI jobs on one machine) never hand out the same port.
|
||||
package weedtest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// EphemeralRange is the host's range for outgoing connections' source
|
||||
// ports (Linux ip_local_port_range; the Linux default when unreadable). A
|
||||
// port in it can be taken by any outgoing connection between the free check
|
||||
// and the server's bind, so a handed-out port never uses it.
|
||||
func EphemeralRange() (int, int) {
|
||||
lo, hi := 32768, 60999
|
||||
if b, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil {
|
||||
var a, z int
|
||||
if n, _ := fmt.Sscan(string(b), &a, &z); n == 2 && a > 0 && z >= a {
|
||||
lo, hi = a, z
|
||||
}
|
||||
}
|
||||
return lo, hi
|
||||
}
|
||||
|
||||
// Span narrows a port range [lo, hi) to this test process's share when
|
||||
// several process-level test binaries run in parallel on one host (CI
|
||||
// shards): SWBLOCK_TEST_PORT_SHARD=k of SWBLOCK_TEST_PORT_SHARDS=n
|
||||
// (1 <= k <= n) gets the k-th of n equal slices, so two shards never draw
|
||||
// the same port. Unset or invalid, the whole range.
|
||||
func Span(lo, hi int) (int, int) {
|
||||
n, errN := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARDS"))
|
||||
k, errK := strconv.Atoi(os.Getenv("SWBLOCK_TEST_PORT_SHARD"))
|
||||
if errN != nil || errK != nil || n < 2 || k < 1 || k > n || hi-lo < n {
|
||||
return lo, hi
|
||||
}
|
||||
w := (hi - lo) / n
|
||||
return lo + (k-1)*w, lo + k*w
|
||||
}
|
||||
|
||||
// WeedPairRange is the range [20000, hi) of a weed server's HTTP port p,
|
||||
// whose gRPC port is p+10000, given the host's ephemeral range starting at
|
||||
// ephemeralLo: every gRPC port stays below the ephemeral range when that
|
||||
// leaves room, and every HTTP port stays below every gRPC port (hi <= 30000),
|
||||
// so slicing the HTTP range per shard keeps both kinds of port apart.
|
||||
func WeedPairRange(ephemeralLo int) (int, int) {
|
||||
hi := 30000
|
||||
if ephemeralLo-10000 > 20000 && ephemeralLo-10000 < hi {
|
||||
hi = ephemeralLo - 10000
|
||||
}
|
||||
return 20000, hi
|
||||
}
|
||||
|
||||
// FreeWeedPair picks a weed server's port pair (HTTP p, gRPC p+10000) on
|
||||
// host: this shard's slice of WeedPairRange, neither port in used or in the
|
||||
// ephemeral range, both claimed host-wide and free to listen on now. It
|
||||
// marks both in used; false when no pair was found.
|
||||
func FreeWeedPair(host string, used map[int]bool) (int, bool) {
|
||||
lo, hi := EphemeralRange()
|
||||
sLo, sHi := Span(WeedPairRange(lo))
|
||||
for i := 0; i < 200; i++ {
|
||||
p := sLo + rand.Intn(sHi-sLo)
|
||||
if used[p] || used[p+10000] {
|
||||
continue
|
||||
}
|
||||
if (p >= lo && p <= hi) || (p+10000 >= lo && p+10000 <= hi) {
|
||||
continue
|
||||
}
|
||||
if !Claim(p) || !Claim(p+10000) {
|
||||
continue
|
||||
}
|
||||
ok := true
|
||||
for _, q := range []int{p, p + 10000} {
|
||||
l, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(q)))
|
||||
if err != nil {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
l.Close()
|
||||
}
|
||||
if ok {
|
||||
used[p], used[p+10000] = true, true
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//go:build linux
|
||||
|
||||
package weedtest
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// No port of a handed-out pair lies in the host's range for outgoing
|
||||
// connections' source ports, where any connection could take it between the
|
||||
// free check and weed's bind (a filer gRPC port in that range failed to bind
|
||||
// on a shared runner, and its start waited 30 s for a port nothing served).
|
||||
func TestWeedPairsAvoidTheEphemeralRange(t *testing.T) {
|
||||
lo, hi := EphemeralRange()
|
||||
used := map[int]bool{}
|
||||
for i := 0; i < 100; i++ {
|
||||
p := PickPair(t, used, "test")
|
||||
for _, q := range []int{p, p + 10000} {
|
||||
if q >= lo && q <= hi {
|
||||
t.Fatalf("pair %d/%d: port %d is in the ephemeral range %d-%d", p, p+10000, q, lo, hi)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HoldWithoutListening reproduces that collision: the port cannot be bound
|
||||
// and nothing answers on it.
|
||||
func TestAHeldPortCannotBeBoundAndDoesNotAnswer(t *testing.T) {
|
||||
p := PickPair(t, map[int]bool{}, "test") + 10000
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(p))
|
||||
HoldWithoutListening(t, p)
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err == nil {
|
||||
ln.Close()
|
||||
t.Fatalf("%s could be bound while held", addr)
|
||||
}
|
||||
if !errors.Is(err, syscall.EADDRINUSE) {
|
||||
t.Fatalf("bind %s while held: %v, want address already in use", addr, err)
|
||||
}
|
||||
if c, err := net.DialTimeout("tcp", addr, time.Second); err == nil {
|
||||
c.Close()
|
||||
t.Fatalf("%s answered while held without a listener", addr)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user