kubo/test/cli/harness/peering.go
Marcin Rataj 4bafb22b76
Some checks failed
Docker Build / docker-build (push) Waiting to run
Gateway Conformance / gateway-conformance (push) Waiting to run
Gateway Conformance / gateway-conformance-libp2p-experiment (push) Waiting to run
Go Build / go-build (push) Waiting to run
Go Check / go-check (push) Waiting to run
Go Lint / go-lint (push) Waiting to run
Go Test / go-test (push) Waiting to run
Interop / interop-prep (push) Waiting to run
Interop / helia-interop (push) Blocked by required conditions
Interop / ipfs-webui (push) Blocked by required conditions
Sharness / sharness-test (push) Waiting to run
Spell Check / spellcheck (push) Waiting to run
CodeQL / codeql (push) Has been cancelled
fix(ci): make NewRandPort thread-safe (#10921)
* chore: disable AutoTLS in TCP-only transport tests

Tests were failing intermittently. Disabling AutoTLS when WebSocket
transport is disabled appears to resolve the issue.

* fix: make NewRandPort thread-safe

Track allocated ports globally to prevent conflicts
when tests run in parallel.
2025-08-18 22:12:22 +02:00

69 lines
1.3 KiB
Go

package harness
import (
"fmt"
"math/rand"
"net"
"sync"
"testing"
"github.com/ipfs/kubo/config"
)
type Peering struct {
From int
To int
}
var (
allocatedPorts = make(map[int]struct{})
portMutex sync.Mutex
)
func NewRandPort() int {
portMutex.Lock()
defer portMutex.Unlock()
for i := 0; i < 100; i++ {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
continue
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
if _, used := allocatedPorts[port]; !used {
allocatedPorts[port] = struct{}{}
return port
}
}
// Fallback to random port if we can't get a unique one from the OS
for i := 0; i < 1000; i++ {
port := 30000 + rand.Intn(10000)
if _, used := allocatedPorts[port]; !used {
allocatedPorts[port] = struct{}{}
return port
}
}
panic("failed to allocate unique port after 1100 attempts")
}
func CreatePeerNodes(t *testing.T, n int, peerings []Peering) (*Harness, Nodes) {
h := NewT(t)
nodes := h.NewNodes(n).Init()
nodes.ForEachPar(func(node *Node) {
node.UpdateConfig(func(cfg *config.Config) {
cfg.Routing.Type = config.NewOptionalString("none")
cfg.Addresses.Swarm = []string{fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", NewRandPort())}
})
})
for _, peering := range peerings {
nodes[peering.From].PeerWith(nodes[peering.To])
}
return h, nodes
}