-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
tcp_layer.go
111 lines (90 loc) · 2.21 KB
/
tcp_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
package cluster
import (
"crypto/tls"
"net"
"sync"
"time"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-multierror"
"go.uber.org/atomic"
)
// TCPLayer implements the NetworkLayer interface and uses TCP as the underlying
// network.
type TCPLayer struct {
listeners []NetworkListener
addrs []*net.TCPAddr
logger log.Logger
l sync.Mutex
stopped *atomic.Bool
}
// NewTCPLayer returns a TCPLayer.
func NewTCPLayer(addrs []*net.TCPAddr, logger log.Logger) *TCPLayer {
return &TCPLayer{
addrs: addrs,
logger: logger,
stopped: atomic.NewBool(false),
}
}
// Addrs implements NetworkLayer.
func (l *TCPLayer) Addrs() []net.Addr {
l.l.Lock()
defer l.l.Unlock()
if len(l.addrs) == 0 {
return nil
}
ret := make([]net.Addr, len(l.addrs))
for i, a := range l.addrs {
ret[i] = a
}
return ret
}
// Listeners implements NetworkLayer. It starts a new TCP listener for each
// configured address.
func (l *TCPLayer) Listeners() []NetworkListener {
l.l.Lock()
defer l.l.Unlock()
if l.listeners != nil {
return l.listeners
}
listeners := []NetworkListener{}
for i, laddr := range l.addrs {
if l.logger.IsInfo() {
l.logger.Info("starting listener", "listener_address", laddr)
}
tcpLn, err := net.ListenTCP("tcp", laddr)
if err != nil {
l.logger.Error("error starting listener", "error", err)
continue
}
if laddr.String() != tcpLn.Addr().String() {
// If we listened on port 0, record the port the OS gave us.
l.addrs[i] = tcpLn.Addr().(*net.TCPAddr)
}
listeners = append(listeners, tcpLn)
}
l.listeners = listeners
return listeners
}
// Dial implements the NetworkLayer interface.
func (l *TCPLayer) Dial(address string, timeout time.Duration, tlsConfig *tls.Config) (*tls.Conn, error) {
dialer := &net.Dialer{
Timeout: timeout,
}
return tls.DialWithDialer(dialer, "tcp", address, tlsConfig)
}
// Close implements the NetworkLayer interface.
func (l *TCPLayer) Close() error {
if l.stopped.Swap(true) {
return nil
}
l.l.Lock()
defer l.l.Unlock()
var retErr *multierror.Error
for _, ln := range l.listeners {
if err := ln.Close(); err != nil {
retErr = multierror.Append(retErr, err)
}
}
l.listeners = nil
return retErr.ErrorOrNil()
}