/
tcp_listener.go
107 lines (90 loc) · 2.12 KB
/
tcp_listener.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
package main
import (
"fmt"
"net"
"time"
log "github.com/hashicorp/go-hclog"
)
type tcpListener struct {
addr string
standbyOK bool
statusChange <-chan vaultStatus
logger log.Logger
listener net.Listener
shutdown chan struct{}
}
func newTCPListener(addr string, standbyOK bool, logger log.Logger, statusChange <-chan vaultStatus) *tcpListener {
return &tcpListener{
addr: addr,
standbyOK: standbyOK,
logger: logger,
statusChange: statusChange,
shutdown: make(chan struct{}, 1),
}
}
func (tl *tcpListener) run() {
for {
status := <-tl.statusChange
shouldRun := false
switch status {
case vaultStatusActive:
tl.logger.Info("Vault Status: Healthy (Active)")
shouldRun = true
case vaultStatusStandby:
if tl.standbyOK {
tl.logger.Info("Vault Status: Healthy (Standby)")
shouldRun = true
} else {
tl.logger.Info("Vault Status: Unhealthy (Standby)")
shouldRun = false
}
case vaultStatusDRSecondary:
tl.logger.Info("Vault Status: Healthy (Active DR Secondary)")
shouldRun = true
case vaultStatusPerformanceStandby:
tl.logger.Info("Vault Status: Healthy (Performance Standby)")
shouldRun = true
case vaultStatusUnhealthy:
tl.logger.Info("Vault Status: Unhealthy")
shouldRun = false
}
if shouldRun {
if tl.listener != nil {
continue
}
go tl.runListener()
} else {
if tl.listener != nil {
tl.shutdown <- struct{}{}
tl.listener.Close()
tl.logger.Info(fmt.Sprintf("Listener %s closed", tl.addr))
}
}
}
}
func (tl *tcpListener) runListener() {
listener, err := net.Listen("tcp", tl.addr)
if err != nil {
tl.logger.Error(fmt.Sprintf("TCP Listener Error: %s", err))
return
}
tl.logger.Info(fmt.Sprintf("Listening on %s...", tl.addr))
tl.listener = listener
for {
conn, err := listener.Accept()
if err != nil {
tl.logger.Error(fmt.Sprintf("Error accepting connection: %s", err))
select {
case <-tl.shutdown:
break
default:
continue
}
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
time.Sleep(500 * time.Millisecond)
}