-
Notifications
You must be signed in to change notification settings - Fork 211
/
integration_suite.go
245 lines (215 loc) · 6.39 KB
/
integration_suite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package p2p
import (
"context"
"fmt"
"net"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"golang.org/x/sync/errgroup"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/p2p/config"
"github.com/spacemeshos/go-spacemesh/p2p/node"
)
// NodeTestInstance is an instance of a p2p node for testing
type NodeTestInstance interface {
Service
LocalNode() node.LocalNode // this holds the keys
}
// IntegrationTestSuite is a suite which bootstraps a network according to the given params
// and lets you run actions on this network.
// You must set the params before running the suite.
type IntegrationTestSuite struct {
suite.Suite
BootstrapNodesCount int
BootstrappedNodeCount int
NeighborsCount int
BeforeHook func(idx int, s NodeTestInstance)
AfterHook func(idx int, s NodeTestInstance)
boot []*Switch
Instances []*Switch
}
// SetupSuite setups the configured nodes, bootstraps and connects them.
func (its *IntegrationTestSuite) SetupSuite() {
boot := make([]*Switch, its.BootstrapNodesCount)
swarm := make([]*Switch, its.BootstrappedNodeCount)
bootcfg := config.DefaultConfig()
bootcfg.SwarmConfig.Bootstrap = false
bootcfg.SwarmConfig.Gossip = true
bootcfg.SwarmConfig.RandomConnections = its.NeighborsCount
// start boot
for i := 0; i < len(boot); i++ {
boot[i] = createP2pInstance(its.T(), bootcfg)
if its.BeforeHook != nil {
its.BeforeHook(i, boot[i])
}
_ = boot[i].Start() // ignore error ?
if its.AfterHook != nil {
its.AfterHook(i, boot[i])
}
testLog("BOOTNODE : %v", boot[i].LocalNode().PublicKey().String())
}
for i := 0; i < len(boot); i++ {
for j := 0; j < len(boot); j++ {
if j == i {
continue
}
udpAddr := boot[j].udpnetwork.LocalAddr().(*net.UDPAddr)
tcpAddr := boot[j].network.LocalAddr().(*net.TCPAddr)
pk := boot[j].lNode.PublicKey()
info := node.NewNode(pk, tcpAddr.IP, uint16(tcpAddr.Port), uint16(udpAddr.Port))
boot[i].discover.Update(info, info)
}
}
cfg := config.DefaultConfig()
cfg.AcquirePort = false
cfg.SwarmConfig.Bootstrap = true
cfg.SwarmConfig.Gossip = true
cfg.SwarmConfig.RandomConnections = its.NeighborsCount
cfg.SwarmConfig.BootstrapNodes = StringIdentifiers(boot...)
tm := time.Now()
testLog("Started up %d swarms", its.BootstrappedNodeCount)
//var wg sync.WaitGroup
totalTimeout := time.NewTimer((time.Second * 5) * time.Duration(len(swarm)))
finchan := make(chan error)
for i := 0; i < len(swarm); i++ {
swarm[i] = createP2pInstance(its.T(), cfg)
i := i
// wg.Add(1)
go func() {
// we add a timeout before starting to reduce the possibility or trying to connect at the same time
// pretty rare occasion in real life (which we handle anyway), but happens a lot when running everything in 1 binary.
time.Sleep(time.Duration(i) * 50 * time.Millisecond)
if its.BeforeHook != nil {
its.BeforeHook(i, swarm[i])
}
err := swarm[i].Start() // ignore error?
if err != nil {
finchan <- err
return
//its.T().Fatal(fmt.Sprintf("failed to start a node, %v", err))
}
err = swarm[i].waitForBoot()
if err != nil {
finchan <- err
return
}
if its.AfterHook != nil {
its.AfterHook(i, swarm[i])
}
finchan <- nil
}()
}
testLog("Launched all processes 🎉, now waiting...")
i := 0
lop:
for {
select {
case err := <-finchan:
i++
if err != nil {
its.T().Fatal(err)
}
if i == len(swarm) {
break lop
}
case <-totalTimeout.C:
its.T().Fatal("timeout")
}
}
testLog("Took %s for all swarms to boot up", time.Since(tm))
// go interfaces suck with slices
its.Instances = swarm
its.boot = boot
}
// TearDownSuite shutdowns all nodes.
func (its *IntegrationTestSuite) TearDownSuite() {
testLog("Shutting down all nodes" + its.T().Name())
_ = its.ForAll(func(idx int, s NodeTestInstance) error {
s.Shutdown()
return nil
}, nil)
}
func createP2pInstance(t testing.TB, config config.Config) *Switch {
config.TCPPort = 0
config.AcquirePort = false
p, err := newSwarm(context.TODO(), config, log.NewDefault("test instance"), "")
require.NoError(t, err)
require.NotNil(t, p)
return p
}
// WaitForGossip waits that all nodes initialized gossip connections
func (its *IntegrationTestSuite) WaitForGossip(ctx context.Context) error {
g, _ := errgroup.WithContext(ctx)
for _, b := range its.boot {
g.Go(func() error {
return b.waitForGossip()
})
}
for _, i := range its.Instances {
g.Go(func() error {
return i.waitForGossip()
})
}
return g.Wait()
}
// ForAll executes f on all the node and returns error if it failed
func (its *IntegrationTestSuite) ForAll(f func(idx int, s NodeTestInstance) error, filter []int) []error {
e := make([]error, 0)
swarms:
for i, s := range its.Instances {
for _, j := range filter {
if j == i {
continue swarms
}
}
e = append(e, f(i, s))
}
boots:
for i, s := range its.boot {
for _, j := range filter {
if j == i {
continue boots
}
}
e = append(e, f(i, s))
}
return e
}
// ForAllAsync executes f on all the nodes concurrently, it stops if ctx is cancelled.
func (its *IntegrationTestSuite) ForAllAsync(ctx context.Context, f func(idx int, s NodeTestInstance) error) ([]error, error) {
var mtx sync.Mutex
errs := make([]error, len(its.Instances))
group, _ := errgroup.WithContext(ctx)
for i, s := range its.Instances {
i, s := i, s
group.Go(func() error {
e := f(i, s)
mtx.Lock()
errs[i] = e
mtx.Unlock()
return e
})
}
return errs, group.Wait()
}
func testLog(text string, args ...interface{}) {
fmt.Println("################################################################################################")
fmt.Println("Test Logger :")
fmt.Println(fmt.Sprintf(text, args...))
fmt.Println("################################################################################################")
}
// StringIdentifiers turns Switch into string representation node for use as bootnodes.
func StringIdentifiers(boot ...*Switch) []string {
s := make([]string, len(boot))
for i := 0; i < len(s); i++ {
pk := boot[i].LocalNode().PublicKey()
tcp := boot[i].network.LocalAddr().(*net.TCPAddr)
udp := boot[i].udpnetwork.LocalAddr().(*net.UDPAddr)
nodeinfo := node.NewNode(pk, net.IPv6loopback, uint16(tcp.Port), uint16(udp.Port))
s[i] = nodeinfo.String() //node.StringFromNode(node.New(boot[i].LocalNode().Node.PublicKey(), boot[i].udpnetwork.LocalAddr().String())) )
}
return s
}