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