master
go 68 lines 1.29 KB
Raw
1 package harness
2
3 import (
4 "fmt"
5 "math/rand"
6 "net"
7 "sync"
8 "testing"
9
10 "github.com/ipfs/kubo/config"
11 )
12
13 type Peering struct {
14 From int
15 To int
16 }
17
18 var (
19 allocatedPorts = make(map[int]struct{})
20 portMutex sync.Mutex
21 )
22
23 func NewRandPort() int {
24 portMutex.Lock()
25 defer portMutex.Unlock()
26
27 for range 100 {
28 l, err := net.Listen("tcp", "localhost:0")
29 if err != nil {
30 continue
31 }
32 port := l.Addr().(*net.TCPAddr).Port
33 l.Close()
34
35 if _, used := allocatedPorts[port]; !used {
36 allocatedPorts[port] = struct{}{}
37 return port
38 }
39 }
40
41 // Fallback to random port if we can't get a unique one from the OS
42 for range 1000 {
43 port := 30000 + rand.Intn(10000)
44 if _, used := allocatedPorts[port]; !used {
45 allocatedPorts[port] = struct{}{}
46 return port
47 }
48 }
49
50 panic("failed to allocate unique port after 1100 attempts")
51 }
52
53 func CreatePeerNodes(t *testing.T, n int, peerings []Peering) (*Harness, Nodes) {
54 h := NewT(t)
55 nodes := h.NewNodes(n).Init()
56 nodes.ForEachPar(func(node *Node) {
57 node.UpdateConfig(func(cfg *config.Config) {
58 cfg.Routing.Type = config.NewOptionalString("none")
59 cfg.Addresses.Swarm = []string{fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", NewRandPort())}
60 })
61 })
62
63 for _, peering := range peerings {
64 nodes[peering.From].PeerWith(nodes[peering.To])
65 }
66
67 return h, nodes
68 }