-
Notifications
You must be signed in to change notification settings - Fork 202
/
continuousKadDhtDiscoverer.go
251 lines (211 loc) · 6.74 KB
/
continuousKadDhtDiscoverer.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
package discovery
import (
"context"
"fmt"
"sync"
"time"
logger "github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/p2p"
"github.com/libp2p/go-libp2p-core/protocol"
dht "github.com/libp2p/go-libp2p-kad-dht"
kbucket "github.com/libp2p/go-libp2p-kbucket"
)
var _ p2p.PeerDiscoverer = (*ContinuousKadDhtDiscoverer)(nil)
var _ p2p.Reconnecter = (*ContinuousKadDhtDiscoverer)(nil)
var log = logger.GetOrCreate("p2p/libp2p/kaddht")
const kadDhtName = "kad-dht discovery"
// ArgKadDht represents the kad-dht config argument DTO
type ArgKadDht struct {
Context context.Context
Host ConnectableHost
PeersRefreshInterval time.Duration
ProtocolID string
InitialPeersList []string
BucketSize uint32
RoutingTableRefresh time.Duration
KddSharder p2p.CommonSharder
}
// ContinuousKadDhtDiscoverer is the kad-dht discovery type implementation
// This implementation does not support pausing and resuming of the discovery process
type ContinuousKadDhtDiscoverer struct {
host ConnectableHost
context context.Context
mutKadDht sync.RWMutex
kadDHT *dht.IpfsDHT
refreshCancel context.CancelFunc
peersRefreshInterval time.Duration
protocolID string
initialPeersList []string
bucketSize uint32
routingTableRefresh time.Duration
hostConnManagement *hostWithConnectionManagement
sharder Sharder
}
// NewContinuousKadDhtDiscoverer creates a new kad-dht discovery type implementation
// initialPeersList can be nil or empty, no initial connection will be attempted, a warning message will appear
func NewContinuousKadDhtDiscoverer(arg ArgKadDht) (*ContinuousKadDhtDiscoverer, error) {
if check.IfNilReflect(arg.Context) {
return nil, p2p.ErrNilContext
}
if check.IfNilReflect(arg.Host) {
return nil, p2p.ErrNilHost
}
if check.IfNil(arg.KddSharder) {
return nil, p2p.ErrNilSharder
}
sharder, ok := arg.KddSharder.(Sharder)
if !ok {
return nil, fmt.Errorf("%w for sharder: expected discovery.Sharder type of interface", p2p.ErrWrongTypeAssertion)
}
if arg.PeersRefreshInterval < time.Second {
return nil, fmt.Errorf("%w, PeersRefreshInterval should have been at least 1 second", p2p.ErrInvalidValue)
}
if arg.RoutingTableRefresh < time.Second {
return nil, fmt.Errorf("%w, RoutingTableRefresh should have been at least 1 second", p2p.ErrInvalidValue)
}
isListNilOrEmpty := len(arg.InitialPeersList) == 0
if isListNilOrEmpty {
log.Warn("nil or empty initial peers list provided to kad dht implementation. " +
"No initial connection will be done")
}
return &ContinuousKadDhtDiscoverer{
context: arg.Context,
host: arg.Host,
sharder: sharder,
peersRefreshInterval: arg.PeersRefreshInterval,
protocolID: arg.ProtocolID,
initialPeersList: arg.InitialPeersList,
bucketSize: arg.BucketSize,
routingTableRefresh: arg.RoutingTableRefresh,
}, nil
}
// Bootstrap will start the bootstrapping new peers process
func (ckdd *ContinuousKadDhtDiscoverer) Bootstrap() error {
ckdd.mutKadDht.Lock()
defer ckdd.mutKadDht.Unlock()
if ckdd.kadDHT != nil {
return p2p.ErrPeerDiscoveryProcessAlreadyStarted
}
return ckdd.startDHT()
}
func (ckdd *ContinuousKadDhtDiscoverer) startDHT() error {
ctxrun, cancel := context.WithCancel(ckdd.context)
var err error
ckdd.hostConnManagement, err = NewHostWithConnectionManagement(ckdd.host, ckdd.sharder)
if err != nil {
cancel()
return err
}
protocolID := protocol.ID(ckdd.protocolID)
kademliaDHT, err := dht.New(
ckdd.context,
ckdd.hostConnManagement,
dht.ProtocolPrefix(protocolID),
dht.RoutingTableRefreshPeriod(ckdd.routingTableRefresh),
dht.Mode(dht.ModeServer),
)
if err != nil {
cancel()
return err
}
go ckdd.connectToInitialAndBootstrap(ctxrun)
ckdd.kadDHT = kademliaDHT
ckdd.refreshCancel = cancel
return nil
}
func (ckdd *ContinuousKadDhtDiscoverer) stopDHT() error {
if ckdd.refreshCancel == nil {
return nil
}
ckdd.refreshCancel()
ckdd.refreshCancel = nil
protocolID := protocol.ID(ckdd.protocolID)
ckdd.host.RemoveStreamHandler(protocolID)
err := ckdd.kadDHT.Close()
ckdd.kadDHT = nil
return err
}
func (ckdd *ContinuousKadDhtDiscoverer) connectToInitialAndBootstrap(ctx context.Context) {
chanStartBootstrap := ckdd.connectToOnePeerFromInitialPeersList(
ckdd.peersRefreshInterval,
ckdd.initialPeersList,
)
go func() {
<-chanStartBootstrap
ckdd.bootstrap(ctx)
}()
}
func (ckdd *ContinuousKadDhtDiscoverer) bootstrap(ctx context.Context) {
log.Debug("starting the p2p bootstrapping process")
for {
ckdd.mutKadDht.RLock()
kadDht := ckdd.kadDHT
ckdd.mutKadDht.RUnlock()
shouldReconnect := kadDht != nil && kbucket.ErrLookupFailure == kadDht.Bootstrap(ckdd.context)
if shouldReconnect {
log.Debug("pausing the p2p bootstrapping process")
<-ckdd.ReconnectToNetwork()
log.Debug("resuming the p2p bootstrapping process")
}
select {
case <-time.After(ckdd.peersRefreshInterval):
case <-ctx.Done():
log.Debug("closing the p2p bootstrapping process")
return
}
}
}
func (ckdd *ContinuousKadDhtDiscoverer) connectToOnePeerFromInitialPeersList(
intervalBetweenAttempts time.Duration,
initialPeersList []string,
) <-chan struct{} {
chanDone := make(chan struct{}, 1)
if len(initialPeersList) == 0 {
chanDone <- struct{}{}
return chanDone
}
go ckdd.tryConnectToSeeder(intervalBetweenAttempts, initialPeersList, chanDone)
return chanDone
}
func (ckdd *ContinuousKadDhtDiscoverer) tryConnectToSeeder(
intervalBetweenAttempts time.Duration,
initialPeersList []string,
chanDone chan struct{},
) {
startIndex := 0
for {
initialPeer := initialPeersList[startIndex]
err := ckdd.host.ConnectToPeer(ckdd.context, initialPeer)
if err != nil {
log.Debug("error connecting to seeder",
"seeder", initialPeer,
"error", err.Error(),
)
startIndex++
startIndex = startIndex % len(initialPeersList)
select {
case <-ckdd.context.Done():
break
case <-time.After(intervalBetweenAttempts):
continue
}
} else {
log.Debug("connected to seeder", "address", initialPeer)
}
break
}
chanDone <- struct{}{}
}
// Name returns the name of the kad dht peer discovery implementation
func (ckdd *ContinuousKadDhtDiscoverer) Name() string {
return kadDhtName
}
// ReconnectToNetwork will try to connect to one peer from the initial peer list
func (ckdd *ContinuousKadDhtDiscoverer) ReconnectToNetwork() <-chan struct{} {
return ckdd.connectToOnePeerFromInitialPeersList(ckdd.peersRefreshInterval, ckdd.initialPeersList)
}
// IsInterfaceNil returns true if there is no value under the interface
func (ckdd *ContinuousKadDhtDiscoverer) IsInterfaceNil() bool {
return ckdd == nil
}