forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer.go
120 lines (99 loc) · 2.15 KB
/
peer.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
package remotedialer
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
var (
Token = "X-API-Tunnel-Token"
ID = "X-API-Tunnel-ID"
)
func (s *Server) AddPeer(url, id, token string) {
if s.PeerID == "" || s.PeerToken == "" {
return
}
ctx, cancel := context.WithCancel(context.Background())
peer := peer{
url: url,
id: id,
token: token,
cancel: cancel,
}
logrus.Infof("Adding peer %s, %s", url, id)
s.peerLock.Lock()
defer s.peerLock.Unlock()
if p, ok := s.peers[id]; ok {
if p.equals(peer) {
return
}
p.cancel()
}
s.peers[id] = peer
go peer.start(ctx, s)
}
func (s *Server) RemovePeer(id string) {
s.peerLock.Lock()
defer s.peerLock.Unlock()
if p, ok := s.peers[id]; ok {
logrus.Infof("Removing peer %s", id)
p.cancel()
}
delete(s.peers, id)
}
type peer struct {
url, id, token string
cancel func()
}
func (p peer) equals(other peer) bool {
return p.url == other.url &&
p.id == other.id &&
p.token == other.token
}
func (p *peer) start(ctx context.Context, s *Server) {
headers := http.Header{
ID: {s.PeerID},
Token: {s.PeerToken},
}
dialer := &websocket.Dialer{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
outer:
for {
select {
case <-ctx.Done():
break outer
default:
}
ws, _, err := dialer.Dial(p.url, headers)
if err != nil {
logrus.Errorf("Failed to connect to peer %s [local ID=%s]: %v", p.url, s.PeerID, err)
time.Sleep(5 * time.Second)
continue
}
session := newClientSession(func(string, string) bool { return true }, ws)
session.dialer = func(network, address string) (net.Conn, error) {
parts := strings.SplitN(network, "::", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid clientKey/proto: %s", network)
}
return s.Dial(parts[0], 15*time.Second, parts[1], address)
}
s.sessions.addListener(session)
_, err = session.serve()
s.sessions.removeListener(session)
session.Close()
if err != nil {
logrus.Errorf("Failed to serve peer connection %s: %v", p.id, err)
}
ws.Close()
time.Sleep(5 * time.Second)
}
}