forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadbalancer.go
271 lines (238 loc) · 6.26 KB
/
loadbalancer.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
/*
Copyright 2017 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"context"
"io"
"net"
"sync"
"time"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// NewLoadBalancer returns new load balancer listening on frontend
// and redirecting requests to backends using round robin algo
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error) {
if ctx == nil {
return nil, trace.BadParameter("missing parameter context")
}
waitCtx, waitCancel := context.WithCancel(ctx)
return &LoadBalancer{
frontend: frontend,
ctx: ctx,
backends: backends,
currentIndex: -1,
waitCtx: waitCtx,
waitCancel: waitCancel,
Entry: log.WithFields(log.Fields{
trace.Component: "loadbalancer",
trace.ComponentFields: log.Fields{
"listen": frontend.String(),
},
}),
connections: make(map[NetAddr]map[int64]net.Conn),
}, nil
}
// LoadBalancer implements naive round robin TCP load
// balancer used in tests.
type LoadBalancer struct {
sync.RWMutex
connID int64
*log.Entry
frontend NetAddr
backends []NetAddr
ctx context.Context
currentIndex int
listener net.Listener
listenerClosed bool
connections map[NetAddr]map[int64]net.Conn
waitCtx context.Context
waitCancel context.CancelFunc
}
// trackeConnection adds connection to the connection tracker
func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64 {
l.Lock()
defer l.Unlock()
l.connID += 1
tracker, ok := l.connections[backend]
if !ok {
tracker = make(map[int64]net.Conn)
l.connections[backend] = tracker
}
tracker[l.connID] = conn
return l.connID
}
// untrackConnection removes connection from connection tracker
func (l *LoadBalancer) untrackConnection(backend NetAddr, id int64) {
l.Lock()
defer l.Unlock()
tracker, ok := l.connections[backend]
if !ok {
return
}
delete(tracker, id)
}
// dropConnections drops connections associated with backend
func (l *LoadBalancer) dropConnections(backend NetAddr) {
tracker := l.connections[backend]
for _, conn := range tracker {
conn.Close()
}
delete(l.connections, backend)
}
// AddBackend adds backend
func (l *LoadBalancer) AddBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.backends = append(l.backends, b)
l.Debugf("backends %v", l.backends)
}
// RemoveBackend removes backend
func (l *LoadBalancer) RemoveBackend(b NetAddr) {
l.Lock()
defer l.Unlock()
l.currentIndex = -1
for i := range l.backends {
if l.backends[i].Equals(b) {
l.backends = append(l.backends[:i], l.backends[i+1:]...)
l.dropConnections(b)
return
}
}
}
func (l *LoadBalancer) nextBackend() (*NetAddr, error) {
l.Lock()
defer l.Unlock()
if len(l.backends) == 0 {
return nil, trace.ConnectionProblem(nil, "no backends")
}
l.currentIndex = ((l.currentIndex + 1) % len(l.backends))
return &l.backends[l.currentIndex], nil
}
func (l *LoadBalancer) closeListener() {
l.Lock()
defer l.Unlock()
if l.listener == nil {
return
}
if l.listenerClosed {
return
}
l.listenerClosed = true
l.listener.Close()
}
func (l *LoadBalancer) isClosed() bool {
l.RLock()
defer l.RUnlock()
return l.listenerClosed
}
func (l *LoadBalancer) Close() error {
l.closeListener()
return nil
}
// ListenAndServe starts listening socket and serves connections on it
func (l *LoadBalancer) ListenAndServe() error {
if err := l.Listen(); err != nil {
return trace.Wrap(err)
}
return l.Serve()
}
// Listen creates a listener on the frontend addr
func (l *LoadBalancer) Listen() error {
var err error
l.listener, err = net.Listen(l.frontend.AddrNetwork, l.frontend.Addr)
if err != nil {
return trace.ConvertSystemError(err)
}
l.Debugf("created listening socket")
return nil
}
// Serve starts accepting connections
func (l *LoadBalancer) Serve() error {
defer l.waitCancel()
backoffTimer := time.NewTicker(5 * time.Second)
defer backoffTimer.Stop()
for {
conn, err := l.listener.Accept()
if err != nil {
if l.isClosed() {
return trace.ConnectionProblem(nil, "listener is closed")
}
select {
case <-backoffTimer.C:
l.Debugf("backoff on network error")
case <-l.ctx.Done():
return trace.ConnectionProblem(nil, "context is closing")
}
}
go l.forwardConnection(conn)
}
}
func (l *LoadBalancer) forwardConnection(conn net.Conn) {
err := l.forward(conn)
if err != nil {
l.Warningf("failed to forward connection: %v", err)
}
}
// this is to workaround issue https://github.com/golang/go/issues/10527
// in tests
func (l *LoadBalancer) Wait() {
<-l.waitCtx.Done()
}
func (l *LoadBalancer) forward(conn net.Conn) error {
defer conn.Close()
backend, err := l.nextBackend()
if err != nil {
return trace.Wrap(err)
}
connID := l.trackConnection(*backend, conn)
defer l.untrackConnection(*backend, connID)
backendConn, err := net.Dial(backend.AddrNetwork, backend.Addr)
if err != nil {
return trace.ConvertSystemError(err)
}
defer backendConn.Close()
backendConnID := l.trackConnection(*backend, backendConn)
defer l.untrackConnection(*backend, backendConnID)
logger := l.WithFields(log.Fields{
"source": conn.RemoteAddr(),
"dest": backendConn.RemoteAddr(),
})
logger.Debugf("forward")
messagesC := make(chan error, 2)
go func() {
defer conn.Close()
defer backendConn.Close()
_, err := io.Copy(conn, backendConn)
messagesC <- err
}()
go func() {
defer conn.Close()
defer backendConn.Close()
_, err := io.Copy(backendConn, conn)
messagesC <- err
}()
var lastErr error
for i := 0; i < 2; i++ {
select {
case err := <-messagesC:
if err != nil && err != io.EOF {
logger.Warningf("connection problem: %v %T", trace.DebugReport(err), err)
lastErr = err
}
case <-l.ctx.Done():
return trace.ConnectionProblem(nil, "context is closing")
}
}
return lastErr
}