-
Notifications
You must be signed in to change notification settings - Fork 925
/
discovery.go
387 lines (334 loc) · 10.2 KB
/
discovery.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
375
376
377
378
379
380
381
382
383
384
385
386
387
package discovery
import (
"context"
"errors"
"fmt"
"time"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/discovery"
"github.com/libp2p/go-libp2p/core/event"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/host/eventbus"
"golang.org/x/sync/errgroup"
)
var log = logging.Logger("share/discovery")
const (
// eventbusBufSize is the size of the buffered channel to handle
// events in libp2p. We specify a larger buffer size for the channel
// to avoid overflowing and blocking subscription during disconnection bursts.
// (by default it is 16)
eventbusBufSize = 64
// findPeersTimeout limits the FindPeers operation in time
findPeersTimeout = time.Minute
// retryTimeout defines time interval between discovery and advertise attempts.
retryTimeout = time.Second
// logInterval defines the time interval at which a warning message will be logged
// if the desired number of nodes is not detected.
logInterval = 5 * time.Minute
)
// discoveryRetryTimeout defines time interval between discovery attempts, needed for tests
var discoveryRetryTimeout = retryTimeout
// Discovery combines advertise and discover services and allows to store discovered nodes.
// TODO: The code here gets horribly hairy, so we should refactor this at some point
type Discovery struct {
// Tag is used as rondezvous point for discovery service
tag string
set *limitedSet
host host.Host
disc discovery.Discovery
connector *backoffConnector
// onUpdatedPeers will be called on peer set changes
onUpdatedPeers OnUpdatedPeers
triggerDisc chan struct{}
metrics *metrics
cancel context.CancelFunc
params *Parameters
}
type OnUpdatedPeers func(peerID peer.ID, isAdded bool)
func (f OnUpdatedPeers) add(next OnUpdatedPeers) OnUpdatedPeers {
return func(peerID peer.ID, isAdded bool) {
f(peerID, isAdded)
next(peerID, isAdded)
}
}
// NewDiscovery constructs a new discovery.
func NewDiscovery(
params *Parameters,
h host.Host,
d discovery.Discovery,
tag string,
opts ...Option,
) (*Discovery, error) {
if err := params.Validate(); err != nil {
return nil, err
}
if tag == "" {
return nil, fmt.Errorf("discovery: tag cannot be empty")
}
o := newOptions(opts...)
return &Discovery{
tag: tag,
set: newLimitedSet(params.PeersLimit),
host: h,
disc: d,
connector: newBackoffConnector(h, defaultBackoffFactory),
onUpdatedPeers: o.onUpdatedPeers,
params: params,
triggerDisc: make(chan struct{}),
}, nil
}
func (d *Discovery) Start(context.Context) error {
ctx, cancel := context.WithCancel(context.Background())
d.cancel = cancel
sub, err := d.host.EventBus().Subscribe(&event.EvtPeerConnectednessChanged{}, eventbus.BufSize(eventbusBufSize))
if err != nil {
return fmt.Errorf("subscribing for connection events: %w", err)
}
go d.discoveryLoop(ctx)
go d.disconnectsLoop(ctx, sub)
go d.connector.GC(ctx)
return nil
}
func (d *Discovery) Stop(context.Context) error {
d.cancel()
if err := d.metrics.close(); err != nil {
log.Warnw("failed to close metrics", "err", err)
}
return nil
}
// Peers provides a list of discovered peers in the given topic.
// If Discovery hasn't found any peers, it blocks until at least one peer is found.
func (d *Discovery) Peers(ctx context.Context) ([]peer.ID, error) {
return d.set.Peers(ctx)
}
// Discard removes the peer from the peer set and rediscovers more if soft peer limit is not
// reached. Reports whether peer was removed with bool.
func (d *Discovery) Discard(id peer.ID) bool {
if !d.set.Contains(id) {
return false
}
d.host.ConnManager().Unprotect(id, d.tag)
d.connector.Backoff(id)
d.set.Remove(id)
d.onUpdatedPeers(id, false)
log.Debugw("removed peer from the peer set", "peer", id.String())
if d.set.Size() < d.set.Limit() {
// trigger discovery
select {
case d.triggerDisc <- struct{}{}:
default:
}
}
return true
}
// Advertise is a utility function that persistently advertises a service through an Advertiser.
// TODO: Start advertising only after the reachability is confirmed by AutoNAT
func (d *Discovery) Advertise(ctx context.Context) {
timer := time.NewTimer(d.params.AdvertiseInterval)
defer timer.Stop()
for {
_, err := d.disc.Advertise(ctx, d.tag)
d.metrics.observeAdvertise(ctx, err)
if err != nil {
if ctx.Err() != nil {
return
}
log.Warnw("error advertising", "rendezvous", d.tag, "err", err)
// we don't want retry indefinitely in busy loop
// internal discovery mechanism may need some time before attempts
errTimer := time.NewTimer(retryTimeout)
select {
case <-errTimer.C:
errTimer.Stop()
if !timer.Stop() {
<-timer.C
}
continue
case <-ctx.Done():
errTimer.Stop()
return
}
}
log.Debugf("advertised")
if !timer.Stop() {
<-timer.C
}
timer.Reset(d.params.AdvertiseInterval)
select {
case <-timer.C:
case <-ctx.Done():
return
}
}
}
// discoveryLoop ensures we always have '~peerLimit' connected peers.
// It initiates peer discovery upon request and restarts the process until the soft limit is
// reached.
func (d *Discovery) discoveryLoop(ctx context.Context) {
t := time.NewTicker(discoveryRetryTimeout)
defer t.Stop()
warnTicker := time.NewTicker(logInterval)
defer warnTicker.Stop()
for {
// drain all previous ticks from the channel
drainChannel(t.C)
select {
case <-t.C:
if !d.discover(ctx) {
// rerun discovery if the number of peers hasn't reached the limit
continue
}
case <-warnTicker.C:
if d.set.Size() < d.set.Limit() {
log.Warnf(
"Potentially degraded connectivity, unable to discover the desired amount of %s peers in %v. "+
"Number of peers discovered: %d. Required: %d.",
d.tag, logInterval, d.set.Size(), d.set.Limit(),
)
}
// Do not break the loop; just continue
continue
case <-ctx.Done():
return
}
}
}
// disconnectsLoop listen for disconnect events and ensures Discovery state
// is updated.
func (d *Discovery) disconnectsLoop(ctx context.Context, sub event.Subscription) {
defer sub.Close()
for {
select {
case <-ctx.Done():
return
case e, ok := <-sub.Out():
if !ok {
log.Error("connection subscription was closed unexpectedly")
return
}
if evnt := e.(event.EvtPeerConnectednessChanged); evnt.Connectedness == network.NotConnected {
d.Discard(evnt.Peer)
}
}
}
}
// discover finds new peers and reports whether it succeeded.
func (d *Discovery) discover(ctx context.Context) bool {
size := d.set.Size()
want := d.set.Limit() - size
if want == 0 {
log.Debugw("reached soft peer limit, skipping discovery", "size", size)
return true
}
// TODO @renaynay: eventually, have a mechanism to catch if wanted amount of peers
// has not been discovered in X amount of time so that users are warned of degraded
// FN connectivity.
log.Debugw("discovering peers", "want", want)
// we use errgroup as it provide limits
var wg errgroup.Group
// limit to minimize chances of overreaching the limit
wg.SetLimit(int(d.set.Limit()))
findCtx, findCancel := context.WithTimeout(ctx, findPeersTimeout)
defer func() {
// some workers could still be running, wait them to finish before canceling findCtx
wg.Wait() //nolint:errcheck
findCancel()
}()
peers, err := d.disc.FindPeers(findCtx, d.tag)
if err != nil {
log.Error("unable to start discovery", "err", err)
return false
}
for {
select {
case p, ok := <-peers:
if !ok {
break
}
peer := p
wg.Go(func() error {
if findCtx.Err() != nil {
log.Debug("find has been canceled, skip peer")
return nil //nolint:nilerr
}
// we don't pass findCtx so that we don't cancel in progress connections
// that are likely to be valuable
if !d.handleDiscoveredPeer(ctx, peer) {
return nil
}
size := d.set.Size()
log.Debugw("found peer", "peer", peer.ID.String(), "found_amount", size)
if size < d.set.Limit() {
return nil
}
log.Infow("discovered wanted peers", "amount", size)
findCancel() // stop discovery when we are done
return nil
})
continue
case <-findCtx.Done():
}
isEnoughPeers := d.set.Size() >= d.set.Limit()
d.metrics.observeFindPeers(ctx, isEnoughPeers)
log.Debugw("discovery finished", "discovered_wanted", isEnoughPeers)
return isEnoughPeers
}
}
// handleDiscoveredPeer adds peer to the internal if can connect or is connected.
// Report whether it succeeded.
func (d *Discovery) handleDiscoveredPeer(ctx context.Context, peer peer.AddrInfo) bool {
logger := log.With("peer", peer.ID.String())
switch {
case peer.ID == d.host.ID():
d.metrics.observeHandlePeer(ctx, handlePeerSkipSelf)
logger.Debug("skip handle: self discovery")
return false
case d.set.Size() >= d.set.Limit():
d.metrics.observeHandlePeer(ctx, handlePeerEnoughPeers)
logger.Debug("skip handle: enough peers found")
return false
}
switch d.host.Network().Connectedness(peer.ID) {
case network.Connected:
d.connector.Backoff(peer.ID) // we still have to backoff the connected peer
case network.NotConnected:
err := d.connector.Connect(ctx, peer)
if errors.Is(err, errBackoffNotEnded) {
d.metrics.observeHandlePeer(ctx, handlePeerBackoff)
logger.Debug("skip handle: backoff")
return false
}
if err != nil {
d.metrics.observeHandlePeer(ctx, handlePeerConnErr)
logger.Debugw("unable to connect", "err", err)
return false
}
default:
panic("unknown connectedness")
}
if !d.set.Add(peer.ID) {
d.metrics.observeHandlePeer(ctx, handlePeerInSet)
logger.Debug("peer is already in discovery set")
return false
}
d.onUpdatedPeers(peer.ID, true)
d.metrics.observeHandlePeer(ctx, handlePeerConnected)
logger.Debug("added peer to set")
// Tag to protect peer from being killed by ConnManager
// NOTE: This is does not protect from remote killing the connection.
// In the future, we should design a protocol that keeps bidirectional agreement on whether
// connection should be kept or not, similar to mesh link in GossipSub.
d.host.ConnManager().Protect(peer.ID, d.tag)
return true
}
func drainChannel(c <-chan time.Time) {
for {
select {
case <-c:
default:
return
}
}
}