-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
bootstrap.go
65 lines (60 loc) · 1.58 KB
/
bootstrap.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
package dht
import (
"context"
"errors"
"time"
"github.com/anacrolix/dht/v2/krpc"
"github.com/anacrolix/dht/v2/traversal"
)
type TraversalStats = traversal.Stats
// See BootstrapContext.
func (s *Server) Bootstrap() (TraversalStats, error) {
return s.BootstrapContext(context.Background())
}
// Populates the node table.
func (s *Server) BootstrapContext(ctx context.Context) (_ TraversalStats, err error) {
s.mu.Lock()
if s.bootstrappingNow {
s.mu.Unlock()
err = errors.New("already bootstrapping")
return
}
s.bootstrappingNow = true
s.mu.Unlock()
defer func() {
s.mu.Lock()
defer s.mu.Unlock()
s.bootstrappingNow = false
}()
// Track number of responses, for STM use. (It's available via atomic in TraversalStats but that
// won't let wake up STM transactions that are observing the value.)
t := traversal.Start(traversal.OperationInput{
Target: s.id.AsByteArray(),
K: 16,
DoQuery: func(ctx context.Context, addr krpc.NodeAddr) traversal.QueryResult {
return s.FindNode(NewAddr(addr.UDP()), s.id, QueryRateLimiting{}).TraversalQueryResult(addr)
},
NodeFilter: s.TraversalNodeFilter,
})
nodes, err := s.TraversalStartingNodes()
if err != nil {
return
}
t.AddNodes(nodes)
s.mu.Lock()
s.lastBootstrap = time.Now()
s.mu.Unlock()
select {
case <-ctx.Done():
err = ctx.Err()
case <-t.Stalled():
}
t.Stop()
if err != nil {
// Could test for Stopped and return stats here but the interface doesn't tell the caller if
// we were successful in taking the stats. We could also take a snapshot instead.
return
}
<-t.Stopped()
return *t.Stats(), nil
}