-
Notifications
You must be signed in to change notification settings - Fork 0
/
inmem_layer.go
418 lines (343 loc) · 8.93 KB
/
inmem_layer.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package cluster
import (
"crypto/tls"
"errors"
"fmt"
"net"
"sync"
"time"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/base62"
"go.uber.org/atomic"
)
// InmemLayer is an in-memory implementation of NetworkLayer. This is
// primarially useful for tests.
type InmemLayer struct {
listener *inmemListener
addr string
logger log.Logger
servConns map[string][]net.Conn
clientConns map[string][]net.Conn
peers map[string]*InmemLayer
l sync.Mutex
stopped *atomic.Bool
stopCh chan struct{}
connectionCh chan *ConnectionInfo
readerDelay time.Duration
}
// NewInmemLayer returns a new in-memory layer configured to listen on the
// provided address.
func NewInmemLayer(addr string, logger log.Logger) *InmemLayer {
return &InmemLayer{
addr: addr,
logger: logger,
stopped: atomic.NewBool(false),
stopCh: make(chan struct{}),
peers: make(map[string]*InmemLayer),
servConns: make(map[string][]net.Conn),
clientConns: make(map[string][]net.Conn),
}
}
func (l *InmemLayer) SetConnectionCh(ch chan *ConnectionInfo) {
l.l.Lock()
l.connectionCh = ch
l.l.Unlock()
}
func (l *InmemLayer) SetReaderDelay(delay time.Duration) {
l.l.Lock()
defer l.l.Unlock()
l.readerDelay = delay
// Update the existing server and client connections
for _, servConns := range l.servConns {
for _, c := range servConns {
c.(*delayedConn).SetDelay(delay)
}
}
for _, clientConns := range l.clientConns {
for _, c := range clientConns {
c.(*delayedConn).SetDelay(delay)
}
}
}
// Addrs implements NetworkLayer.
func (l *InmemLayer) Addrs() []net.Addr {
l.l.Lock()
defer l.l.Unlock()
if l.listener == nil {
return nil
}
return []net.Addr{l.listener.Addr()}
}
// Listeners implements NetworkLayer.
func (l *InmemLayer) Listeners() []NetworkListener {
l.l.Lock()
defer l.l.Unlock()
if l.listener != nil {
return []NetworkListener{l.listener}
}
l.listener = &inmemListener{
addr: l.addr,
pendingConns: make(chan net.Conn),
stopped: atomic.NewBool(false),
stopCh: make(chan struct{}),
}
return []NetworkListener{l.listener}
}
// Dial implements NetworkLayer.
func (l *InmemLayer) Dial(addr string, timeout time.Duration, tlsConfig *tls.Config) (*tls.Conn, error) {
l.l.Lock()
connectionCh := l.connectionCh
if addr == l.addr {
panic(fmt.Sprintf("%q attempted to dial itself", l.addr))
}
peer, ok := l.peers[addr]
l.l.Unlock()
if !ok {
return nil, errors.New("inmemlayer: no address found")
}
alpn := ""
if tlsConfig != nil {
alpn = tlsConfig.NextProtos[0]
}
if l.logger.IsDebug() {
l.logger.Debug("dailing connection", "node", l.addr, "remote", addr, "alpn", alpn)
}
if connectionCh != nil {
select {
case connectionCh <- &ConnectionInfo{
Node: l.addr,
Remote: addr,
IsServer: false,
ALPN: alpn,
}:
case <-time.After(2 * time.Second):
l.logger.Warn("failed to send connection info")
}
}
conn, err := peer.clientConn(l.addr)
if err != nil {
return nil, err
}
tlsConn := tls.Client(conn, tlsConfig)
l.l.Lock()
l.clientConns[addr] = append(l.clientConns[addr], conn)
l.l.Unlock()
return tlsConn, nil
}
// clientConn is executed on a server when a new client connection comes in and
// needs to be Accepted.
func (l *InmemLayer) clientConn(addr string) (net.Conn, error) {
l.l.Lock()
if l.listener == nil {
l.l.Unlock()
return nil, errors.New("inmemlayer: listener not started")
}
_, ok := l.peers[addr]
if !ok {
l.l.Unlock()
return nil, errors.New("inmemlayer: no peer found")
}
retConn, servConn := net.Pipe()
retConn = newDelayedConn(retConn, l.readerDelay)
servConn = newDelayedConn(servConn, l.readerDelay)
l.servConns[addr] = append(l.servConns[addr], servConn)
connectionCh := l.connectionCh
pendingConns := l.listener.pendingConns
l.l.Unlock()
if l.logger.IsDebug() {
l.logger.Debug("received connection", "node", l.addr, "remote", addr)
}
if connectionCh != nil {
select {
case connectionCh <- &ConnectionInfo{
Node: l.addr,
Remote: addr,
IsServer: true,
}:
case <-time.After(2 * time.Second):
l.logger.Warn("failed to send connection info")
}
}
select {
case pendingConns <- servConn:
case <-time.After(2 * time.Second):
return nil, errors.New("inmemlayer: timeout while accepting connection")
}
return retConn, nil
}
// Connect is used to connect this transport to another transport for
// a given peer name. This allows for local routing.
func (l *InmemLayer) Connect(remote *InmemLayer) {
l.l.Lock()
defer l.l.Unlock()
l.peers[remote.addr] = remote
}
// Disconnect is used to remove the ability to route to a given peer.
func (l *InmemLayer) Disconnect(peer string) {
l.l.Lock()
defer l.l.Unlock()
delete(l.peers, peer)
// Remove any open connections
servConns := l.servConns[peer]
for _, c := range servConns {
c.Close()
}
delete(l.servConns, peer)
clientConns := l.clientConns[peer]
for _, c := range clientConns {
c.Close()
}
delete(l.clientConns, peer)
}
// DisconnectAll is used to remove all routes to peers.
func (l *InmemLayer) DisconnectAll() {
l.l.Lock()
defer l.l.Unlock()
l.peers = make(map[string]*InmemLayer)
// Close all connections
for _, peerConns := range l.servConns {
for _, c := range peerConns {
c.Close()
}
}
l.servConns = make(map[string][]net.Conn)
for _, peerConns := range l.clientConns {
for _, c := range peerConns {
c.Close()
}
}
l.clientConns = make(map[string][]net.Conn)
}
// Close is used to permanently disable the transport
func (l *InmemLayer) Close() error {
if l.stopped.Swap(true) {
return nil
}
l.DisconnectAll()
close(l.stopCh)
return nil
}
// inmemListener implements the NetworkListener interface.
type inmemListener struct {
addr string
pendingConns chan net.Conn
stopped *atomic.Bool
stopCh chan struct{}
deadline time.Time
}
// Accept implements the NetworkListener interface.
func (ln *inmemListener) Accept() (net.Conn, error) {
deadline := ln.deadline
if !deadline.IsZero() {
select {
case conn := <-ln.pendingConns:
return conn, nil
case <-time.After(time.Until(deadline)):
return nil, deadlineError("deadline")
case <-ln.stopCh:
return nil, errors.New("listener shut down")
}
}
select {
case conn := <-ln.pendingConns:
return conn, nil
case <-ln.stopCh:
return nil, errors.New("listener shut down")
}
}
// Close implements the NetworkListener interface.
func (ln *inmemListener) Close() error {
if ln.stopped.Swap(true) {
return nil
}
close(ln.stopCh)
return nil
}
// Addr implements the NetworkListener interface.
func (ln *inmemListener) Addr() net.Addr {
return inmemAddr{addr: ln.addr}
}
// SetDeadline implements the NetworkListener interface.
func (ln *inmemListener) SetDeadline(d time.Time) error {
ln.deadline = d
return nil
}
type inmemAddr struct {
addr string
}
func (a inmemAddr) Network() string {
return "inmem"
}
func (a inmemAddr) String() string {
return a.addr
}
type deadlineError string
func (d deadlineError) Error() string { return string(d) }
func (d deadlineError) Timeout() bool { return true }
func (d deadlineError) Temporary() bool { return true }
// InmemLayerCluster composes a set of layers and handles connecting them all
// together. It also satisfies the NetworkLayerSet interface.
type InmemLayerCluster struct {
layers []*InmemLayer
}
// NewInmemLayerCluster returns a new in-memory layer set that builds n nodes
// and connects them all together.
func NewInmemLayerCluster(clusterName string, nodes int, logger log.Logger) (*InmemLayerCluster, error) {
if clusterName == "" {
clusterID, err := base62.Random(4)
if err != nil {
return nil, err
}
clusterName = "cluster_" + clusterID
}
layers := make([]*InmemLayer, nodes)
for i := 0; i < nodes; i++ {
layers[i] = NewInmemLayer(fmt.Sprintf("%s_node_%d", clusterName, i), logger)
}
// Connect all the peers together
for _, node := range layers {
for _, peer := range layers {
// Don't connect to itself
if node == peer {
continue
}
node.Connect(peer)
peer.Connect(node)
}
}
return &InmemLayerCluster{layers: layers}, nil
}
// ConnectCluster connects this cluster with the provided remote cluster,
// connecting all nodes to each other.
func (ic *InmemLayerCluster) ConnectCluster(remote *InmemLayerCluster) {
for _, node := range ic.layers {
for _, peer := range remote.layers {
node.Connect(peer)
peer.Connect(node)
}
}
}
// Layers implements the NetworkLayerSet interface.
func (ic *InmemLayerCluster) Layers() []NetworkLayer {
ret := make([]NetworkLayer, len(ic.layers))
for i, l := range ic.layers {
ret[i] = l
}
return ret
}
func (ic *InmemLayerCluster) SetConnectionCh(ch chan *ConnectionInfo) {
for _, node := range ic.layers {
node.SetConnectionCh(ch)
}
}
func (ic *InmemLayerCluster) SetReaderDelay(delay time.Duration) {
for _, node := range ic.layers {
node.SetReaderDelay(delay)
}
}
type ConnectionInfo struct {
Node string
Remote string
IsServer bool
ALPN string
}