test(blockvolume): weed port pairs avoid the host's ephemeral port range

w4FreePortPair checked a pair free and weed bound it later; a pair inside
ip_local_port_range could be taken in between by any outgoing connection's
source port (seen: a filer's gRPC port 43775 inside a host's 43255-47350,
"bind: address already in use", with extra volumes adding connections).
handoffAddress already stays below that range for the same reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a54fcdde5ea81b1d23396c45ace385038288553a)
This commit is contained in:
pingqiu committed 2026-11-26 06:19:00 -08:00
1 parent c86586a124
commit cb51f2ebe9
1 file changed
+19
@@ -37,13 +37,32 @@ func testListenHost() string {
return "127.0.0.1"
}
// ephemeralPorts is the host's range for outgoing connections' source ports
// (Linux ip_local_port_range; the Linux default when unreadable). A port in it
// can be taken by any outgoing connection between the free check and weed's
// bind, so a port pair never uses it.
func ephemeralPorts() (int, int) {
lo, hi := 32768, 60999
if b, err := os.ReadFile("/proc/sys/net/ipv4/ip_local_port_range"); err == nil {
var a, z int
if n, _ := fmt.Sscan(string(b), &a, &z); n == 2 && a > 0 && z >= a {
lo, hi = a, z
}
}
return lo, hi
}
func w4FreePortPair(t *testing.T, used map[int]bool) int {
t.Helper()
lo, hi := ephemeralPorts()
for i := 0; i < 200; i++ {
p := 20000 + rand.Intn(20000)
if used[p] || used[p+10000] {
continue
}
if (p >= lo && p <= hi) || (p+10000 >= lo && p+10000 <= hi) {
continue
}
ok := true
for _, q := range []int{p, p + 10000} {
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q))