dial_test.go 11 KB
Newer Older
1
2
3
4
package swarm

import (
	"net"
Jeromy's avatar
Jeromy committed
5
	"sort"
6
7
8
9
	"sync"
	"testing"
	"time"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
11
	addrutil "github.com/ipfs/go-libp2p/p2p/net/swarm/addr"
	peer "github.com/ipfs/go-libp2p/p2p/peer"
12

Jeromy's avatar
Jeromy committed
13
14
	testutil "github.com/ipfs/go-libp2p/testutil"
	ci "github.com/ipfs/go-libp2p/testutil/ci"
15

Jeromy's avatar
Jeromy committed
16
17
18
	ma "gx/ipfs/QmR3JkmZBKYXgNMNsNZawm914455Qof3PEopwuVSeXG7aV/go-multiaddr"
	manet "gx/ipfs/QmYtzQmUwPFGxjCXctJ8e6GXS8sYfoXy2pdeMbS5SFWqRi/go-multiaddr-net"
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
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
)

func acceptAndHang(l net.Listener) {
	conns := make([]net.Conn, 0, 10)
	for {
		c, err := l.Accept()
		if err != nil {
			break
		}
		if c != nil {
			conns = append(conns, c)
		}
	}
	for _, c := range conns {
		c.Close()
	}
}

func TestSimultDials(t *testing.T) {
	// t.Skip("skipping for another test")
	t.Parallel()

	ctx := context.Background()
	swarms := makeSwarms(ctx, t, 2)

	// connect everyone
	{
		var wg sync.WaitGroup
		connect := func(s *Swarm, dst peer.ID, addr ma.Multiaddr) {
			// copy for other peer
			log.Debugf("TestSimultOpen: connecting: %s --> %s (%s)", s.local, dst, addr)
50
			s.peers.AddAddr(dst, addr, peer.TempAddrTTL)
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
			if _, err := s.Dial(ctx, dst); err != nil {
				t.Fatal("error swarm dialing to peer", err)
			}
			wg.Done()
		}

		ifaceAddrs0, err := swarms[0].InterfaceListenAddresses()
		if err != nil {
			t.Fatal(err)
		}
		ifaceAddrs1, err := swarms[1].InterfaceListenAddresses()
		if err != nil {
			t.Fatal(err)
		}

		log.Info("Connecting swarms simultaneously.")
		for i := 0; i < 10; i++ { // connect 10x for each.
			wg.Add(2)
			go connect(swarms[0], swarms[1].local, ifaceAddrs1[0])
			go connect(swarms[1], swarms[0].local, ifaceAddrs0[0])
		}
		wg.Wait()
	}

	// should still just have 1, at most 2 connections :)
	c01l := len(swarms[0].ConnectionsToPeer(swarms[1].local))
	if c01l > 2 {
		t.Error("0->1 has", c01l)
	}
	c10l := len(swarms[1].ConnectionsToPeer(swarms[0].local))
	if c10l > 2 {
		t.Error("1->0 has", c10l)
	}

	for _, s := range swarms {
		s.Close()
	}
}

func newSilentPeer(t *testing.T) (peer.ID, ma.Multiaddr, net.Listener) {
	dst := testutil.RandPeerIDFatal(t)
	lst, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatal(err)
	}
	addr, err := manet.FromNetAddr(lst.Addr())
	if err != nil {
		t.Fatal(err)
	}
	addrs := []ma.Multiaddr{addr}
	addrs, err = addrutil.ResolveUnspecifiedAddresses(addrs, nil)
	if err != nil {
		t.Fatal(err)
	}
	t.Log("new silent peer:", dst, addrs[0])
	return dst, addrs[0], lst
}

func TestDialWait(t *testing.T) {
	// t.Skip("skipping for another test")
	t.Parallel()

	ctx := context.Background()
	swarms := makeSwarms(ctx, t, 1)
	s1 := swarms[0]
	defer s1.Close()

	s1.dialT = time.Millisecond * 300 // lower timeout for tests.
119
	if ci.IsRunning() {
120
121
		s1.dialT = time.Second
	}
122
123
124
125
126

	// dial to a non-existent peer.
	s2p, s2addr, s2l := newSilentPeer(t)
	go acceptAndHang(s2l)
	defer s2l.Close()
127
	s1.peers.AddAddr(s2p, s2addr, peer.PermanentAddrTTL)
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

	before := time.Now()
	if c, err := s1.Dial(ctx, s2p); err == nil {
		defer c.Close()
		t.Fatal("error swarm dialing to unknown peer worked...", err)
	} else {
		t.Log("correctly got error:", err)
	}
	duration := time.Now().Sub(before)

	dt := s1.dialT
	if duration < dt*dialAttempts {
		t.Error("< DialTimeout * dialAttempts not being respected", duration, dt*dialAttempts)
	}
	if duration > 2*dt*dialAttempts {
		t.Error("> 2*DialTimeout * dialAttempts not being respected", duration, 2*dt*dialAttempts)
	}

	if !s1.backf.Backoff(s2p) {
		t.Error("s2 should now be on backoff")
	}
}

func TestDialBackoff(t *testing.T) {
	// t.Skip("skipping for another test")
153
	if ci.IsRunning() {
154
		t.Skip("travis and jenkins will never have fun with this test")
155
156
	}

157
158
159
160
161
162
163
164
165
	t.Parallel()

	ctx := context.Background()
	swarms := makeSwarms(ctx, t, 2)
	s1 := swarms[0]
	s2 := swarms[1]
	defer s1.Close()
	defer s2.Close()

166
167
	s1.dialT = time.Second // lower timeout for tests.
	s2.dialT = time.Second // lower timeout for tests.
168
169
170
171
172

	s2addrs, err := s2.InterfaceListenAddresses()
	if err != nil {
		t.Fatal(err)
	}
173
	s1.peers.AddAddrs(s2.local, s2addrs, peer.PermanentAddrTTL)
174
175
176
177
178

	// dial to a non-existent peer.
	s3p, s3addr, s3l := newSilentPeer(t)
	go acceptAndHang(s3l)
	defer s3l.Close()
179
	s1.peers.AddAddr(s3p, s3addr, peer.PermanentAddrTTL)
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

	// in this test we will:
	//   1) dial 10x to each node.
	//   2) all dials should hang
	//   3) s1->s2 should succeed.
	//   4) s1->s3 should not (and should place s3 on backoff)
	//   5) disconnect entirely
	//   6) dial 10x to each node again
	//   7) s3 dials should all return immediately (except 1)
	//   8) s2 dials should all hang, and succeed
	//   9) last s3 dial ends, unsuccessful

	dialOnlineNode := func(dst peer.ID, times int) <-chan bool {
		ch := make(chan bool)
		for i := 0; i < times; i++ {
			go func() {
				if _, err := s1.Dial(ctx, dst); err != nil {
					t.Error("error dialing", dst, err)
					ch <- false
				} else {
					ch <- true
				}
			}()
		}
		return ch
	}

	dialOfflineNode := func(dst peer.ID, times int) <-chan bool {
		ch := make(chan bool)
		for i := 0; i < times; i++ {
			go func() {
				if c, err := s1.Dial(ctx, dst); err != nil {
					ch <- false
				} else {
					t.Error("succeeded in dialing", dst)
					ch <- true
					c.Close()
				}
			}()
		}
		return ch
	}

	{
		// 1) dial 10x to each node.
		N := 10
		s2done := dialOnlineNode(s2.local, N)
		s3done := dialOfflineNode(s3p, N)

		// when all dials should be done by:
		dialTimeout1x := time.After(s1.dialT)
231
232
		// dialTimeout1Ax := time.After(s1.dialT * 2)       // dialAttempts)
		dialTimeout10Ax := time.After(s1.dialT * 2 * 10) // dialAttempts * 10)
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

		// 2) all dials should hang
		select {
		case <-s2done:
			t.Error("s2 should not happen immediately")
		case <-s3done:
			t.Error("s3 should not happen yet")
		case <-time.After(time.Millisecond):
			// s2 may finish very quickly, so let's get out.
		}

		// 3) s1->s2 should succeed.
		for i := 0; i < N; i++ {
			select {
			case r := <-s2done:
				if !r {
					t.Error("s2 should not fail")
				}
			case <-s3done:
				t.Error("s3 should not happen yet")
			case <-dialTimeout1x:
				t.Error("s2 took too long")
			}
		}

		select {
		case <-s2done:
			t.Error("s2 should have no more")
		case <-s3done:
			t.Error("s3 should not happen yet")
		case <-dialTimeout1x: // let it pass
		}

		// 4) s1->s3 should not (and should place s3 on backoff)
267
		// N-1 should finish before dialTimeout1x * 2
268
269
270
271
272
273
274
275
		for i := 0; i < N; i++ {
			select {
			case <-s2done:
				t.Error("s2 should have no more")
			case r := <-s3done:
				if r {
					t.Error("s3 should not succeed")
				}
276
			case <-(dialTimeout1x):
277
278
279
				if i < (N - 1) {
					t.Fatal("s3 took too long")
				}
280
				t.Log("dialTimeout1x * 1.3 hit for last peer")
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
			case <-dialTimeout10Ax:
				t.Fatal("s3 took too long")
			}
		}

		// check backoff state
		if s1.backf.Backoff(s2.local) {
			t.Error("s2 should not be on backoff")
		}
		if !s1.backf.Backoff(s3p) {
			t.Error("s3 should be on backoff")
		}

		// 5) disconnect entirely

		for _, c := range s1.Connections() {
			c.Close()
		}
		for i := 0; i < 100 && len(s1.Connections()) > 0; i++ {
			<-time.After(time.Millisecond)
		}
		if len(s1.Connections()) > 0 {
			t.Fatal("s1 conns must exit")
		}
	}

	{
		// 6) dial 10x to each node again
		N := 10
		s2done := dialOnlineNode(s2.local, N)
		s3done := dialOfflineNode(s3p, N)

		// when all dials should be done by:
		dialTimeout1x := time.After(s1.dialT)
315
316
		// dialTimeout1Ax := time.After(s1.dialT * 2)       // dialAttempts)
		dialTimeout10Ax := time.After(s1.dialT * 2 * 10) // dialAttempts * 10)
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339

		// 7) s3 dials should all return immediately (except 1)
		for i := 0; i < N-1; i++ {
			select {
			case <-s2done:
				t.Error("s2 should not succeed yet")
			case r := <-s3done:
				if r {
					t.Error("s3 should not succeed")
				}
			case <-dialTimeout1x:
				t.Fatal("s3 took too long")
			}
		}

		// 8) s2 dials should all hang, and succeed
		for i := 0; i < N; i++ {
			select {
			case r := <-s2done:
				if !r {
					t.Error("s2 should succeed")
				}
			// case <-s3done:
340
			case <-(dialTimeout1x):
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
375
376
377
378
379
				t.Fatal("s3 took too long")
			}
		}

		// 9) the last s3 should return, failed.
		select {
		case <-s2done:
			t.Error("s2 should have no more")
		case r := <-s3done:
			if r {
				t.Error("s3 should not succeed")
			}
		case <-dialTimeout10Ax:
			t.Fatal("s3 took too long")
		}

		// check backoff state (the same)
		if s1.backf.Backoff(s2.local) {
			t.Error("s2 should not be on backoff")
		}
		if !s1.backf.Backoff(s3p) {
			t.Error("s3 should be on backoff")
		}

	}
}

func TestDialBackoffClears(t *testing.T) {
	// t.Skip("skipping for another test")
	t.Parallel()

	ctx := context.Background()
	swarms := makeSwarms(ctx, t, 2)
	s1 := swarms[0]
	s2 := swarms[1]
	defer s1.Close()
	defer s2.Close()
	s1.dialT = time.Millisecond * 300 // lower timeout for tests.
	s2.dialT = time.Millisecond * 300 // lower timeout for tests.
380
381
382
	if ci.IsRunning() {
		s1.dialT = 2 * time.Second
		s2.dialT = 2 * time.Second
383
	}
384
385
386
387
388
389
390

	// use another address first, that accept and hang on conns
	_, s2bad, s2l := newSilentPeer(t)
	go acceptAndHang(s2l)
	defer s2l.Close()

	// phase 1 -- dial to non-operational addresses
391
	s1.peers.AddAddr(s2.local, s2bad, peer.PermanentAddrTTL)
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

	before := time.Now()
	if c, err := s1.Dial(ctx, s2.local); err == nil {
		t.Fatal("dialing to broken addr worked...", err)
		defer c.Close()
	} else {
		t.Log("correctly got error:", err)
	}
	duration := time.Now().Sub(before)

	dt := s1.dialT
	if duration < dt*dialAttempts {
		t.Error("< DialTimeout * dialAttempts not being respected", duration, dt*dialAttempts)
	}
	if duration > 2*dt*dialAttempts {
		t.Error("> 2*DialTimeout * dialAttempts not being respected", duration, 2*dt*dialAttempts)
	}

	if !s1.backf.Backoff(s2.local) {
		t.Error("s2 should now be on backoff")
	} else {
		t.Log("correctly added to backoff")
	}

	// phase 2 -- add the working address. dial should succeed.
	ifaceAddrs1, err := swarms[1].InterfaceListenAddresses()
	if err != nil {
		t.Fatal(err)
	}
421
	s1.peers.AddAddrs(s2.local, ifaceAddrs1, peer.PermanentAddrTTL)
422

Jeromy's avatar
Jeromy committed
423
424
425
426
427
428
	if _, err := s1.Dial(ctx, s2.local); err == nil {
		t.Fatal("should have failed to dial backed off peer")
	}

	time.Sleep(baseBackoffTime)

429
430
431
432
433
434
435
436
437
438
439
440
441
	if c, err := s1.Dial(ctx, s2.local); err != nil {
		t.Fatal(err)
	} else {
		c.Close()
		t.Log("correctly connected")
	}

	if s1.backf.Backoff(s2.local) {
		t.Error("s2 should no longer be on backoff")
	} else {
		t.Log("correctly cleared backoff")
	}
}
Jeromy's avatar
Jeromy committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476

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

	return a
}

func TestAddressSorting(t *testing.T) {
	u1 := mkAddr(t, "/ip4/152.12.23.53/udp/1234/utp")
	u2l := mkAddr(t, "/ip4/127.0.0.1/udp/1234/utp")
	local := mkAddr(t, "/ip4/127.0.0.1/tcp/1234")
	norm := mkAddr(t, "/ip4/6.5.4.3/tcp/1234")

	l := AddrList{local, u1, u2l, norm}
	sort.Sort(l)

	if !l[0].Equal(u2l) {
		t.Fatal("expected utp local addr to be sorted first: ", l[0])
	}

	if !l[1].Equal(u1) {
		t.Fatal("expected utp addr to be sorted second")
	}

	if !l[2].Equal(local) {
		t.Fatal("expected tcp localhost addr thid")
	}

	if !l[3].Equal(norm) {
		t.Fatal("expected normal addr last")
	}
}