2019-09-23 21:43:53 +00:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2020-07-13 02:28:40 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/host"
|
2020-10-12 08:11:05 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
2019-09-23 21:43:53 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
2021-01-07 16:42:03 +00:00
|
|
|
peerInfo, err := MakePeer(p)
|
2019-09-23 21:43:53 +00:00
|
|
|
if err != nil {
|
2022-08-05 10:52:02 +00:00
|
|
|
log.WithError(err).Error("Could not make peer")
|
2019-09-23 21:43:53 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-01-07 16:42:03 +00:00
|
|
|
c := h.Network().ConnsToPeer(peerInfo.ID)
|
2019-09-23 21:43:53 +00:00
|
|
|
if len(c) == 0 {
|
2021-01-07 16:42:03 +00:00
|
|
|
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")
|
2019-09-23 21:43:53 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-10-12 08:11:05 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|