limiter_test.go 7.12 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
2
3
package swarm

import (
4
	"context"
Jeromy's avatar
Jeromy committed
5
	"fmt"
Jeromy's avatar
Jeromy committed
6
	"math/rand"
Jeromy's avatar
Jeromy committed
7
8
9
10
	"strconv"
	"testing"
	"time"

11
	iconn "github.com/libp2p/go-libp2p-interface-conn"
Jeromy's avatar
Jeromy committed
12
13
	peer "github.com/libp2p/go-libp2p-peer"
	ma "github.com/multiformats/go-multiaddr"
Jeromy's avatar
Jeromy committed
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
	mafmt "github.com/whyrusleeping/mafmt"
)

func mustAddr(t *testing.T, s string) ma.Multiaddr {
	a, err := ma.NewMultiaddr(s)
	if err != nil {
		t.Fatal(err)
	}
	return a
}

func addrWithPort(t *testing.T, p int) ma.Multiaddr {
	return mustAddr(t, fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", p))
}

// in these tests I use addresses with tcp ports over a certain number to
// signify 'good' addresses that will succeed, and addresses below that number
// will fail. This lets us more easily test these different scenarios.
func tcpPortOver(a ma.Multiaddr, n int) bool {
	port, err := a.ValueForProtocol(ma.P_TCP)
	if err != nil {
		panic(err)
	}

	pnum, err := strconv.Atoi(port)
	if err != nil {
		panic(err)
	}

	return pnum > n
}

func tryDialAddrs(ctx context.Context, l *dialLimiter, p peer.ID, addrs []ma.Multiaddr, res chan dialResult) {
	for _, a := range addrs {
		l.AddDialJob(&dialJob{
			ctx:  ctx,
			peer: p,
			addr: a,
			resp: res,
		})
	}
}

func hangDialFunc(hang chan struct{}) dialfunc {
58
	return func(ctx context.Context, p peer.ID, a ma.Multiaddr) (iconn.Conn, error) {
Jeromy's avatar
Jeromy committed
59
		if mafmt.UTP.Matches(a) {
60
			return iconn.Conn(nil), nil
Jeromy's avatar
Jeromy committed
61
62
63
		}

		if tcpPortOver(a, 10) {
64
			return iconn.Conn(nil), nil
Jeromy's avatar
Jeromy committed
65
		}
66
67
68

		<-hang
		return nil, fmt.Errorf("test bad dial")
Jeromy's avatar
Jeromy committed
69
70
71
72
73
74
75
76
77
	}
}

func TestLimiterBasicDials(t *testing.T) {
	hang := make(chan struct{})
	defer close(hang)

	l := newDialLimiterWithParams(hangDialFunc(hang), concurrentFdDials, 4)

Jeromy's avatar
Jeromy committed
78
	bads := []ma.Multiaddr{addrWithPort(t, 1), addrWithPort(t, 2), addrWithPort(t, 3), addrWithPort(t, 4)}
Jeromy's avatar
Jeromy committed
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
	good := addrWithPort(t, 20)

	resch := make(chan dialResult)
	pid := peer.ID("testpeer")
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	tryDialAddrs(ctx, l, pid, bads, resch)

	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pid,
		addr: good,
		resp: resch,
	})

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// complete a single hung dial
	hang <- struct{}{}

	select {
	case r := <-resch:
		if r.Err == nil {
			t.Fatal("should have gotten failed dial result")
		}
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for dial completion")
	}

	select {
	case r := <-resch:
		if r.Err != nil {
			t.Fatal("expected second result to be success!")
		}
	case <-time.After(time.Second):
	}
}

func TestFDLimiting(t *testing.T) {
	hang := make(chan struct{})
	defer close(hang)
	l := newDialLimiterWithParams(hangDialFunc(hang), 16, 5)

	bads := []ma.Multiaddr{addrWithPort(t, 1), addrWithPort(t, 2), addrWithPort(t, 3), addrWithPort(t, 4)}
	pids := []peer.ID{"testpeer1", "testpeer2", "testpeer3", "testpeer4"}
129
	goodTCP := addrWithPort(t, 20)
Jeromy's avatar
Jeromy committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

	ctx := context.Background()
	resch := make(chan dialResult)

	// take all fd limit tokens with hang dials
	for _, pid := range pids {
		tryDialAddrs(ctx, l, pid, bads, resch)
	}

	// these dials should work normally, but will hang because we have taken
	// up all the fd limiting
	for _, pid := range pids {
		l.AddDialJob(&dialJob{
			ctx:  ctx,
			peer: pid,
145
			addr: goodTCP,
Jeromy's avatar
Jeromy committed
146
147
148
149
150
151
152
153
154
155
156
157
158
			resp: resch,
		})
	}

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	pid5 := peer.ID("testpeer5")
	utpaddr := mustAddr(t, "/ip4/127.0.0.1/udp/7777/utp")

Jeromy's avatar
Jeromy committed
159
	// This should complete immediately since utp addresses arent blocked by fd rate limiting
Jeromy's avatar
Jeromy committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
	l.AddDialJob(&dialJob{ctx: ctx, peer: pid5, addr: utpaddr, resp: resch})

	select {
	case res := <-resch:
		if res.Err != nil {
			t.Fatal("should have gotten successful response")
		}
	case <-time.After(time.Second * 5):
		t.Fatal("timeout waiting for utp addr success")
	}
}

func TestTokenRedistribution(t *testing.T) {
	hangchs := make(map[peer.ID]chan struct{})
174
	df := func(ctx context.Context, p peer.ID, a ma.Multiaddr) (iconn.Conn, error) {
Jeromy's avatar
Jeromy committed
175
		if tcpPortOver(a, 10) {
176
			return (iconn.Conn)(nil), nil
Jeromy's avatar
Jeromy committed
177
		}
178
179
180

		<-hangchs[p]
		return nil, fmt.Errorf("test bad dial")
Jeromy's avatar
Jeromy committed
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
	}
	l := newDialLimiterWithParams(df, 8, 4)

	bads := []ma.Multiaddr{addrWithPort(t, 1), addrWithPort(t, 2), addrWithPort(t, 3), addrWithPort(t, 4)}
	pids := []peer.ID{"testpeer1", "testpeer2"}

	ctx := context.Background()
	resch := make(chan dialResult)

	// take all fd limit tokens with hang dials
	for _, pid := range pids {
		hangchs[pid] = make(chan struct{})
		tryDialAddrs(ctx, l, pid, bads, resch)
	}

	good := mustAddr(t, "/ip4/127.0.0.1/tcp/1001")

	// add a good dial job for peer 1
	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pids[1],
		addr: good,
		resp: resch,
	})

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// unblock one dial for peer 0
	hangchs[pids[0]] <- struct{}{}

	select {
	case res := <-resch:
		if res.Err == nil {
			t.Fatal("should have only been a failure here")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("expected a dial failure here")
	}

	select {
	case <-resch:
		t.Fatal("no more dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// add a bad dial job to peer 0 to fill their rate limiter
	// and test that more dials for this peer won't interfere with peer 1's successful dial incoming
	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pids[0],
		addr: addrWithPort(t, 7),
		resp: resch,
	})

	hangchs[pids[1]] <- struct{}{}

	// now one failed dial from peer 1 should get through and fail
	// which will in turn unblock the successful dial on peer 1
	select {
	case res := <-resch:
		if res.Err == nil {
			t.Fatal("should have only been a failure here")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("expected a dial failure here")
	}

	select {
	case res := <-resch:
		if res.Err != nil {
			t.Fatal("should have succeeded!")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("should have gotten successful dial")
	}
}
Jeromy's avatar
Jeromy committed
261
262

func TestStressLimiter(t *testing.T) {
263
	df := func(ctx context.Context, p peer.ID, a ma.Multiaddr) (iconn.Conn, error) {
Jeromy's avatar
Jeromy committed
264
		if tcpPortOver(a, 1000) {
265
			return iconn.Conn(nil), nil
Jeromy's avatar
Jeromy committed
266
		}
267
268
269

		time.Sleep(time.Millisecond * time.Duration(5+rand.Intn(100)))
		return nil, fmt.Errorf("test bad dial")
Jeromy's avatar
Jeromy committed
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
	}

	l := newDialLimiterWithParams(df, 20, 5)

	var bads []ma.Multiaddr
	for i := 0; i < 100; i++ {
		bads = append(bads, addrWithPort(t, i))
	}

	addresses := append(bads, addrWithPort(t, 2000))
	success := make(chan struct{})

	for i := 0; i < 20; i++ {
		go func(id peer.ID) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			resp := make(chan dialResult)
			time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
			for _, i := range rand.Perm(len(addresses)) {
				l.AddDialJob(&dialJob{
					addr: addresses[i],
					ctx:  ctx,
					peer: id,
					resp: resp,
				})
			}

			for res := range resp {
				if res.Err == nil {
					success <- struct{}{}
					return
				}
			}
		}(peer.ID(fmt.Sprintf("testpeer%d", i)))
	}

	for i := 0; i < 20; i++ {
		select {
		case <-success:
		case <-time.After(time.Second * 5):
			t.Fatal("expected a success within five seconds")
		}
	}
}