-
Notifications
You must be signed in to change notification settings - Fork 969
/
watch_peers.go
41 lines (36 loc) · 1.06 KB
/
watch_peers.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
package p2p
import (
"context"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
)
// ensurePeerConnections will attempt to reestablish connection to the peers
// if there are currently no connections to that peer.
func ensurePeerConnections(ctx context.Context, h host.Host, peers ...string) {
if len(peers) == 0 {
return
}
for _, p := range peers {
if p == "" {
continue
}
peerInfo, err := MakePeer(p)
if err != nil {
log.Errorf("Could not make peer: %v", err)
continue
}
c := h.Network().ConnsToPeer(peerInfo.ID)
if len(c) == 0 {
if err := connectWithTimeout(ctx, h, peerInfo); err != nil {
log.WithField("peer", peerInfo.ID).WithField("addrs", peerInfo.Addrs).WithError(err).Errorf("Failed to reconnect to peer")
continue
}
}
}
}
func connectWithTimeout(ctx context.Context, h host.Host, peer *peer.AddrInfo) error {
log.WithField("peer", peer.ID).Debug("No connections to peer, reconnecting")
ctx, cancel := context.WithTimeout(ctx, maxDialTimeout)
defer cancel()
return h.Connect(ctx, *peer)
}