forked from uber/ringpop-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.go
374 lines (317 loc) · 10.3 KB
/
test_utils.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package swim
import (
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/benbjohnson/clock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/uber/ringpop-go/discovery/statichosts"
"github.com/uber/ringpop-go/events"
"github.com/uber/ringpop-go/shared"
"github.com/uber/ringpop-go/util"
"github.com/uber/tchannel-go"
)
var testNow = time.Now()
var testInc = util.TimeNowMS()
var testSuspect = Change{
Address: "127.0.0.1:3002",
Incarnation: testInc,
Source: "127.0.0.1:3001",
SourceIncarnation: testInc,
Status: Suspect,
Timestamp: util.Timestamp(testNow),
}
type dummyIter struct{}
func (dummyIter) Next() (*Member, bool) {
return &Member{
Address: "127.0.0.1:3010",
Status: Alive,
Incarnation: testInc,
}, true
}
type testNode struct {
node *Node
channel *tchannel.Channel
}
func (n *testNode) Destroy() {
n.node.Destroy()
n.channel.Close()
}
func (n *testNode) closeAndWait(sender *tchannel.Channel) {
n.channel.Close()
// wait for tchannel to respond with connection refused errors.
for {
ctx, cancel := shared.NewTChannelContext(time.Millisecond * 50)
err := sender.Ping(ctx, n.node.Address())
if err == nil {
cancel()
continue
}
_, ok := err.(tchannel.SystemError)
if ok {
cancel()
continue
}
cancel()
break
}
}
// newChannelNode creates a testNode with a listening channel and associated
// SWIM node. The channel listens on a random port assigned by the OS.
func newChannelNode(t *testing.T) *testNode {
ch, err := tchannel.NewChannel("test", nil)
require.NoError(t, err, "channel must create successfully")
// Set the channel listening so it binds to the socket and we get a port
// allocated by the OS
err = ch.ListenAndServe("127.0.0.1:0")
require.NoError(t, err, "channel must listen")
hostport := ch.PeerInfo().HostPort
node := NewNode("test", hostport, ch.GetSubChannel("test"), &Options{
Clock: clock.NewMock(),
})
return &testNode{node, ch}
}
// newChannelNodeWithHostPort creates a testNode with the address specified by
// the hostport parameter.
func newChannelNodeWithHostPort(t *testing.T, hostport string) *testNode {
ch, err := tchannel.NewChannel("test", nil)
require.NoError(t, err, "channel must create successfully")
node := NewNode("test", hostport, ch.GetSubChannel("test"), &Options{
Clock: clock.NewMock(),
})
return &testNode{node, ch}
}
func genChannelNodes(t *testing.T, n int) (nodes []*testNode) {
for i := 0; i < n; i++ {
node := newChannelNode(t)
nodes = append(nodes, node)
}
return
}
func memberlistHasMembers(t *testing.T, m *memberlist, members []Member) {
for _, expected := range members {
member, ok := m.Member(expected.Address)
assert.True(t, ok, "expected member to be in memberlist")
require.NotNil(t, member, "member cannot be nil")
assert.Equal(t, expected.Status, member.Status, "expected statuses to be the same")
}
}
func bootstrapNodes(t *testing.T, testNodes ...*testNode) []string {
var hostports []string
for _, tn := range testNodes {
hostports = append(hostports, tn.node.Address())
_, err := tn.node.Bootstrap(&BootstrapOptions{
DiscoverProvider: statichosts.New(hostports...),
Stopped: true,
})
require.NoError(t, err, "node must bootstrap successfully")
}
return hostports
}
// waitForConvergence lets the nodes gossip and returns when the nodes are converged.
// After the cluster finished gossiping we double check that all nodes have the
// same checksum for the memberlist, this means that the cluster is converged.
func waitForConvergence(t *testing.T, timeout time.Duration, testNodes ...*testNode) {
deadline := time.Now().Add(timeout)
nodes := testNodesToNodes(testNodes)
// 1 node is a special case because it can't drain its changes since it
// cannot ping or be pinged by another member
if len(nodes) == 1 {
nodes[0].disseminator.ClearChanges()
return
}
Tick:
// return when deadline is reached
if time.Now().After(deadline) {
t.Errorf("timeout during wait for convergence")
return
}
// tick all the nodes
for _, node := range nodes {
node.gossip.ProtocolPeriod()
}
// repeat if we stil have changes
for _, node := range nodes {
if node.HasChanges() {
goto Tick
}
}
// check for convergence if there are no changes left
if !nodesConverged(nodes) {
t.Errorf("nodes did not converge to 1 checksum")
}
}
func destroyNodes(tnodes ...*testNode) {
for _, tnode := range tnodes {
tnode.Destroy()
}
}
// fakeAddresses returns a slice of fake IP address/port combinations that can
// be used during testing. Note that these addresses cannot be used in tests
// which require real communication or binding to a socket.
//
// The IP addresses returned are from the TEST-NET-1 block which are defined in
// RFC 5737 as to be used for documentation and recommended to be unrouteable.
// In practice, these addresses may also just time out.
//
// See:
// http://tools.ietf.org/html/rfc5737
// http://stackoverflow.com/questions/10456044/what-is-a-good-invalid-ip-address-to-use-for-unit-tests
//
func fakeHostPorts(fromHost, toHost, fromPort, toPort int) []string {
var hostports []string
for h := fromHost; h <= toHost; h++ {
for p := fromPort; p <= toPort; p++ {
hostports = append(hostports, fmt.Sprintf("192.0.2.%v:%v", h, p))
}
}
return hostports
}
// swimCluster is a group of real swim nodes listening on randomly-assigned
// ports.
type swimCluster struct {
nodes []*Node
channels []*tchannel.Channel
}
// newSwimCluster creates a new swimCluster with the number of nodes specified
// by size. These nodes are not joined together at creation. Use Bootstrap if you
// need a bootstrapped cluster.
func newSwimCluster(size int) *swimCluster {
var nodes []*Node
var channels []*tchannel.Channel
for i := 0; i < size; i++ {
ch, err := tchannel.NewChannel("test", nil)
if err != nil {
panic(err)
}
if err := ch.ListenAndServe("127.0.0.1:0"); err != nil {
panic(err)
}
channels = append(channels, ch)
hostport := ch.PeerInfo().HostPort
node := NewNode("test", hostport, ch.GetSubChannel("test"), nil)
nodes = append(nodes, node)
}
return &swimCluster{nodes: nodes, channels: channels}
}
// Add adds the specified node to the cluster and bootstraps it so that it is
// joined to the existing nodes.
func (c *swimCluster) Add(n *Node) {
n.Bootstrap(&BootstrapOptions{
DiscoverProvider: statichosts.New(c.Addresses()...),
})
c.nodes = append(c.nodes, n)
}
// Addresses returns a slice of addresses of all nodes in the cluster.
func (c *swimCluster) Addresses() (hostports []string) {
for _, node := range c.nodes {
hostports = append(hostports, node.Address())
}
return
}
// Bootstrap joins all the nodes in this cluster together using Bootstrap calls.
func (c *swimCluster) Bootstrap() {
for _, node := range c.nodes {
node.Bootstrap(&BootstrapOptions{
DiscoverProvider: statichosts.New(c.Addresses()...),
})
}
}
// WaitForConvergence polls the checksums of each node in the cluster and returns when they all match, or until timeout occurs.
func (c *swimCluster) WaitForConvergence(timeout time.Duration) error {
timeoutCh := time.After(timeout)
for {
select {
case <-time.After(time.Millisecond):
if nodesConverged(c.nodes) {
return nil
}
case <-timeoutCh:
return errors.New("timeout during converging")
}
}
}
func testNodesToNodes(testNodes []*testNode) []*Node {
nodes := make([]*Node, len(testNodes))
for i, tn := range testNodes {
nodes[i] = tn.node
}
return nodes
}
func nodesConverged(nodes []*Node) bool {
if len(nodes) == 0 {
return true
}
first := nodes[0].memberlist.Checksum()
for _, node := range nodes {
if node.memberlist.Checksum() != first {
return false
}
}
return true
}
// Destroy destroys all nodes in this cluster. It also closes channels, but
// only those that were created as part of newSwimCluster.
func (c *swimCluster) Destroy() {
for _, node := range c.nodes {
node.Destroy()
}
for _, ch := range c.channels {
ch.Close()
}
}
// Nodes returns a slice of all nodes in the cluster.
func (c *swimCluster) Nodes() []*Node {
return c.nodes
}
// DoThenWaitFor executes a function and then waits for a specific type
// of event to occur. This function shouldn't be used outside tests because
// there is no way to unsubscribe the event handler.
//
// Often we want to execute some code and then wait for an event be emitted due
// to the code being executed. However in order to not miss the event we must
// first register an event handler before we can execute the code:
// - register listener that signals we can continue on receiving the correct event;
// - execute the code that will lead to an event being emitted;
// - wait for the continue signal.
//
// This can be quite hard to follow. Ideally we want it to look like
// - execute the code that will lead to an event being emitted;
// - and then wait for a specific event.
//
// This function helps with making the code read like the latter.
func DoThenWaitFor(f func(), er events.EventRegistrar, t interface{}) {
block := make(chan struct{}, 1)
var once sync.Once
er.RegisterListener(on(t, func(e events.Event) {
once.Do(func() {
block <- struct{}{}
})
}))
f()
// wait for first occurence of the event, close thereafter
<-block
close(block)
}