2019-09-23 21:43:53 +00:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
host "github.com/libp2p/go-libp2p-host"
|
|
|
|
)
|
|
|
|
|
2020-07-03 15:25:32 +00:00
|
|
|
const timeoutMax = 30 * time.Second
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
peer, err := MakePeer(p)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Could not make peer: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
c := h.Network().ConnsToPeer(peer.ID)
|
|
|
|
if len(c) == 0 {
|
|
|
|
log.WithField("peer", peer.ID).Debug("No connections to peer, reconnecting")
|
2020-07-03 15:25:32 +00:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, timeoutMax)
|
2019-09-23 21:43:53 +00:00
|
|
|
defer cancel()
|
|
|
|
if err := h.Connect(ctx, *peer); err != nil {
|
|
|
|
log.WithField("peer", peer.ID).WithField("addrs", peer.Addrs).WithError(err).Errorf("Failed to reconnect to peer")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|