mock_peernet.go 9.08 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
package mocknet

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
6
7
8
	"fmt"
	"math/rand"
	"sync"

Jeromy's avatar
Jeromy committed
9
10
	"github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
Jeromy's avatar
Jeromy committed
11
	inet "github.com/libp2p/go-libp2p-net"
Jeromy's avatar
Jeromy committed
12
13
14
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	ma "github.com/multiformats/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
16
17
18
19
20
21
)

// peernet implements inet.Network
type peernet struct {
	mocknet *mocknet // parent

	peer peer.ID
Jeromy's avatar
Jeromy committed
22
	ps   pstore.Peerstore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23
24
25
26
27
28
29

	// conns are actual live connections between peers.
	// many conns could run over each link.
	// **conns are NOT shared between peers**
	connsByPeer map[peer.ID]map[*conn]struct{}
	connsByLink map[*link]map[*conn]struct{}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
31
32
	// implement inet.Network
	streamHandler inet.StreamHandler
	connHandler   inet.ConnHandler
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33

34
35
36
	notifmu sync.RWMutex
	notifs  map[inet.Notifiee]struct{}

37
	proc goprocess.Process
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
39
40
41
	sync.RWMutex
}

// newPeernet constructs a new peernet
Jeromy's avatar
Jeromy committed
42
func newPeernet(ctx context.Context, m *mocknet, p peer.ID, ps pstore.Peerstore) (*peernet, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
44
45
46
47
48
49
50

	n := &peernet{
		mocknet: m,
		peer:    p,
		ps:      ps,

		connsByPeer: map[peer.ID]map[*conn]struct{}{},
		connsByLink: map[*link]map[*conn]struct{}{},
51
52

		notifs: make(map[inet.Notifiee]struct{}),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53
54
	}

55
	n.proc = goprocessctx.WithContextAndTeardown(ctx, n.teardown)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
	return n, nil
}

func (pn *peernet) teardown() error {

	// close the connections
	for _, c := range pn.allConns() {
		c.Close()
	}
	return nil
}

// allConns returns all the connections between this peer and others
func (pn *peernet) allConns() []*conn {
	pn.RLock()
	var cs []*conn
	for _, csl := range pn.connsByPeer {
		for c := range csl {
			cs = append(cs, c)
		}
	}
	pn.RUnlock()
	return cs
}

// Close calls the ContextCloser func
func (pn *peernet) Close() error {
83
	return pn.proc.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
85
}

Jeromy's avatar
Jeromy committed
86
func (pn *peernet) Peerstore() pstore.Peerstore {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87
88
89
90
91
92
93
	return pn.ps
}

func (pn *peernet) String() string {
	return fmt.Sprintf("<mock.peernet %s - %d conns>", pn.peer, len(pn.allConns()))
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94
// handleNewStream is an internal function to trigger the client's handler
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95
func (pn *peernet) handleNewStream(s inet.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
	pn.RLock()
	handler := pn.streamHandler
	pn.RUnlock()
	if handler != nil {
		go handler(s)
	}
}

// handleNewConn is an internal function to trigger the client's handler
func (pn *peernet) handleNewConn(c inet.Conn) {
	pn.RLock()
	handler := pn.connHandler
	pn.RUnlock()
	if handler != nil {
		go handler(c)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
113
114
115
}

// DialPeer attempts to establish a connection to a given peer.
// Respects the context.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
func (pn *peernet) DialPeer(ctx context.Context, p peer.ID) (inet.Conn, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
118
119
	return pn.connect(p)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120
func (pn *peernet) connect(p peer.ID) (*conn, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
122
123
124
	// first, check if we already have live connections
	pn.RLock()
	cs, found := pn.connsByPeer[p]
	if found && len(cs) > 0 {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
125
126
127
128
		var chosen *conn
		for c := range cs { // because cs is a map
			chosen = c // select first
			break
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
130
131
		pn.RUnlock()
		return chosen, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
133
	pn.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
135
136
137
138
139

	log.Debugf("%s (newly) dialing %s", pn.peer, p)

	// ok, must create a new connection. we need a link
	links := pn.mocknet.LinksBetweenPeers(pn.peer, p)
	if len(links) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140
		return nil, fmt.Errorf("%s cannot connect to %s", pn.peer, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
142
143
144
145
146
147
148
149
	}

	// if many links found, how do we select? for now, randomly...
	// this would be an interesting place to test logic that can measure
	// links (network interfaces) and select properly
	l := links[rand.Intn(len(links))]

	log.Debugf("%s dialing %s openingConn", pn.peer, p)
	// create a new connection with link
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150
151
	c := pn.openConn(p, l.(*link))
	return c, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
153
154
155
156
157
}

func (pn *peernet) openConn(r peer.ID, l *link) *conn {
	lc, rc := l.newConnPair(pn)
	log.Debugf("%s opening connection to %s", pn.LocalPeer(), lc.RemotePeer())
	pn.addConn(lc)
158
159
160
	pn.notifyAll(func(n inet.Notifiee) {
		n.Connected(pn, lc)
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
162
163
164
165
166
167
	rc.net.remoteOpenedConn(rc)
	return lc
}

func (pn *peernet) remoteOpenedConn(c *conn) {
	log.Debugf("%s accepting connection from %s", pn.LocalPeer(), c.RemotePeer())
	pn.addConn(c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
	pn.handleNewConn(c)
169
170
171
	pn.notifyAll(func(n inet.Notifiee) {
		n.Connected(pn, c)
	})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
173
174
175
176
177
}

// addConn constructs and adds a connection
// to given remote peer over given link
func (pn *peernet) addConn(c *conn) {
	pn.Lock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178
179
	defer pn.Unlock()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
	cs, found := pn.connsByPeer[c.RemotePeer()]
	if !found {
		cs = map[*conn]struct{}{}
		pn.connsByPeer[c.RemotePeer()] = cs
	}
	pn.connsByPeer[c.RemotePeer()][c] = struct{}{}

	cs, found = pn.connsByLink[c.link]
	if !found {
		cs = map[*conn]struct{}{}
		pn.connsByLink[c.link] = cs
	}
	pn.connsByLink[c.link][c] = struct{}{}
}

// removeConn removes a given conn
func (pn *peernet) removeConn(c *conn) {
	pn.Lock()
	defer pn.Unlock()

	cs, found := pn.connsByLink[c.link]
	if !found || len(cs) < 1 {
202
		panic(fmt.Sprintf("attempting to remove a conn that doesnt exist %p", c.link))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
204
205
206
207
	}
	delete(cs, c)

	cs, found = pn.connsByPeer[c.remote]
	if !found {
208
		panic(fmt.Sprintf("attempting to remove a conn that doesnt exist %p", c.remote))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
210
211
212
	}
	delete(cs, c)
}

213
214
215
// Process returns the network's Process
func (pn *peernet) Process() goprocess.Process {
	return pn.proc
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
}

// LocalPeer the network's LocalPeer
func (pn *peernet) LocalPeer() peer.ID {
	return pn.peer
}

// Peers returns the connected peers
func (pn *peernet) Peers() []peer.ID {
	pn.RLock()
	defer pn.RUnlock()

	peers := make([]peer.ID, 0, len(pn.connsByPeer))
	for _, cs := range pn.connsByPeer {
		for c := range cs {
			peers = append(peers, c.remote)
			break
		}
	}
	return peers
}

// Conns returns all the connections of this peer
func (pn *peernet) Conns() []inet.Conn {
	pn.RLock()
	defer pn.RUnlock()

	out := make([]inet.Conn, 0, len(pn.connsByPeer))
	for _, cs := range pn.connsByPeer {
		for c := range cs {
			out = append(out, c)
		}
	}
	return out
}

func (pn *peernet) ConnsToPeer(p peer.ID) []inet.Conn {
	pn.RLock()
	defer pn.RUnlock()

	cs, found := pn.connsByPeer[p]
	if !found || len(cs) == 0 {
		return nil
	}

	var cs2 []inet.Conn
	for c := range cs {
		cs2 = append(cs2, c)
	}
	return cs2
}

// ClosePeer connections to peer
func (pn *peernet) ClosePeer(p peer.ID) error {
	pn.RLock()
	cs, found := pn.connsByPeer[p]
	if !found {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
273
		pn.RUnlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274
275
276
		return nil
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
277
	var conns []*conn
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278
	for c := range cs {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
279
280
281
282
		conns = append(conns, c)
	}
	pn.RUnlock()
	for _, c := range conns {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
284
285
286
287
288
289
290
291
292
293
294
		c.Close()
	}
	return nil
}

// BandwidthTotals returns the total amount of bandwidth transferred
func (pn *peernet) BandwidthTotals() (in uint64, out uint64) {
	// need to implement this. probably best to do it in swarm this time.
	// need a "metrics" object
	return 0, 0
}

295
296
// Listen tells the network to start listening on given multiaddrs.
func (pn *peernet) Listen(addrs ...ma.Multiaddr) error {
Jeromy's avatar
Jeromy committed
297
	pn.Peerstore().AddAddrs(pn.LocalPeer(), addrs, pstore.PermanentAddrTTL)
298
299
300
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301
302
// ListenAddresses returns a list of addresses at which this network listens.
func (pn *peernet) ListenAddresses() []ma.Multiaddr {
303
	return pn.Peerstore().Addrs(pn.LocalPeer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
}

// InterfaceListenAddresses returns a list of addresses at which this network
// listens. It expands "any interface" addresses (/ip4/0.0.0.0, /ip6/::) to
// use the known local interfaces.
func (pn *peernet) InterfaceListenAddresses() ([]ma.Multiaddr, error) {
	return pn.ListenAddresses(), nil
}

// Connectedness returns a state signaling connection capabilities
// For now only returns Connecter || NotConnected. Expand into more later.
func (pn *peernet) Connectedness(p peer.ID) inet.Connectedness {
	pn.Lock()
	defer pn.Unlock()

	cs, found := pn.connsByPeer[p]
	if found && len(cs) > 0 {
		return inet.Connected
	}
	return inet.NotConnected
}

// NewStream returns a new stream to given peer p.
// If there is no connection to p, attempts to create one.
328
func (pn *peernet) NewStream(ctx context.Context, p peer.ID) (inet.Stream, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329
330
331
	pn.Lock()
	cs, found := pn.connsByPeer[p]
	if !found || len(cs) < 1 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
		pn.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
		return nil, fmt.Errorf("no connection to peer")
	}

	// if many conns are found, how do we select? for now, randomly...
	// this would be an interesting place to test logic that can measure
	// links (network interfaces) and select properly
	n := rand.Intn(len(cs))
	var c *conn
	for c = range cs {
		if n == 0 {
			break
		}
		n--
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
347
	pn.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
348

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
349
	return c.NewStream()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350
351
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352
// SetStreamHandler sets the new stream handler on the Network.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
// This operation is threadsafe.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
354
355
356
357
func (pn *peernet) SetStreamHandler(h inet.StreamHandler) {
	pn.Lock()
	pn.streamHandler = h
	pn.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358
359
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
360
361
362
363
364
365
// SetConnHandler sets the new conn handler on the Network.
// This operation is threadsafe.
func (pn *peernet) SetConnHandler(h inet.ConnHandler) {
	pn.Lock()
	pn.connHandler = h
	pn.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
366
}
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

// Notify signs up Notifiee to receive signals when events happen
func (pn *peernet) Notify(f inet.Notifiee) {
	pn.notifmu.Lock()
	pn.notifs[f] = struct{}{}
	pn.notifmu.Unlock()
}

// StopNotify unregisters Notifiee fromr receiving signals
func (pn *peernet) StopNotify(f inet.Notifiee) {
	pn.notifmu.Lock()
	delete(pn.notifs, f)
	pn.notifmu.Unlock()
}

// notifyAll runs the notification function on all Notifiees
func (pn *peernet) notifyAll(notification func(f inet.Notifiee)) {
	pn.notifmu.RLock()
	for n := range pn.notifs {
		// make sure we dont block
		// and they dont block each other.
		go notification(n)
	}
	pn.notifmu.RUnlock()
}