-
Notifications
You must be signed in to change notification settings - Fork 784
/
tcp_transport.go
612 lines (508 loc) · 17.8 KB
/
tcp_transport.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
package memberlist
import (
"bytes"
"crypto/md5"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"sync"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/hashicorp/go-sockaddr"
"github.com/hashicorp/memberlist"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
"github.com/cortexproject/cortex/pkg/util/flagext"
)
type messageType uint8
const (
_ messageType = iota // don't use 0
packet
stream
)
const zeroZeroZeroZero = "0.0.0.0"
// TCPTransportConfig is a configuration structure for creating new TCPTransport.
type TCPTransportConfig struct {
// BindAddrs is a list of addresses to bind to.
BindAddrs flagext.StringSlice `yaml:"bind_addr"`
// BindPort is the port to listen on, for each address above.
BindPort int `yaml:"bind_port"`
// Timeout used when making connections to other nodes to send packet.
// Zero = no timeout
PacketDialTimeout time.Duration `yaml:"packet_dial_timeout"`
// Timeout for writing packet data. Zero = no timeout.
PacketWriteTimeout time.Duration `yaml:"packet_write_timeout"`
// WriteTo is used to send "UDP" packets. Since we use TCP, we can detect more errors,
// but memberlist doesn't seem to cope with that very well.
ReportWriteToErrors bool `yaml:"-"`
// Transport logs lot of messages at debug level, so it deserves an extra flag for turning it on
TransportDebug bool `yaml:"-"`
// Where to put custom metrics. nil = don't register.
MetricsRegisterer prometheus.Registerer `yaml:"-"`
MetricsNamespace string `yaml:"-"`
}
// RegisterFlags registers flags.
func (cfg *TCPTransportConfig) RegisterFlags(f *flag.FlagSet, prefix string) {
// "Defaults to hostname" -- memberlist sets it to hostname by default.
f.Var(&cfg.BindAddrs, prefix+"memberlist.bind-addr", "IP address to listen on for gossip messages. Multiple addresses may be specified. Defaults to 0.0.0.0")
f.IntVar(&cfg.BindPort, prefix+"memberlist.bind-port", 7946, "Port to listen on for gossip messages.")
f.DurationVar(&cfg.PacketDialTimeout, prefix+"memberlist.packet-dial-timeout", 5*time.Second, "Timeout used when connecting to other nodes to send packet.")
f.DurationVar(&cfg.PacketWriteTimeout, prefix+"memberlist.packet-write-timeout", 5*time.Second, "Timeout for writing 'packet' data.")
f.BoolVar(&cfg.TransportDebug, prefix+"memberlist.transport-debug", false, "Log debug transport messages. Note: global log.level must be at debug level as well.")
}
// TCPTransport is a memberlist.Transport implementation that uses TCP for both packet and stream
// operations ("packet" and "stream" are terms used by memberlist).
// It uses a new TCP connections for each operation. There is no connection reuse.
type TCPTransport struct {
cfg TCPTransportConfig
logger log.Logger
packetCh chan *memberlist.Packet
connCh chan net.Conn
wg sync.WaitGroup
tcpListeners []*net.TCPListener
shutdown atomic.Int32
advertiseMu sync.RWMutex
advertiseAddr string
// metrics
incomingStreams prometheus.Counter
outgoingStreams prometheus.Counter
outgoingStreamErrors prometheus.Counter
receivedPackets prometheus.Counter
receivedPacketsBytes prometheus.Counter
receivedPacketsErrors prometheus.Counter
sentPackets prometheus.Counter
sentPacketsBytes prometheus.Counter
sentPacketsErrors prometheus.Counter
unknownConnections prometheus.Counter
}
// NewTCPTransport returns a new tcp-based transport with the given configuration. On
// success all the network listeners will be created and listening.
func NewTCPTransport(config TCPTransportConfig, logger log.Logger) (*TCPTransport, error) {
if len(config.BindAddrs) == 0 {
config.BindAddrs = []string{zeroZeroZeroZero}
}
// Build out the new transport.
var ok bool
t := TCPTransport{
cfg: config,
logger: logger,
packetCh: make(chan *memberlist.Packet),
connCh: make(chan net.Conn),
}
t.registerMetrics()
// Clean up listeners if there's an error.
defer func() {
if !ok {
_ = t.Shutdown()
}
}()
// Build all the TCP and UDP listeners.
port := config.BindPort
for _, addr := range config.BindAddrs {
ip := net.ParseIP(addr)
tcpAddr := &net.TCPAddr{IP: ip, Port: port}
tcpLn, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return nil, fmt.Errorf("failed to start TCP listener on %q port %d: %v", addr, port, err)
}
t.tcpListeners = append(t.tcpListeners, tcpLn)
// If the config port given was zero, use the first TCP listener
// to pick an available port and then apply that to everything
// else.
if port == 0 {
port = tcpLn.Addr().(*net.TCPAddr).Port
}
}
// Fire them up now that we've been able to create them all.
for i := 0; i < len(config.BindAddrs); i++ {
t.wg.Add(1)
go t.tcpListen(t.tcpListeners[i])
}
ok = true
return &t, nil
}
// tcpListen is a long running goroutine that accepts incoming TCP connections
// and spawns new go routine to handle each connection. This transport uses TCP connections
// for both packet sending and streams.
// (copied from Memberlist net_transport.go)
func (t *TCPTransport) tcpListen(tcpLn *net.TCPListener) {
defer t.wg.Done()
// baseDelay is the initial delay after an AcceptTCP() error before attempting again
const baseDelay = 5 * time.Millisecond
// maxDelay is the maximum delay after an AcceptTCP() error before attempting again.
// In the case that tcpListen() is error-looping, it will delay the shutdown check.
// Therefore, changes to maxDelay may have an effect on the latency of shutdown.
const maxDelay = 1 * time.Second
var loopDelay time.Duration
for {
conn, err := tcpLn.AcceptTCP()
if err != nil {
if s := t.shutdown.Load(); s == 1 {
break
}
if loopDelay == 0 {
loopDelay = baseDelay
} else {
loopDelay *= 2
}
if loopDelay > maxDelay {
loopDelay = maxDelay
}
level.Error(t.logger).Log("msg", "TCPTransport: Error accepting TCP connection", "err", err)
time.Sleep(loopDelay)
continue
}
// No error, reset loop delay
loopDelay = 0
go t.handleConnection(conn)
}
}
var noopLogger = log.NewNopLogger()
func (t *TCPTransport) debugLog() log.Logger {
if t.cfg.TransportDebug {
return level.Debug(t.logger)
}
return noopLogger
}
func (t *TCPTransport) handleConnection(conn *net.TCPConn) {
t.debugLog().Log("msg", "TCPTransport: New connection", "addr", conn.RemoteAddr())
closeConn := true
defer func() {
if closeConn {
_ = conn.Close()
}
}()
// let's read first byte, and determine what to do about this connection
msgType := []byte{0}
_, err := io.ReadFull(conn, msgType)
if err != nil {
level.Error(t.logger).Log("msg", "TCPTransport: failed to read message type", "err", err)
return
}
if messageType(msgType[0]) == stream {
t.incomingStreams.Inc()
// hand over this connection to memberlist
closeConn = false
t.connCh <- conn
} else if messageType(msgType[0]) == packet {
// it's a memberlist "packet", which contains an address and data.
t.receivedPackets.Inc()
// before reading packet, read the address
b := []byte{0}
_, err := io.ReadFull(conn, b)
if err != nil {
t.receivedPacketsErrors.Inc()
level.Error(t.logger).Log("msg", "TCPTransport: error while reading address:", "err", err)
return
}
addrBuf := make([]byte, b[0])
_, err = io.ReadFull(conn, addrBuf)
if err != nil {
t.receivedPacketsErrors.Inc()
level.Error(t.logger).Log("msg", "TCPTransport: error while reading address:", "err", err)
return
}
// read the rest to buffer -- this is the "packet" itself
buf, err := ioutil.ReadAll(conn)
if err != nil {
t.receivedPacketsErrors.Inc()
level.Error(t.logger).Log("msg", "TCPTransport: error while reading packet data:", "err", err)
return
}
if len(buf) < md5.Size {
t.receivedPacketsErrors.Inc()
level.Error(t.logger).Log("msg", "TCPTransport: not enough data received", "length", len(buf))
return
}
receivedDigest := buf[len(buf)-md5.Size:]
buf = buf[:len(buf)-md5.Size]
expectedDigest := md5.Sum(buf)
if !bytes.Equal(receivedDigest, expectedDigest[:]) {
t.receivedPacketsErrors.Inc()
level.Warn(t.logger).Log("msg", "TCPTransport: packet digest mismatch", "expected", fmt.Sprintf("%x", expectedDigest), "received", fmt.Sprintf("%x", receivedDigest))
}
t.debugLog().Log("msg", "TCPTransport: Received packet", "addr", addr(addrBuf), "size", len(buf), "hash", fmt.Sprintf("%x", receivedDigest))
t.receivedPacketsBytes.Add(float64(len(buf)))
t.packetCh <- &memberlist.Packet{
Buf: buf,
From: addr(addrBuf),
Timestamp: time.Now(),
}
} else {
t.unknownConnections.Inc()
level.Error(t.logger).Log("msg", "TCPTransport: unknown message type", "msgType", msgType)
}
}
type addr string
func (a addr) Network() string {
return "tcp"
}
func (a addr) String() string {
return string(a)
}
// GetAutoBindPort returns the bind port that was automatically given by the
// kernel, if a bind port of 0 was given.
func (t *TCPTransport) GetAutoBindPort() int {
// We made sure there's at least one TCP listener, and that one's
// port was applied to all the others for the dynamic bind case.
return t.tcpListeners[0].Addr().(*net.TCPAddr).Port
}
// FinalAdvertiseAddr is given the user's configured values (which
// might be empty) and returns the desired IP and port to advertise to
// the rest of the cluster.
// (Copied from memberlist' net_transport.go)
func (t *TCPTransport) FinalAdvertiseAddr(ip string, port int) (net.IP, int, error) {
var advertiseAddr net.IP
var advertisePort int
if ip != "" {
// If they've supplied an address, use that.
advertiseAddr = net.ParseIP(ip)
if advertiseAddr == nil {
return nil, 0, fmt.Errorf("failed to parse advertise address %q", ip)
}
// Ensure IPv4 conversion if necessary.
if ip4 := advertiseAddr.To4(); ip4 != nil {
advertiseAddr = ip4
}
advertisePort = port
} else {
if t.cfg.BindAddrs[0] == zeroZeroZeroZero {
// Otherwise, if we're not bound to a specific IP, let's
// use a suitable private IP address.
var err error
ip, err = sockaddr.GetPrivateIP()
if err != nil {
return nil, 0, fmt.Errorf("failed to get interface addresses: %v", err)
}
if ip == "" {
return nil, 0, fmt.Errorf("no private IP address found, and explicit IP not provided")
}
advertiseAddr = net.ParseIP(ip)
if advertiseAddr == nil {
return nil, 0, fmt.Errorf("failed to parse advertise address: %q", ip)
}
} else {
// Use the IP that we're bound to, based on the first
// TCP listener, which we already ensure is there.
advertiseAddr = t.tcpListeners[0].Addr().(*net.TCPAddr).IP
}
// Use the port we are bound to.
advertisePort = t.GetAutoBindPort()
}
level.Debug(t.logger).Log("msg", "FinalAdvertiseAddr", "advertiseAddr", advertiseAddr.String(), "advertisePort", advertisePort)
t.setAdvertisedAddr(advertiseAddr, advertisePort)
return advertiseAddr, advertisePort, nil
}
func (t *TCPTransport) setAdvertisedAddr(advertiseAddr net.IP, advertisePort int) {
t.advertiseMu.Lock()
defer t.advertiseMu.Unlock()
addr := net.TCPAddr{IP: advertiseAddr, Port: advertisePort}
t.advertiseAddr = addr.String()
}
func (t *TCPTransport) getAdvertisedAddr() string {
t.advertiseMu.RLock()
defer t.advertiseMu.RUnlock()
return t.advertiseAddr
}
// WriteTo is a packet-oriented interface that fires off the given
// payload to the given address.
func (t *TCPTransport) WriteTo(b []byte, addr string) (time.Time, error) {
t.sentPackets.Inc()
t.sentPacketsBytes.Add(float64(len(b)))
err := t.writeTo(b, addr)
if err != nil {
t.sentPacketsErrors.Inc()
if t.cfg.ReportWriteToErrors {
return time.Time{}, fmt.Errorf("WriteTo %s: %w", addr, err)
}
level.Warn(t.logger).Log("msg", "TCPTransport: WriteTo failed", "addr", addr, "err", err)
return time.Now(), nil
}
return time.Now(), nil
}
func (t *TCPTransport) writeTo(b []byte, addr string) error {
// Open connection, write packet header and data, data hash, close. Simple.
c, err := net.DialTimeout("tcp", addr, t.cfg.PacketDialTimeout)
if err != nil {
return nil
}
closed := false
defer func() {
if !closed {
// If we still need to close, then there was another error. Ignore this one.
_ = c.Close()
}
}()
if t.cfg.PacketWriteTimeout > 0 {
deadline := time.Now().Add(t.cfg.PacketWriteTimeout)
err := c.SetDeadline(deadline)
if err != nil {
return fmt.Errorf("setting deadline: %v", err)
}
}
buf := bytes.Buffer{}
buf.WriteByte(byte(packet))
// We need to send our address to the other side, otherwise other side can only see IP and port from TCP header.
// But that doesn't match our node address (new TCP connection has new random port), which confuses memberlist.
// So we send our advertised address, so that memberlist on the receiving side can match it with correct node.
// This seems to be important for node probes (pings) done by memberlist.
ourAddr := t.getAdvertisedAddr()
if len(ourAddr) > 255 {
return fmt.Errorf("local address too long")
}
buf.WriteByte(byte(len(ourAddr)))
buf.WriteString(ourAddr)
_, err = c.Write(buf.Bytes())
if err != nil {
return fmt.Errorf("sending local address: %v", err)
}
n, err := c.Write(b)
if err != nil {
return fmt.Errorf("sending data: %v", err)
}
if n != len(b) {
return fmt.Errorf("sending data: short write")
}
// Append digest. We use md5 as quick and relatively short hash, not in cryptographic context.
// This helped to find some bugs, so let's keep it.
digest := md5.Sum(b)
n, err = c.Write(digest[:])
if err != nil {
return fmt.Errorf("digest: %v", err)
}
if n != len(digest) {
return fmt.Errorf("digest: short write")
}
closed = true
err = c.Close()
if err != nil {
return fmt.Errorf("close: %v", err)
}
t.debugLog().Log("msg", "WriteTo: packet sent", "addr", addr, "size", len(b), "hash", fmt.Sprintf("%x", digest))
return nil
}
// PacketCh returns a channel that can be read to receive incoming
// packets from other peers.
func (t *TCPTransport) PacketCh() <-chan *memberlist.Packet {
return t.packetCh
}
// DialTimeout is used to create a connection that allows memberlist to perform
// two-way communication with a peer.
func (t *TCPTransport) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {
t.outgoingStreams.Inc()
c, err := net.DialTimeout("tcp", addr, timeout)
if err != nil {
t.outgoingStreamErrors.Inc()
return nil, err
}
_, err = c.Write([]byte{byte(stream)})
if err != nil {
t.outgoingStreamErrors.Inc()
_ = c.Close()
return nil, err
}
return c, nil
}
// StreamCh returns a channel that can be read to handle incoming stream
// connections from other peers.
func (t *TCPTransport) StreamCh() <-chan net.Conn {
return t.connCh
}
// Shutdown is called when memberlist is shutting down; this gives the
// transport a chance to clean up any listeners.
func (t *TCPTransport) Shutdown() error {
// This will avoid log spam about errors when we shut down.
t.shutdown.Store(1)
// Rip through all the connections and shut them down.
for _, conn := range t.tcpListeners {
_ = conn.Close()
}
// Block until all the listener threads have died.
t.wg.Wait()
return nil
}
func (t *TCPTransport) registerMetrics() {
const subsystem = "memberlist_tcp_transport"
t.incomingStreams = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "incoming_streams_total",
Help: "Number of incoming memberlist streams",
})
t.outgoingStreams = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "outgoing_streams_total",
Help: "Number of outgoing streams",
})
t.outgoingStreamErrors = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "outgoing_stream_errors_total",
Help: "Number of errors when opening memberlist stream to another node",
})
t.receivedPackets = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_received_total",
Help: "Number of received memberlist packets",
})
t.receivedPacketsBytes = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_received_bytes_total",
Help: "Total bytes received as packets",
})
t.receivedPacketsErrors = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_received_errors_total",
Help: "Number of errors when receiving memberlist packets",
})
t.sentPackets = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_sent_total",
Help: "Number of memberlist packets sent",
})
t.sentPacketsBytes = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_sent_bytes_total",
Help: "Total bytes sent as packets",
})
t.sentPacketsErrors = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "packets_sent_errors_total",
Help: "Number of errors when sending memberlist packets",
})
t.unknownConnections = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: t.cfg.MetricsNamespace,
Subsystem: subsystem,
Name: "unknown_connections_total",
Help: "Number of unknown TCP connections (not a packet or stream)",
})
if t.cfg.MetricsRegisterer == nil {
return
}
all := []prometheus.Metric{
t.incomingStreams,
t.outgoingStreams,
t.outgoingStreamErrors,
t.receivedPackets,
t.receivedPacketsBytes,
t.receivedPacketsErrors,
t.sentPackets,
t.sentPacketsBytes,
t.sentPacketsErrors,
t.unknownConnections,
}
// if registration fails, that's too bad, but don't panic
for _, c := range all {
t.cfg.MetricsRegisterer.MustRegister(c.(prometheus.Collector))
}
}