-
Notifications
You must be signed in to change notification settings - Fork 107
/
router.go
319 lines (286 loc) · 9.21 KB
/
router.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package mesh
import (
"bytes"
"encoding/gob"
"fmt"
"math"
"net"
"sync"
"time"
)
var (
// Port is the port used for all mesh communication.
Port = 6783
// ChannelSize is the buffer size used by so-called actor goroutines
// throughout mesh.
ChannelSize = 16
defaultGossipInterval = 30 * time.Second
)
const (
tcpHeartbeat = 30 * time.Second
maxDuration = time.Duration(math.MaxInt64)
acceptMaxTokens = 20
acceptTokenDelay = 50 * time.Millisecond
)
// Config defines dimensions of configuration for the router.
// TODO(pb): provide usable defaults in NewRouter
type Config struct {
Host string
Port int
Password []byte
ConnLimit int
ProtocolMinVersion byte
PeerDiscovery bool
TrustedSubnets []*net.IPNet
GossipInterval *time.Duration
}
// Router manages communication between this peer and the rest of the mesh.
// Router implements Gossiper.
type Router struct {
Config
Overlay Overlay
Ourself *localPeer
Peers *Peers
Routes *routes
ConnectionMaker *connectionMaker
gossipLock sync.RWMutex
gossipChannels gossipChannels
topologyGossip Gossip
acceptLimiter *tokenBucket
logger Logger
}
// NewRouter returns a new router. It must be started.
func NewRouter(config Config, name PeerName, nickName string, overlay Overlay, logger Logger) (*Router, error) {
router := &Router{Config: config, gossipChannels: make(gossipChannels)}
if overlay == nil {
overlay = NullOverlay{}
}
router.Overlay = overlay
router.Ourself = newLocalPeer(name, nickName, router)
router.Peers = newPeers(router.Ourself)
router.Peers.OnGC(func(peer *Peer) {
logger.Printf("Removed unreachable peer %s", peer)
})
router.Routes = newRoutes(router.Ourself, router.Peers)
router.ConnectionMaker = newConnectionMaker(router.Ourself, router.Peers, net.JoinHostPort(router.Host, "0"), router.Port, router.PeerDiscovery, logger)
router.logger = logger
gossip, err := router.NewGossip("topology", router)
if err != nil {
return nil, err
}
router.topologyGossip = gossip
router.acceptLimiter = newTokenBucket(acceptMaxTokens, acceptTokenDelay)
return router, nil
}
// Start listening for TCP connections. This is separate from NewRouter so
// that gossipers can register before we start forming connections.
func (router *Router) Start() {
router.listenTCP()
}
// Stop shuts down the router.
func (router *Router) Stop() error {
router.Overlay.Stop()
// TODO: perform more graceful shutdown...
return nil
}
func (router *Router) usingPassword() bool {
return router.Password != nil
}
func (router *Router) listenTCP() {
localAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(router.Host, fmt.Sprint(router.Port)))
if err != nil {
panic(err)
}
ln, err := net.ListenTCP("tcp", localAddr)
if err != nil {
panic(err)
}
go func() {
defer ln.Close()
for {
tcpConn, err := ln.AcceptTCP()
if err != nil {
router.logger.Printf("%v", err)
continue
}
router.acceptTCP(tcpConn)
router.acceptLimiter.wait()
}
}()
}
func (router *Router) acceptTCP(tcpConn *net.TCPConn) {
remoteAddrStr := tcpConn.RemoteAddr().String()
router.logger.Printf("->[%s] connection accepted", remoteAddrStr)
connRemote := newRemoteConnection(router.Ourself.Peer, nil, remoteAddrStr, false, false)
startLocalConnection(connRemote, tcpConn, router, true, router.logger)
}
// NewGossip returns a usable GossipChannel from the router.
//
// TODO(pb): rename?
func (router *Router) NewGossip(channelName string, g Gossiper) (Gossip, error) {
channel := newGossipChannel(channelName, router.Ourself, router.Routes, g, router.logger)
router.gossipLock.Lock()
defer router.gossipLock.Unlock()
if _, found := router.gossipChannels[channelName]; found {
return nil, fmt.Errorf("[gossip] duplicate channel %s", channelName)
}
router.gossipChannels[channelName] = channel
return channel, nil
}
func (router *Router) gossipChannel(channelName string) *gossipChannel {
router.gossipLock.RLock()
channel, found := router.gossipChannels[channelName]
router.gossipLock.RUnlock()
if found {
return channel
}
router.gossipLock.Lock()
defer router.gossipLock.Unlock()
if channel, found = router.gossipChannels[channelName]; found {
return channel
}
channel = newGossipChannel(channelName, router.Ourself, router.Routes, &surrogateGossiper{router: router}, router.logger)
channel.logf("created surrogate channel")
router.gossipChannels[channelName] = channel
return channel
}
func (router *Router) gossipChannelSet() map[*gossipChannel]struct{} {
channels := make(map[*gossipChannel]struct{})
router.gossipLock.RLock()
defer router.gossipLock.RUnlock()
for _, channel := range router.gossipChannels {
channels[channel] = struct{}{}
}
return channels
}
func (router *Router) gossipInterval() time.Duration {
if router.Config.GossipInterval != nil {
return *router.Config.GossipInterval
} else {
return defaultGossipInterval
}
}
func (router *Router) handleGossip(tag protocolTag, payload []byte) error {
decoder := gob.NewDecoder(bytes.NewReader(payload))
var channelName string
if err := decoder.Decode(&channelName); err != nil {
return err
}
channel := router.gossipChannel(channelName)
var srcName PeerName
if err := decoder.Decode(&srcName); err != nil {
return err
}
switch tag {
case ProtocolGossipUnicast:
return channel.deliverUnicast(srcName, payload, decoder)
case ProtocolGossipBroadcast:
return channel.deliverBroadcast(srcName, payload, decoder)
case ProtocolGossip:
return channel.deliver(srcName, payload, decoder)
}
return nil
}
// Relay all pending gossip data for each channel via random neighbours.
func (router *Router) sendAllGossip() {
for channel := range router.gossipChannelSet() {
if gossip := channel.gossiper.Gossip(); gossip != nil {
channel.Send(gossip)
}
}
}
// Relay all pending gossip data for each channel via conn.
func (router *Router) sendAllGossipDown(conn Connection) {
for channel := range router.gossipChannelSet() {
if gossip := channel.gossiper.Gossip(); gossip != nil {
channel.SendDown(conn, gossip)
}
}
}
// for testing
func (router *Router) sendPendingGossip() bool {
sentSomething := false
for conn := range router.Ourself.getConnections() {
sentSomething = conn.(gossipConnection).gossipSenders().Flush() || sentSomething
}
return sentSomething
}
// BroadcastTopologyUpdate is invoked whenever there is a change to the mesh
// topology, and broadcasts the new set of peers to the mesh.
func (router *Router) broadcastTopologyUpdate(update peerNameSet) {
gossipData := &topologyGossipData{peers: router.Peers, update: update}
router.topologyGossip.GossipNeighbourSubset(gossipData)
}
// OnGossipUnicast implements Gossiper, but always returns an error, as a
// router should only receive gossip broadcasts of TopologyGossipData.
func (router *Router) OnGossipUnicast(sender PeerName, msg []byte) error {
return fmt.Errorf("unexpected topology gossip unicast: %v", msg)
}
// OnGossipBroadcast receives broadcasts of TopologyGossipData.
// It returns the received update unchanged.
func (router *Router) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) {
origUpdate, _, err := router.applyTopologyUpdate(update)
if err != nil || len(origUpdate) == 0 {
return nil, err
}
return &topologyGossipData{peers: router.Peers, update: origUpdate}, nil
}
// Gossip yields the current topology as GossipData.
func (router *Router) Gossip() GossipData {
return &topologyGossipData{peers: router.Peers, update: router.Peers.names()}
}
// OnGossip receives broadcasts of TopologyGossipData.
// It returns an "improved" version of the received update.
// See peers.ApplyUpdate.
func (router *Router) OnGossip(update []byte) (GossipData, error) {
_, newUpdate, err := router.applyTopologyUpdate(update)
if err != nil || len(newUpdate) == 0 {
return nil, err
}
return &topologyGossipData{peers: router.Peers, update: newUpdate}, nil
}
func (router *Router) applyTopologyUpdate(update []byte) (peerNameSet, peerNameSet, error) {
origUpdate, newUpdate, err := router.Peers.applyUpdate(update)
if err != nil {
return nil, nil, err
}
if len(newUpdate) > 0 {
router.ConnectionMaker.refresh()
router.Routes.recalculate()
}
return origUpdate, newUpdate, nil
}
func (router *Router) trusts(remote *remoteConnection) bool {
if tcpAddr, err := net.ResolveTCPAddr("tcp", remote.remoteTCPAddr); err == nil {
for _, trustedSubnet := range router.TrustedSubnets {
if trustedSubnet.Contains(tcpAddr.IP) {
return true
}
}
} else {
// Should not happen as remoteTCPAddr was obtained from TCPConn
router.logger.Printf("Unable to parse remote TCP addr: %s", err)
}
return false
}
// The set of peers in the mesh network.
// Gossiped just like anything else.
type topologyGossipData struct {
peers *Peers
update peerNameSet
}
// Merge implements GossipData.
func (d *topologyGossipData) Merge(other GossipData) GossipData {
names := make(peerNameSet)
for name := range d.update {
names[name] = struct{}{}
}
for name := range other.(*topologyGossipData).update {
names[name] = struct{}{}
}
return &topologyGossipData{peers: d.peers, update: names}
}
// Encode implements GossipData.
func (d *topologyGossipData) Encode() [][]byte {
return [][]byte{d.peers.encodePeers(d.update)}
}