-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimizedKadDhtDiscoverer.go
261 lines (215 loc) · 7.6 KB
/
optimizedKadDhtDiscoverer.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
package discovery
import (
"context"
"time"
"github.com/bhagyaraj1208117/andes-communication-go/p2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/protocol"
)
type discovererStatus string
const statNotInitialized discovererStatus = "not initialized"
const statInitialized discovererStatus = "initialized"
const minIntervalForSeedersReconnection = time.Second
const optimizedKadDhtName = "optimized kad-dht discovery"
type optimizedKadDhtDiscoverer struct {
kadDHT KadDhtHandler
peersRefreshInterval time.Duration
seedersReconnectionInterval time.Duration
protocolID string
initialPeersList []string
bucketSize uint32
routingTableRefresh time.Duration
hostConnManagement *hostWithConnectionManagement
sharder Sharder
status discovererStatus
chanInit chan struct{}
errChanInit chan error
chanConnectToSeeders chan struct{}
createKadDhtHandler func(ctx context.Context) (KadDhtHandler, error)
connectionWatcher p2p.ConnectionsWatcher
networkType p2p.NetworkType
log p2p.Logger
}
// NewOptimizedKadDhtDiscoverer creates an optimized kad-dht discovery type implementation
// initialPeersList can be nil or empty, no initial connection will be attempted, a warning message will appear
// This implementation uses a single process loop function able to carry multiple tasks synchronously
func NewOptimizedKadDhtDiscoverer(arg ArgKadDht) (*optimizedKadDhtDiscoverer, error) {
sharder, err := prepareArguments(arg)
if err != nil {
return nil, err
}
if arg.SeedersReconnectionInterval < minIntervalForSeedersReconnection {
return nil, p2p.ErrInvalidSeedersReconnectionInterval
}
sharder.SetSeeders(arg.InitialPeersList)
okdd := &optimizedKadDhtDiscoverer{
sharder: sharder,
peersRefreshInterval: arg.PeersRefreshInterval,
seedersReconnectionInterval: arg.SeedersReconnectionInterval,
protocolID: arg.ProtocolID,
initialPeersList: arg.InitialPeersList,
bucketSize: arg.BucketSize,
routingTableRefresh: arg.RoutingTableRefresh,
status: statNotInitialized,
chanInit: make(chan struct{}),
errChanInit: make(chan error),
chanConnectToSeeders: make(chan struct{}),
connectionWatcher: arg.ConnectionWatcher,
networkType: arg.NetworkType,
log: arg.Logger,
}
okdd.createKadDhtHandler = okdd.createKadDht
args := ArgsHostWithConnectionManagement{
ConnectableHost: arg.Host,
Sharder: okdd.sharder,
ConnectionsWatcher: okdd.connectionWatcher,
}
okdd.hostConnManagement, err = NewHostWithConnectionManagement(args)
if err != nil {
return nil, err
}
go okdd.processLoop(arg.Context)
return okdd, nil
}
// Bootstrap will start the bootstrapping new peers process
func (okdd *optimizedKadDhtDiscoverer) Bootstrap() error {
okdd.chanInit <- struct{}{}
return <-okdd.errChanInit
}
func (okdd *optimizedKadDhtDiscoverer) processLoop(ctx context.Context) {
chTimeSeedersReconnect := time.After(okdd.seedersReconnectionInterval)
chTimeFindPeers := time.After(okdd.peersRefreshInterval)
for {
select {
case <-okdd.chanInit:
chTimeSeedersReconnect = okdd.processInit(ctx)
case <-chTimeSeedersReconnect:
chTimeSeedersReconnect = okdd.processSeedersReconnect(ctx)
case <-okdd.chanConnectToSeeders:
chTimeSeedersReconnect = okdd.processSeedersReconnect(ctx)
case <-chTimeFindPeers:
okdd.findPeers(ctx)
chTimeFindPeers = time.After(okdd.peersRefreshInterval)
case <-ctx.Done():
okdd.log.Debug("closing the p2p bootstrapping process")
okdd.finishMainLoopProcessing(ctx)
return
}
}
}
func (okdd *optimizedKadDhtDiscoverer) processInit(ctx context.Context) <-chan time.Time {
err := okdd.init(ctx)
okdd.errChanInit <- err
if err != nil {
return okdd.createChTimeSeedersReconnect(false)
}
ch := okdd.processSeedersReconnect(ctx)
okdd.findPeers(ctx)
return ch
}
func (okdd *optimizedKadDhtDiscoverer) processSeedersReconnect(ctx context.Context) <-chan time.Time {
isConnectedToSeeders := okdd.tryToReconnectAtLeastToASeeder(ctx)
return okdd.createChTimeSeedersReconnect(isConnectedToSeeders)
}
func (okdd *optimizedKadDhtDiscoverer) finishMainLoopProcessing(ctx context.Context) {
select {
case okdd.errChanInit <- ctx.Err():
default:
}
}
func (okdd *optimizedKadDhtDiscoverer) createChTimeSeedersReconnect(isConnectedToSeeders bool) <-chan time.Time {
if isConnectedToSeeders {
// the reconnection will be done less often
return time.After(okdd.seedersReconnectionInterval)
}
// no connection to seeders, let's try a little bit faster
return time.After(okdd.peersRefreshInterval)
}
func (okdd *optimizedKadDhtDiscoverer) init(ctx context.Context) error {
if okdd.status != statNotInitialized {
return p2p.ErrPeerDiscoveryProcessAlreadyStarted
}
kadDhtHandler, err := okdd.createKadDhtHandler(ctx)
if err != nil {
return err
}
okdd.kadDHT = kadDhtHandler
okdd.status = statInitialized
return nil
}
func (okdd *optimizedKadDhtDiscoverer) createKadDht(ctx context.Context) (KadDhtHandler, error) {
protocolID := protocol.ID(okdd.protocolID)
return dht.New(
ctx,
okdd.hostConnManagement,
dht.ProtocolPrefix(protocolID),
dht.RoutingTableRefreshPeriod(okdd.routingTableRefresh),
dht.Mode(dht.ModeServer),
)
}
func (okdd *optimizedKadDhtDiscoverer) tryToReconnectAtLeastToASeeder(ctx context.Context) bool {
if okdd.status != statInitialized {
return false
}
if len(okdd.initialPeersList) == 0 {
return true
}
connectedToOneSeeder := false
for _, seederAddress := range okdd.initialPeersList {
err := okdd.connectToSeeder(ctx, seederAddress)
if err != nil {
printConnectionErrorToSeeder(seederAddress, err, okdd.log)
} else {
connectedToOneSeeder = true
}
select {
case <-ctx.Done():
okdd.log.Debug("optimizedKadDhtDiscoverer.tryToReconnectAtLeastToASeeder",
"network", okdd.networkType,
"num seeders", len(okdd.initialPeersList),
"connected to a seeder", true,
"context", "done")
return true
default:
}
}
okdd.log.Debug("optimizedKadDhtDiscoverer.tryToReconnectAtLeastToASeeder",
"network", okdd.networkType,
"num seeders", len(okdd.initialPeersList),
"connected to a seeder", connectedToOneSeeder)
return connectedToOneSeeder
}
func (okdd *optimizedKadDhtDiscoverer) connectToSeeder(ctx context.Context, seederAddress string) error {
seederInfo, err := okdd.hostConnManagement.AddressToPeerInfo(seederAddress)
if err != nil {
return err
}
if okdd.hostConnManagement.IsConnected(*seederInfo) {
return nil
}
return okdd.hostConnManagement.Connect(ctx, *seederInfo)
}
func (okdd *optimizedKadDhtDiscoverer) findPeers(ctx context.Context) {
if okdd.status != statInitialized {
return
}
err := okdd.kadDHT.Bootstrap(ctx)
if err != nil {
okdd.log.Debug("kad dht bootstrap", "network", okdd.networkType, "error", err)
}
}
// Name returns the name of the kad dht peer discovery implementation
func (okdd *optimizedKadDhtDiscoverer) Name() string {
return optimizedKadDhtName
}
// ReconnectToNetwork will try to connect to one peer from the initial peer list
func (okdd *optimizedKadDhtDiscoverer) ReconnectToNetwork(_ context.Context) {
select {
case okdd.chanConnectToSeeders <- struct{}{}:
default:
}
}
// IsInterfaceNil returns true if there is no value under the interface
func (okdd *optimizedKadDhtDiscoverer) IsInterfaceNil() bool {
return okdd == nil
}