-
Notifications
You must be signed in to change notification settings - Fork 0
/
continuousKadDhtDiscoverer.go
306 lines (261 loc) · 8.14 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
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
package discovery
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/bhagyaraj1208117/andes-abc-1/core/check"
"github.com/bhagyaraj1208117/andes-communication-go/p2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
kbucket "github.com/libp2p/go-libp2p-kbucket"
"github.com/libp2p/go-libp2p/core/protocol"
)
var _ p2p.PeerDiscoverer = (*continuousKadDhtDiscoverer)(nil)
var _ p2p.Reconnecter = (*continuousKadDhtDiscoverer)(nil)
const kadDhtName = "kad-dht discovery"
// ArgKadDht represents the kad-dht config argument DTO
type ArgKadDht struct {
Context context.Context
Host ConnectableHost
PeersRefreshInterval time.Duration
SeedersReconnectionInterval time.Duration
ProtocolID string
InitialPeersList []string
BucketSize uint32
RoutingTableRefresh time.Duration
KddSharder p2p.Sharder
ConnectionWatcher p2p.ConnectionsWatcher
NetworkType p2p.NetworkType
Logger p2p.Logger
}
// 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
connectionWatcher p2p.ConnectionsWatcher
networkType p2p.NetworkType
log p2p.Logger
}
// 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) {
sharder, err := prepareArguments(arg)
if err != nil {
return nil, err
}
sharder.SetSeeders(arg.InitialPeersList)
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,
connectionWatcher: arg.ConnectionWatcher,
networkType: arg.NetworkType,
log: arg.Logger,
}, nil
}
func prepareArguments(arg ArgKadDht) (Sharder, 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
}
if check.IfNil(arg.ConnectionWatcher) {
return nil, p2p.ErrNilConnectionsWatcher
}
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)
}
if check.IfNil(arg.Logger) {
return nil, p2p.ErrNilLogger
}
isListNilOrEmpty := len(arg.InitialPeersList) == 0
if isListNilOrEmpty {
arg.Logger.Warn("nil or empty initial peers list provided to kad dht implementation. " +
"No initial connection will be done")
}
return sharder, 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
args := ArgsHostWithConnectionManagement{
ConnectableHost: ckdd.host,
Sharder: ckdd.sharder,
ConnectionsWatcher: ckdd.connectionWatcher,
}
ckdd.hostConnManagement, err = NewHostWithConnectionManagement(args)
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,
)
// TODO: needs refactor
go func() {
select {
case <-chanStartBootstrap:
case <-ctx.Done():
return
}
ckdd.bootstrap(ctx)
}()
}
func (ckdd *continuousKadDhtDiscoverer) bootstrap(ctx context.Context) {
ckdd.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 {
ckdd.log.Debug("pausing the p2p bootstrapping process")
ckdd.ReconnectToNetwork(ctx)
ckdd.log.Debug("resuming the p2p bootstrapping process")
}
select {
case <-time.After(ckdd.peersRefreshInterval):
case <-ctx.Done():
ckdd.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 {
printConnectionErrorToSeeder(initialPeer, err, ckdd.log)
startIndex++
startIndex = startIndex % len(initialPeersList)
select {
case <-ckdd.context.Done():
ckdd.log.Debug("context done in continuousKadDhtDiscoverer")
return
case <-time.After(intervalBetweenAttempts):
continue
}
} else {
ckdd.log.Debug("connected to seeder",
"network", ckdd.networkType,
"address", initialPeer)
}
break
}
chanDone <- struct{}{}
}
func printConnectionErrorToSeeder(peer string, err error, log p2p.Logger) {
if errors.Is(err, p2p.ErrUnwantedPeer) {
log.Trace("tryConnectToSeeder: unwanted peer",
"seeder", peer,
"error", err.Error(),
)
return
}
log.Debug("error connecting to seeder",
"seeder", peer,
"error", err.Error(),
)
}
// 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(ctx context.Context) {
select {
case <-ckdd.connectToOnePeerFromInitialPeersList(ckdd.peersRefreshInterval, ckdd.initialPeersList):
case <-ctx.Done():
return
}
}
// IsInterfaceNil returns true if there is no value under the interface
func (ckdd *continuousKadDhtDiscoverer) IsInterfaceNil() bool {
return ckdd == nil
}