-
Notifications
You must be signed in to change notification settings - Fork 449
/
proxy.go
247 lines (205 loc) · 5.31 KB
/
proxy.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
package toxiproxy
import (
"errors"
"net"
"sync"
"github.com/rs/zerolog"
tomb "gopkg.in/tomb.v1"
"github.com/Shopify/toxiproxy/v2/stream"
)
// Proxy represents the proxy in its entirety with all its links. The main
// responsibility of Proxy is to accept new client and create Links between the
// client and upstream.
//
// Client <-> toxiproxy <-> Upstream.
type Proxy struct {
sync.Mutex
Name string `json:"name"`
Listen string `json:"listen"`
Upstream string `json:"upstream"`
Enabled bool `json:"enabled"`
listener net.Listener
started chan error
tomb tomb.Tomb
connections ConnectionList
Toxics *ToxicCollection `json:"-"`
apiServer *ApiServer
Logger *zerolog.Logger
}
type ConnectionList struct {
list map[string]net.Conn
lock sync.Mutex
}
func (c *ConnectionList) Lock() {
c.lock.Lock()
}
func (c *ConnectionList) Unlock() {
c.lock.Unlock()
}
var ErrProxyAlreadyStarted = errors.New("Proxy already started")
func NewProxy(server *ApiServer, name, listen, upstream string) *Proxy {
l := server.Logger.
With().
Str("name", name).
Str("listen", listen).
Str("upstream", upstream).
Logger()
proxy := &Proxy{
Name: name,
Listen: listen,
Upstream: upstream,
started: make(chan error),
connections: ConnectionList{list: make(map[string]net.Conn)},
apiServer: server,
Logger: &l,
}
proxy.Toxics = NewToxicCollection(proxy)
return proxy
}
func (proxy *Proxy) Start() error {
proxy.Lock()
defer proxy.Unlock()
return start(proxy)
}
func (proxy *Proxy) Update(input *Proxy) error {
proxy.Lock()
defer proxy.Unlock()
if input.Listen != proxy.Listen || input.Upstream != proxy.Upstream {
stop(proxy)
proxy.Listen = input.Listen
proxy.Upstream = input.Upstream
}
if input.Enabled != proxy.Enabled {
if input.Enabled {
return start(proxy)
}
stop(proxy)
}
return nil
}
func (proxy *Proxy) Stop() {
proxy.Lock()
defer proxy.Unlock()
stop(proxy)
}
func (proxy *Proxy) listen() error {
var err error
proxy.listener, err = net.Listen("tcp", proxy.Listen)
if err != nil {
proxy.started <- err
return err
}
proxy.Listen = proxy.listener.Addr().String()
proxy.started <- nil
proxy.Logger.
Info().
Msg("Started proxy")
return nil
}
func (proxy *Proxy) close() {
// Unblock proxy.listener.Accept()
err := proxy.listener.Close()
if err != nil {
proxy.Logger.
Warn().
Err(err).
Msg("Attempted to close an already closed proxy server")
}
}
// This channel is to kill the blocking Accept() call below by closing the
// net.Listener.
func (proxy *Proxy) freeBlocker(acceptTomb *tomb.Tomb) {
<-proxy.tomb.Dying()
// Notify ln.Accept() that the shutdown was safe
acceptTomb.Killf("Shutting down from stop()")
proxy.close()
// Wait for the accept loop to finish processing
acceptTomb.Wait()
proxy.tomb.Done()
}
// server runs the Proxy server, accepting new clients and creating Links to
// connect them to upstreams.
func (proxy *Proxy) server() {
err := proxy.listen()
if err != nil {
return
}
acceptTomb := &tomb.Tomb{}
defer acceptTomb.Done()
// This channel is to kill the blocking Accept() call below by closing the
// net.Listener.
go proxy.freeBlocker(acceptTomb)
for {
client, err := proxy.listener.Accept()
if err != nil {
// This is to confirm we're being shut down in a legit way. Unfortunately,
// Go doesn't export the error when it's closed from Close() so we have to
// sync up with a channel here.
//
// See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/
select {
case <-acceptTomb.Dying():
default:
proxy.Logger.
Warn().
Err(err).
Msg("Error while accepting client")
}
return
}
proxy.Logger.
Info().
Str("client", client.RemoteAddr().String()).
Msg("Accepted client")
upstream, err := net.Dial("tcp", proxy.Upstream)
if err != nil {
proxy.Logger.
Err(err).
Str("client", client.RemoteAddr().String()).
Msg("Unable to open connection to upstream")
client.Close()
continue
}
name := client.RemoteAddr().String()
proxy.connections.Lock()
proxy.connections.list[name+"upstream"] = upstream
proxy.connections.list[name+"downstream"] = client
proxy.connections.Unlock()
proxy.Toxics.StartLink(proxy.apiServer, name+"upstream", client, upstream, stream.Upstream)
proxy.Toxics.StartLink(proxy.apiServer, name+"downstream", upstream, client, stream.Downstream)
}
}
func (proxy *Proxy) RemoveConnection(name string) {
proxy.connections.Lock()
defer proxy.connections.Unlock()
delete(proxy.connections.list, name)
}
// Starts a proxy, assumes the lock has already been taken.
func start(proxy *Proxy) error {
if proxy.Enabled {
return ErrProxyAlreadyStarted
}
proxy.tomb = tomb.Tomb{} // Reset tomb, from previous starts/stops
go proxy.server()
err := <-proxy.started
// Only enable the proxy if it successfully started
proxy.Enabled = err == nil
return err
}
// Stops a proxy, assumes the lock has already been taken.
func stop(proxy *Proxy) {
if !proxy.Enabled {
return
}
proxy.Enabled = false
proxy.tomb.Killf("Shutting down from stop()")
proxy.tomb.Wait() // Wait until we stop accepting new connections
proxy.connections.Lock()
defer proxy.connections.Unlock()
for _, conn := range proxy.connections.list {
conn.Close()
}
proxy.Logger.
Info().
Msg("Terminated proxy")
}