This repository has been archived by the owner on Nov 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
relaymgr.go
146 lines (124 loc) · 3.99 KB
/
relaymgr.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package relaymgr
import (
"context"
"fmt"
"sync"
"time"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
circuitv2 "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/client"
"github.com/multiformats/go-multiaddr"
logger "github.com/textileio/go-log/v2"
)
const (
connProtectTag = "auction-relay"
)
var (
log = logger.Logger("relaymgr")
pollFrequency = time.Second * 10
)
// RelayManager connects a libp2p host to an external relay and do a best-effort
// in keeping the connection healthy.
type RelayManager struct {
host host.Host
relayAddr peer.AddrInfo
connNotifee *connNotifee
closeOnce sync.Once
closeCtx context.Context
closeSignal context.CancelFunc
closed chan struct{}
}
// New connects the provided host to the remote relay, doing a best-effort
// in keeping the connection healthy. The provided context is only used for
// the initial connection to the relay. To shutdown call Close().
func New(ctx context.Context, h host.Host, relayMultiaddress string) (*RelayManager, error) {
relayAddr, err := multiaddr.NewMultiaddr(relayMultiaddress)
if err != nil {
return nil, fmt.Errorf("parsing relay multiaddr: %s", err)
}
addrInfo, err := peer.AddrInfoFromP2pAddr(relayAddr)
if err != nil {
return nil, fmt.Errorf("get addr-info from relay multiaddr: %s", err)
}
closeCtx, closeSignal := context.WithCancel(context.Background())
rm := &RelayManager{
host: h,
relayAddr: *addrInfo,
closeCtx: closeCtx,
closeSignal: closeSignal,
closed: make(chan struct{}),
}
rm.connNotifee = &connNotifee{rm: rm}
h.Network().Notify(rm.connNotifee)
if err := rm.connect(); err != nil {
return nil, fmt.Errorf("connecting to relay: %s", err)
}
go rm.keepHealthy()
return rm, nil
}
// Close stops relay manager work to keep a healthy connection with the relay.
func (rm *RelayManager) Close() error {
rm.closeOnce.Do(func() {
log.Infof("closing relay manager")
rm.host.ConnManager().Unprotect(rm.relayAddr.ID, connProtectTag)
rm.host.Network().StopNotify(rm.connNotifee)
rm.closeSignal()
<-rm.closed
log.Infof("relay manager closed")
})
return nil
}
func (rm *RelayManager) keepHealthy() {
defer close(rm.closed)
for {
select {
case <-rm.closeCtx.Done():
log.Debugf("closing healthy checker")
return
case <-time.After(pollFrequency):
isProtected := rm.host.ConnManager().IsProtected(rm.relayAddr.ID, "")
connStatus := rm.host.Network().Connectedness(rm.relayAddr.ID)
if !isProtected || connStatus != network.Connected {
log.Warnf("detected unhealthy status of connection (protected: %t, connStatus: %s)", isProtected, connStatus)
if err := rm.connect(); err != nil {
log.Errorf("poller reconnect: %s", err)
continue
}
}
log.Debugf("relay connection is healthy")
}
}
}
func (rm *RelayManager) connect() error {
log.Infof("connecting with relay...")
err := rm.host.Connect(rm.closeCtx, rm.relayAddr)
if err != nil {
return fmt.Errorf("connecting to relay: %s", err)
}
rm.host.ConnManager().Protect(rm.relayAddr.ID, connProtectTag)
log.Infof("connected with relay")
_, err = circuitv2.Reserve(rm.closeCtx, rm.host, peer.AddrInfo{
ID: rm.relayAddr.ID,
})
if err != nil {
return fmt.Errorf("reserving relay slot: %s", err)
}
return nil
}
type connNotifee struct {
rm *RelayManager
}
func (n *connNotifee) Disconnected(_ network.Network, ne network.Conn) {
if ne.RemotePeer() == n.rm.relayAddr.ID {
log.Warnf("disconnected from remote relay")
if err := n.rm.connect(); err != nil {
log.Errorf("notifee reconnect: %s", err)
}
}
}
func (n *connNotifee) Connected(_ network.Network, ne network.Conn) {}
func (n *connNotifee) OpenedStream(_ network.Network, s network.Stream) {}
func (n *connNotifee) ClosedStream(_ network.Network, s network.Stream) {}
func (n *connNotifee) ListenClose(_ network.Network, _ multiaddr.Multiaddr) {}
func (n *connNotifee) Listen(net network.Network, ma multiaddr.Multiaddr) {}