-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathclient.go
651 lines (582 loc) · 14.4 KB
/
client.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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
package tunnel
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff"
"github.com/paralus/relay/pkg/proxy"
"github.com/paralus/relay/pkg/relaylogger"
"github.com/paralus/relay/pkg/utils"
"golang.org/x/net/http2"
)
// ClientConfig ..
type ClientConfig struct {
//ServiceName name of the service
ServiceName string
// ServerAddr specifies address of the tunnel server.
ServerAddr string
//Upstream upstream address
Upstream string
//Protocol ..
Protocol string
// TLSClientConfig specifies the tls configuration to use with
// tls.Client.
TLSClientConfig *tls.Config
// Backoff specifies backoff policy on server connection retry. If nil
// when dial fails it will not be retried.
Backoff Backoff
//ServiceProxy is Func responsible for transferring data between server and local services.
ServiceProxy proxy.Func
// Logger is optional logger. If nil logging is disabled.
Logger *relaylogger.RelayLog
}
// Client struct
type Client struct {
sync.Mutex
conn net.Conn
httpServer *http2.Server
serverErr error
lastDisconnect time.Time
config *ClientConfig
logger *relaylogger.RelayLog
closeChnl chan bool
streams int64
lastRequest time.Time
lastRequestStreams int64
isScaledConnection bool
}
var (
clog *relaylogger.RelayLog
//Clients map, key by ServerName
//Clients = make(map[string]*Client)
ScaleClients = make(chan bool, 5)
)
func expBackoff(c BackoffConfig) *backoff.ExponentialBackOff {
b := backoff.NewExponentialBackOff()
b.InitialInterval = c.Interval
b.Multiplier = c.Multiplier
b.MaxInterval = c.MaxInterval
b.MaxElapsedTime = c.MaxTime
return b
}
// loadNewRelayNetwork start the relay agent for a given network
func loadNewRelayNetwork(ctx context.Context, rnc utils.RelayNetworkConfig) error {
var spxy proxy.Func
var tlsconf *tls.Config
var dialout *Dialout
var err error
backoff := BackoffConfig{
Interval: DefaultBackoffInterval,
Multiplier: DefaultBackoffMultiplier,
MaxInterval: DefaultBackoffMaxInterval,
MaxTime: DefaultBackoffMaxTime,
}
//proxy handler
switch rnc.Network.Name {
case utils.CDAGENTCORE:
tlsconf, err = ClientTLSConfigFromBytes(rnc.RelayAgentCert, rnc.RelayAgentKey, rnc.RelayAgentCACert, strings.ReplaceAll(rnc.Network.Domain, "*", utils.AgentID))
if err != nil {
clog.Error(
err,
"failed to create tlsconfig",
"service name", rnc.Network.Name,
"addr", rnc.Network.Domain,
)
return fmt.Errorf("failed to load client certs")
}
dialout = &Dialout{
Protocol: rnc.Network.Name,
Upstream: rnc.Network.Upstream,
Addr: strings.ReplaceAll(rnc.Network.Domain, "*", utils.AgentID),
ServiceSNI: utils.AgentID,
}
spxy = clientProxy(utils.GENTCP, dialout, clog.WithName(rnc.Network.Name))
default:
tlsconf, err = ClientTLSConfigFromBytes(rnc.RelayAgentCert, rnc.RelayAgentKey, rnc.RelayAgentCACert, strings.ReplaceAll(rnc.Network.Domain, "*", utils.ClusterID))
if err != nil {
clog.Error(
err,
"failed to create tlsconfig",
"service name", rnc.Network.Name,
"addr", rnc.Network.Domain,
)
return fmt.Errorf("failed to load client certs")
}
dialout = &Dialout{
Protocol: rnc.Network.Name,
Upstream: rnc.Network.Upstream,
Addr: strings.ReplaceAll(rnc.Network.Domain, "*", utils.ClusterID),
ServiceSNI: utils.ClusterID,
}
spxy = clientProxy(utils.KUBECTL, dialout, clog.WithName(rnc.Network.Name))
}
if spxy == nil {
return fmt.Errorf("failed to load client proxy")
}
ccfg := &ClientConfig{
ServiceName: rnc.Network.Name,
ServerAddr: dialout.Addr,
Protocol: dialout.Protocol,
TLSClientConfig: tlsconf,
Upstream: dialout.Upstream,
ServiceProxy: spxy,
Backoff: expBackoff(backoff),
Logger: clog.WithName(rnc.Network.Name),
}
for i := 0; i < utils.MaxDials; i++ {
c := &Client{
config: ccfg,
httpServer: &http2.Server{},
logger: clog.WithName(rnc.Network.Name),
isScaledConnection: false,
}
c.closeChnl = make(chan bool)
go c.runClient(ctx)
}
// scale clients
// based on rate of new streams or
// based on total concurrent streams
go runClientScaling(ctx, ccfg, rnc)
return nil
}
func runClientScaling(ctx context.Context, ccfg *ClientConfig, rnc utils.RelayNetworkConfig) {
var scaledClients []*Client
totalScaledClient := 0
for {
select {
case <-ScaleClients:
// got signal to scale
if totalScaledClient < utils.MaxDials*utils.MaxScaleMultiplier {
c := &Client{
config: ccfg,
httpServer: &http2.Server{},
logger: clog.WithName(rnc.Network.Name),
isScaledConnection: true,
}
c.closeChnl = make(chan bool)
scaledClients = append(scaledClients, c)
totalScaledClient++
go c.runClient(ctx)
clog.Info(
"scale client signal",
" totalScaledClient ", totalScaledClient,
)
}
case <-time.After(5 * time.Minute):
tempClients := scaledClients[:0]
for _, c := range scaledClients {
now := time.Now()
c.Lock()
curStreams := atomic.LoadInt64(&c.streams)
d := now.Sub(c.lastRequest)
s := int64(d / time.Hour)
if curStreams <= 0 && s >= int64(utils.HealingInterval) {
// no request for last 24Hr, close client
c.closeChnl <- true
totalScaledClient--
} else {
tempClients = append(tempClients, c)
}
c.Unlock()
}
scaledClients = tempClients
clog.Info(
"scaled client timer",
" totalScaledClient ", totalScaledClient,
)
case <-ctx.Done():
return
}
}
}
func (c *Client) runClient(ctx context.Context) {
if err := c.Start(ctx); err != nil {
if c.isScaledConnection {
c.logger.Info(
"closed scaled dialouts after idle time",
"service name", c.config.ServiceName,
"addr", c.config.ServerAddr,
)
} else {
c.logger.Error(
err,
"failed to start client for dialouts",
"service name", c.config.ServiceName,
"addr", c.config.ServerAddr,
)
}
}
}
// Start relay client
func (c *Client) Start(ctx context.Context) error {
cw := make(chan bool)
for {
conn, err := c.connect()
if err != nil {
c.logger.Info(
"connect failed will retry after 2 sec",
)
time.Sleep(2 * time.Second)
continue
}
go func() {
//handles the http/2 tunnel
c.httpServer.ServeConn(conn, &http2.ServeConnOpts{
Handler: http.HandlerFunc(c.serveHTTP),
})
cw <- true
}()
select {
case <-cw:
// dialout got closed
time.Sleep(100 * time.Millisecond)
case <-c.closeChnl:
c.conn.Close()
c.logger.Info(
"close connection due to idle streams",
)
return fmt.Errorf("idle streams")
case <-ctx.Done():
c.conn.Close()
return fmt.Errorf("ctx done")
}
c.logger.Info(
"client disconnected",
)
c.Lock()
now := time.Now()
err = c.serverErr
// detect disconnect hiccup
if err == nil && now.Sub(c.lastDisconnect).Seconds() < 5 {
err = fmt.Errorf("connection is being cut")
}
c.conn = nil
c.serverErr = nil
c.lastDisconnect = now
c.Unlock()
if err != nil {
c.logger.Error(
err,
"disconnected, will retry after 2 sec",
"name", c.config.ServiceName,
)
time.Sleep(2 * time.Second)
continue
}
}
}
func (c *Client) processDialoutProxy(conn net.Conn, network, addr string) error {
// send CONNECT addr HTTP/1.1 header
connHeader := "CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n"
if utils.DialoutProxyAuth != "" {
connHeader = connHeader + "Proxy-Authorization:" + utils.DialoutProxyAuth + "\r\n"
}
connHeader = connHeader + "Connection: Keep-Alive\r\n\r\n"
conn.Write([]byte(connHeader))
tmp := make([]byte, 1)
checkHeader := ""
startAppend := false
respData := ""
for {
n, err := conn.Read(tmp)
if n != 1 || err != nil {
c.logger.Info(
"dial failed ",
"proxy", utils.DialoutProxy,
"proxy header", connHeader,
"network", network,
"checkHeader", checkHeader,
"err", err,
)
return fmt.Errorf("proxy read error")
}
respData += string(tmp[0])
if tmp[0] == '\r' {
if startAppend {
checkHeader += string(tmp[0])
} else {
checkHeader = "\r"
startAppend = true
}
} else if tmp[0] == '\n' {
if startAppend {
if checkHeader == "\r\n\r" {
// prased the proxy response header
break
}
checkHeader += string(tmp)
}
} else {
startAppend = false
checkHeader = ""
}
}
c.logger.Info(
"proxy dialout success",
"proxy resp", respData,
)
return nil
}
// dialout connect
func (c *Client) connect() (net.Conn, error) {
c.Lock()
defer c.Unlock()
if c.conn != nil {
return nil, fmt.Errorf("already connected")
}
conn, err := c.dial()
if err != nil {
return nil, fmt.Errorf("failed to connect to server %s error %s", c.config.ServerAddr, err)
}
c.conn = conn
return conn, nil
}
// dial
func (c *Client) dial() (net.Conn, error) {
var (
network = "tcp"
addr = c.config.ServerAddr
tlsConfig = c.config.TLSClientConfig
)
doDial := func() (conn net.Conn, err error) {
d := &net.Dialer{
Timeout: 60 * time.Second,
}
if utils.DialoutProxy == "" {
conn, err = d.Dial(network, addr)
} else {
conn, err = d.Dial(network, utils.DialoutProxy)
if err == nil {
err = c.processDialoutProxy(conn, network, addr)
}
}
if err == nil {
err = utils.KeepAlive(conn)
}
if err == nil {
conn = tls.Client(conn, tlsConfig)
}
if err == nil {
err = conn.(*tls.Conn).Handshake()
}
if err != nil {
if conn != nil {
conn.Close()
conn = nil
}
c.logger.Info(
"dial failed",
"network", network,
"addr", addr,
"err", err,
)
}
c.logger.Info(
"action dial out",
"network", network,
"addr", addr,
)
return
}
b := c.config.Backoff
if b == nil {
// try once and return
return doDial()
}
for {
conn, err := doDial()
// success
if err == nil {
b.Reset()
c.logger.Info(
"dial success",
)
return conn, err
}
// failure
d := b.NextBackOff()
if d < 0 {
b.Reset()
return conn, fmt.Errorf("backoff limit exeded: %s", err)
}
// backoff
c.logger.Info(
"action backoff",
"sleep", d,
"address", c.config.ServerAddr,
)
time.Sleep(d)
}
}
// tunnel serveHTTP handler. Requests form relay lands here.
// request handled based on the action in the ctrl message (header)
// Connect method is used as handshake
// PUT method is used for tunneled requests that carry
// stream data as req.Body
func (c *Client) serveHTTP(w http.ResponseWriter, r *http.Request) {
c.logger.Debug(
"invoked handler serveHTTP",
"method", r.Method,
"currentStreams", atomic.LoadInt64(&c.streams),
)
if r.Method == http.MethodConnect {
if r.Header.Get(utils.HeaderError) != "" {
c.handleHandshakeError(w, r)
} else {
c.handleHandshake(w, r)
}
return
}
atomic.AddInt64(&c.streams, 1)
defer atomic.AddInt64(&c.streams, ^int64(0))
curStreams := atomic.LoadInt64(&c.streams)
now := time.Now()
c.Lock()
d := now.Sub(c.lastRequest)
s := int64(d / time.Second)
if s >= 4 { // check in minimum 4 sec
if !c.isScaledConnection {
if curStreams > int64(utils.ScalingStreamsThreshold) {
// concurrent streams count is high
ScaleClients <- true
} else if curStreams > c.lastRequestStreams {
rate := (curStreams - c.lastRequestStreams) / s
if rate > int64(utils.ScalingStreamsRateThreshold) {
// rate of new stream is high
ScaleClients <- true
}
}
}
c.lastRequest = now
c.lastRequestStreams = curStreams
}
c.Unlock()
msg, err := utils.ReadControlMessage(r)
if err != nil {
c.logger.Error(
err,
"Read Control Message failed",
)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
c.logger.Debug(
"handle proxy action",
"ctrlMsg", msg,
"req", r,
"currentStreams", atomic.LoadInt64(&c.streams),
)
switch msg.Action {
case utils.ActionProxy:
c.config.ServiceProxy(w, r.Body, msg, r)
default:
c.logger.Info(
"unknown action",
"ctrlMsg", msg,
)
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
func (c *Client) handleHandshakeError(w http.ResponseWriter, r *http.Request) {
err := fmt.Errorf(r.Header.Get(utils.HeaderError))
c.logger.Info(
"action handshake error",
"addr", r.RemoteAddr,
"err", err,
)
c.Lock()
c.serverErr = fmt.Errorf("server error: %s", err)
c.Unlock()
}
func (c *Client) handleHandshake(w http.ResponseWriter, r *http.Request) {
c.logger.Info(
"action", "handshake",
"addr", r.RemoteAddr,
)
w.WriteHeader(http.StatusOK)
host, _, _ := net.SplitHostPort(c.config.ServerAddr)
msg := handShakeMsg{
ServiceName: c.config.ServiceName,
Protocol: c.config.Protocol,
Host: host,
}
b, err := json.Marshal(msg)
if err != nil {
c.logger.Info(
"msg", "handshake failed",
"err", err,
)
return
}
w.Write(b)
}
// setups the proxy func handler
func clientProxy(svcName string, d *Dialout, logger *relaylogger.RelayLog) proxy.Func {
proxyCfg := &utils.ProxyConfig{
Protocol: d.Protocol,
Addr: d.Addr,
ServiceSNI: d.ServiceSNI,
RootCA: d.RootCA,
ClientCRT: d.ClientCRT,
ClientKEY: d.ClientKEY,
Upstream: d.Upstream,
UpstreamClientCRT: d.UpstreamClientCRT,
UpstreamClientKEY: d.UpstreamClientKEY,
UpstreamRootCA: d.UpstreamRootCA,
UpstreamSkipVerify: d.UpstreamSkipVerify,
UpstreamKubeConfig: d.UpstreamKubeConfig,
Version: d.Version,
}
switch svcName {
case utils.KUBECTL:
if p := proxy.NewKubeCtlTCPProxy(logger.WithName("TCPProxy"), proxyCfg); p != nil {
return p.Proxy
}
logger.Error(
nil,
"proxy.NewKubeCtlTCPProxy returned nil",
)
return nil
case utils.GENTCP:
if p := proxy.NewTCPProxy(logger.WithName("TCPProxy"), proxyCfg); p != nil {
return p.Proxy
}
logger.Error(
nil,
"proxy.NewTCPProxy returned nil",
)
return nil
default:
logger.Error(
nil,
"unknown service name",
)
return nil
}
}
// StartClient starts relay clients
func StartClient(ctx context.Context, log *relaylogger.RelayLog, file string, rnc utils.RelayNetworkConfig, exitChan chan<- bool) {
clog = log.WithName("Client")
if err := loadNewRelayNetwork(ctx, rnc); err != nil {
clog.Error(err, "failed to load relay network")
exitChan <- true
return
}
for {
select {
case <-ctx.Done():
clog.Error(
ctx.Err(),
"Stopping client",
)
return
}
}
}