-
Notifications
You must be signed in to change notification settings - Fork 83
/
main.go
1409 lines (1278 loc) · 38.9 KB
/
main.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021-2024 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"context"
"crypto/ecdsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/http/pprof"
"net/url"
"os"
"os/signal"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"golang.org/x/term"
"github.com/minio/cli"
"github.com/minio/dnscache"
"github.com/minio/pkg/v3/certs"
"github.com/minio/pkg/v3/console"
"github.com/minio/pkg/v3/ellipses"
xnet "github.com/minio/pkg/v3/net"
"github.com/minio/sidekick/reverse"
)
// Use e.g.: go build -ldflags "-X main.version=v1.0.0"
// to set the binary version.
var version = "0.0.0-dev"
const (
slashSeparator = "/"
healthPath = "/v1/health"
certificatesPath = "/v1/certificates"
)
var (
globalQuietEnabled bool
globalDebugEnabled bool
globalLoggingEnabled bool
globalTrace string
globalJSONEnabled bool
globalConsoleDisplay bool
globalErrorsOnly bool
globalStatusCodes []int
globalConnStats atomic.Pointer[[]*ConnStats]
log2 *logrus.Logger
globalHostBalance string
globalTLSCert atomic.Pointer[[]byte]
)
const (
prometheusMetricsPath = "/.prometheus/metrics"
profilingPath = "/.pprof"
)
var dnsCache = &dnscache.Resolver{
Timeout: 5 * time.Second,
}
func init() {
// Create a new instance of the logger. You can have any number of instances.
log2 = logrus.New()
}
func logMsg(msg logMessage) error {
if globalQuietEnabled {
return nil
}
msg.Type = LogMsgType
msg.Timestamp = time.Now().UTC()
if !globalLoggingEnabled {
return nil
}
if globalJSONEnabled {
jsonBytes, err := json.Marshal(msg)
if err != nil {
return err
}
console.Println(string(jsonBytes))
return nil
}
console.Println(msg.String())
return nil
}
const (
// LogMsgType for log messages
LogMsgType = "LOG"
// TraceMsgType for trace messages
TraceMsgType = "TRACE"
// DebugMsgType for debug output
DebugMsgType = "DEBUG"
)
type logMessage struct {
Type string `json:"Type"`
// Endpoint of backend
Endpoint string `json:"Endpoint"`
// Error message
Error string `json:"Error,omitempty"`
// Status of endpoint
Status string `json:"Status,omitempty"`
// Downtime so far
DowntimeDuration time.Duration `json:"Downtime,omitempty"`
Timestamp time.Time
}
func (l logMessage) String() string {
if l.Error == "" {
if l.DowntimeDuration > 0 {
return fmt.Sprintf("%s%2s: %s %s is %s Downtime duration: %s",
console.Colorize("LogMsgType", l.Type), "",
l.Timestamp.Format(timeFormat),
l.Endpoint, l.Status, l.DowntimeDuration)
}
return fmt.Sprintf("%s%2s: %s %s is %s", console.Colorize("LogMsgType", l.Type), "", l.Timestamp.Format(timeFormat),
l.Endpoint, l.Status)
}
return fmt.Sprintf("%s%2s: %s %s is %s: %s", console.Colorize("LogMsgType", l.Type), "",
l.Timestamp.Format(timeFormat), l.Endpoint, l.Status, l.Error)
}
// Backend entity to which requests gets load balanced.
type Backend struct {
ctxt context.Context
siteNumber int
endpoint string
proxy *reverse.Proxy
httpClient *http.Client
up int32
healthCheckURL string
healthCheckDuration time.Duration
healthCheckTimeout time.Duration
healthOptimistic bool
Stats *BackendStats
}
const (
offline = iota
online
)
func (b *Backend) setOffline(msg string) (swapped bool) {
if atomic.SwapInt32(&b.up, offline) == offline {
return false
}
now := time.Now().UTC()
b.Stats.Lock()
b.Stats.DowntimeStart = now
b.Stats.UpSince = time.Time{}
b.Stats.Unlock()
if b.healthOptimistic {
go b.healthCheck(false)
}
if globalLoggingEnabled {
logMsg(logMessage{
Endpoint: b.endpoint,
Status: "down",
Error: msg,
})
}
return true
}
func (b *Backend) setOnline() (swapped bool) {
if atomic.SwapInt32(&b.up, online) == online {
return false
}
now := time.Now().UTC()
b.Stats.Lock()
b.Stats.UpSince = now
if !b.Stats.DowntimeStart.IsZero() {
downtime := now.Sub(b.Stats.DowntimeStart)
b.Stats.LastDowntime = downtime
b.Stats.CumDowntime += downtime
}
b.Stats.DowntimeStart = time.Time{}
b.Stats.Unlock()
if globalLoggingEnabled {
logMsg(logMessage{
Endpoint: b.endpoint,
Status: "up",
DowntimeDuration: b.Stats.LastDowntime,
})
}
return true
}
// Online returns true if backend is up
func (b *Backend) Online() bool {
return atomic.LoadInt32(&b.up) == online
}
func (b *Backend) getServerStatus() string {
if b.Online() {
return "UP"
}
return "DOWN"
}
// BackendStats holds server stats for backend
type BackendStats struct {
LastFinished atomic.Int64
CurrentCalls atomic.Int64
sync.Mutex
LastDowntime time.Duration
CumDowntime time.Duration
TotCalls int64
TotCallFailures int64
MinLatency time.Duration
MaxLatency time.Duration
CumLatency time.Duration
Rx int64
Tx int64
UpSince time.Time
DowntimeStart time.Time
}
const errMessage = `<?xml version="1.0" encoding="UTF-8"?><Error><Code>BackendDown</Code><Message>The remote server returned an error (%v)</Message><Resource>%s</Resource></Error>`
func writeErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
// Set retry-after header to indicate user-agents to retry request after 120secs.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
w.Header().Set("Retry-After", "120")
w.WriteHeader(http.StatusBadGateway)
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintf(w, errMessage, err, r.URL.Path)
}
// ErrorHandler called by httputil.ReverseProxy for errors.
// Avoid canceled context error since it means the client disconnected.
func (b *Backend) ErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
if err == nil {
panic("reverse proxy cannot call error handler without err being set")
}
offline := true
for _, nerr := range []error{
context.Canceled,
io.EOF,
io.ErrClosedPipe,
io.ErrUnexpectedEOF,
errors.New("http: server closed idle connection"),
} {
if errors.Is(err, nerr) {
offline = false
break
}
if err.Error() == nerr.Error() {
offline = false
break
}
}
if offline {
b.setOffline(err.Error())
}
writeErrorResponse(w, r, err)
}
// registerMetricsRouter - add handler functions for metrics.
func registerMetricsRouter(router *mux.Router) error {
handler, err := metricsHandler()
if err != nil {
return err
}
router.Handle(prometheusMetricsPath, handler)
return nil
}
// A blocking call to setup a new web API for pprof - the web API
// can be consumed with go tool pprof command:
//
// e.g. go tool pprof http://localhost:6060/minio/.profile?seconds=20 for CPU profiling
func listenAndServePProf(addr string) error {
router := mux.NewRouter()
for _, profilerName := range []string{"goroutine", "threadcreate", "heap", "allocs", "block", "mutex"} {
router.Handle(profilingPath+"/"+profilerName, pprof.Handler(profilerName))
}
router.Handle(profilingPath+"/profile", http.HandlerFunc(pprof.Profile))
router.Handle(profilingPath+"/symbol", http.HandlerFunc(pprof.Symbol))
router.Handle(profilingPath+"/trace", http.HandlerFunc(pprof.Trace))
return http.ListenAndServe(addr, router)
}
const (
portLowerLimit = 0
portUpperLimit = 65535
)
// getHealthCheckURL - extracts the health check URL.
func getHealthCheckURL(endpoint, healthCheckPath string, healthCheckPort int) (string, error) {
u, err := xnet.ParseHTTPURL(strings.TrimSuffix(endpoint, slashSeparator) + healthCheckPath)
if err != nil {
return "", fmt.Errorf("invalid endpoint %q and health check path %q: %s", endpoint, healthCheckPath, err)
}
if healthCheckPort == 0 {
return u.String(), nil
}
// Validate port range which should be in [0, 65535]
if healthCheckPort < portLowerLimit || healthCheckPort > portUpperLimit {
return "", fmt.Errorf("invalid health check port \"%d\": must be in [0, 65535]", healthCheckPort)
}
// Set healthcheck port
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(healthCheckPort))
return u.String(), nil
}
// healthCheck - background routine which checks if a backend is up or down.
func (b *Backend) healthCheck(immediate bool) {
if immediate {
if err := b.doHealthCheck(); err != nil {
console.Errorln(err)
} else if b.healthOptimistic && b.Online() {
return
}
}
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
timer := time.NewTimer(b.healthCheckDuration)
defer timer.Stop()
for {
select {
case <-b.ctxt.Done():
return
case <-timer.C:
if err := b.doHealthCheck(); err != nil {
console.Errorln(err)
} else if b.healthOptimistic && b.Online() {
return
}
// Add random jitter to call
timer.Reset(b.healthCheckDuration + time.Duration(rng.Int63n(int64(b.healthCheckDuration))))
}
}
}
func drainBody(resp *http.Response) {
if resp != nil {
// Drain the connection.
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
}
func (b *Backend) doHealthCheck() error {
// Set up a maximum timeout time for the healtcheck operation
ctx, cancel := context.WithTimeout(context.Background(), b.healthCheckTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.healthCheckURL, nil)
if err != nil {
return err
}
reqTime := time.Now().UTC()
resp, err := b.httpClient.Do(req)
respTime := time.Now().UTC()
drainBody(resp)
switch {
case err != nil:
b.setOffline(err.Error())
case resp.StatusCode != http.StatusOK:
b.setOffline(fmt.Sprintf("response status %d", resp.StatusCode))
default:
b.setOnline()
}
if globalTrace != "application" {
if resp != nil {
traceHealthCheckReq(req, resp, reqTime, respTime, b, err)
}
}
return nil
}
// updateCallStats updates the cumulative stats for each call to backend
func (b *Backend) updateCallStats(t shortTraceMsg) {
b.Stats.Lock()
defer b.Stats.Unlock()
b.Stats.TotCalls++
if t.StatusCode >= http.StatusBadRequest {
b.Stats.TotCallFailures++
}
b.Stats.MaxLatency = time.Duration(int64(math.Max(float64(b.Stats.MaxLatency), float64(t.CallStats.Latency))))
b.Stats.MinLatency = time.Duration(int64(math.Min(float64(b.Stats.MinLatency), float64(t.CallStats.Latency))))
b.Stats.Rx += int64(t.CallStats.Rx)
b.Stats.Tx += int64(t.CallStats.Tx)
for _, c := range *globalConnStats.Load() {
if c == nil {
continue
}
if c.endpoint != b.endpoint {
continue
}
c.setMinLatency(b.Stats.MinLatency)
c.setMaxLatency(b.Stats.MaxLatency)
c.setInputBytes(b.Stats.Rx)
c.setOutputBytes(b.Stats.Tx)
c.setTotalCalls(b.Stats.TotCalls)
c.setTotalCallFailures(b.Stats.TotCallFailures)
if t.CallStats.HealthError != nil {
c.addHealthErrorCounts(1)
}
}
}
type multisite struct {
sites atomic.Pointer[[]*site]
healthCanceler context.CancelFunc
}
type healthCheckOptions struct {
healthCheckPath string
healthReadCheckPath string
healthCheckPort int
healthCheckDuration time.Duration
healthCheckTimeout time.Duration
healthOptimistic bool
}
func (m *multisite) renewSite(ctx *cli.Context, tlsMaxVersion uint16, opts healthCheckOptions) {
ctxt, cancel := context.WithCancel(context.Background())
var sites []*site
for i, siteStrs := range ctx.Args() {
if i == len(ctx.Args())-1 {
opts.healthCheckPath = opts.healthReadCheckPath
}
site := configureSite(ctxt, ctx, i+1, strings.Split(siteStrs, ","), tlsMaxVersion, opts)
sites = append(sites, site)
}
m.sites.Store(&sites)
// cancel the previous health checker
if m.healthCanceler != nil {
m.healthCanceler()
}
m.healthCanceler = cancel
}
func (m *multisite) displayUI(show bool) {
if !show {
return
}
go func() {
// Clear screen before we start the table UI
clearScreen()
ticker := time.NewTicker(500 * time.Millisecond)
for range ticker.C {
m.populate()
}
}()
}
func (m *multisite) populate() {
sites := *m.sites.Load()
dspOrder := []col{colGreen} // Header
for i := 0; i < len(sites); i++ {
for range sites[i].backends {
dspOrder = append(dspOrder, colGrey)
}
}
var printColors []*color.Color
for _, c := range dspOrder {
printColors = append(printColors, getPrintCol(c))
}
tbl := console.NewTable(printColors, []bool{
false, false, false, false, false, false,
false, false, false, false, false,
}, 0)
cellText := make([][]string, len(dspOrder))
cellText[0] = headers
for i, site := range sites {
for j, b := range site.backends {
b.Stats.Lock()
minLatency := "0s"
maxLatency := "0s"
if b.Stats.MaxLatency > 0 {
minLatency = fmt.Sprintf("%2s", b.Stats.MinLatency.Round(time.Microsecond))
maxLatency = fmt.Sprintf("%2s", b.Stats.MaxLatency.Round(time.Microsecond))
}
cumDowntime := b.Stats.CumDowntime
lastDowntime := b.Stats.LastDowntime
if !b.Online() {
// show current downtime and cumulative downtime including
// the current downtime
lastDowntime = time.Now().UTC().Sub(b.Stats.DowntimeStart)
cumDowntime += lastDowntime
}
cellText[i*len(site.backends)+j+1] = []string{
humanize.Ordinal(b.siteNumber),
b.endpoint,
b.getServerStatus(),
strconv.FormatInt(b.Stats.TotCalls, 10),
strconv.FormatInt(b.Stats.TotCallFailures, 10),
humanize.IBytes(uint64(b.Stats.Rx)),
humanize.IBytes(uint64(b.Stats.Tx)),
cumDowntime.Round(time.Microsecond).String(),
lastDowntime.Round(time.Microsecond).String(),
minLatency,
maxLatency,
}
b.Stats.Unlock()
}
}
console.RewindLines(len(cellText) + 2)
tbl.DisplayTable(cellText)
}
func (m *multisite) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && r.URL.Path == certificatesPath {
cert := globalTLSCert.Load()
if cert != nil {
w.Write(*cert)
} else {
http.Error(w, "no configured certificates found", http.StatusNotFound)
}
return
}
w.Header().Set("Server", "SideKick") // indicate sidekick is serving
for _, s := range *m.sites.Load() {
if s.Online() {
switch r.URL.Path {
case healthPath:
// Health check endpoint should return success
return
default:
s.ServeHTTP(w, r)
return
}
}
}
writeErrorResponse(w, r, errors.New("all backend servers are offline"))
}
type site struct {
backends []*Backend
}
func (s *site) Online() bool {
for _, backend := range s.backends {
if backend.Online() {
return true
}
}
return false
}
func (s *site) upBackends() []*Backend {
var backends []*Backend
for _, backend := range s.backends {
if backend.Online() {
backends = append(backends, backend)
}
}
return backends
}
// Returns the next backend the request should go to.
func (s *site) nextProxy() (*Backend, func()) {
backends := s.upBackends()
if len(backends) == 0 {
return nil, func() {}
}
switch globalHostBalance {
case "least":
minCall := int64(math.MaxInt64)
earliest := int64(math.MaxInt64)
idx := 0
// Shuffle before picking the least connection to ensure all nodes
// are involved if the load is low to medium.
rand.Shuffle(len(backends), func(i, j int) {
backends[i], backends[j] = backends[j], backends[i]
})
for i, backend := range backends {
currentCalls := backend.Stats.CurrentCalls.Load()
if currentCalls < minCall {
minCall = currentCalls
lastFinished := backend.Stats.LastFinished.Load()
if lastFinished < earliest {
earliest = lastFinished
idx = i
}
}
}
backend := backends[idx]
backend.Stats.CurrentCalls.Add(1)
return backend, func() {
backend.Stats.CurrentCalls.Add(-1)
backend.Stats.LastFinished.Store(time.Now().UnixNano())
}
default:
idx := rand.Intn(len(backends))
// random backend from a list of available backends.
return backends[idx], func() {}
}
}
// ServeHTTP - LoadBalancer implements http.Handler
func (s *site) ServeHTTP(w http.ResponseWriter, r *http.Request) {
backend, done := s.nextProxy()
defer done()
if backend != nil && backend.Online() {
httpTraceHdrs(backend.proxy.ServeHTTP, w, r, backend)
return
}
writeErrorResponse(w, r, fmt.Errorf("backend %v is offline", backend.endpoint))
}
// mustGetSystemCertPool - return system CAs or empty pool in case of error (or windows)
func mustGetSystemCertPool() *x509.CertPool {
pool, err := x509.SystemCertPool()
if err != nil {
return x509.NewCertPool()
}
return pool
}
// getCertPool - return system CAs or load CA from file if flag specified
func getCertPool(cacert string) *x509.CertPool {
if cacert == "" {
return mustGetSystemCertPool()
}
pool := x509.NewCertPool()
caPEM, err := os.ReadFile(cacert)
if err != nil {
console.Fatalln(fmt.Errorf("unable to load CA certificate: %s", err))
}
ok := pool.AppendCertsFromPEM(caPEM)
if !ok {
console.Fatalln(fmt.Errorf("unable to load CA certificate: %s is not valid certificate", cacert))
}
return pool
}
// getCertKeyPair - load client certificate and key pair from file if specified
func getCertKeyPair(cert, key string) []tls.Certificate {
if cert == "" && key == "" {
return nil
}
if cert == "" || key == "" {
console.Fatalln(fmt.Errorf("both --cert and --key flags must be specified"))
}
certPEM, err := os.ReadFile(cert)
if err != nil {
console.Fatalln(fmt.Errorf("unable to load certificate: %s", err))
}
keyPEM, err := os.ReadFile(key)
if err != nil {
console.Fatalln(fmt.Errorf("unable to load key: %s", err))
}
keyPair, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
console.Fatalln(fmt.Errorf("%s", err))
}
return []tls.Certificate{keyPair}
}
// dialContextWithDNSCache is a helper function which returns `net.DialContext` function.
// It randomly fetches an IP from the DNS cache and dials it by the given dial
// function. It dials one by one and returns first connected `net.Conn`.
// If it fails to dial all IPs from cache it returns first error. If no baseDialFunc
// is given, it sets default dial function.
//
// You can use returned dial function for `http.Transport.DialContext`.
func dialContextWithDNSCache(resolver *dnscache.Resolver, baseDialCtx DialContext) DialContext {
if baseDialCtx == nil {
// This is same as which `http.DefaultTransport` uses.
baseDialCtx = (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext
}
return func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
if net.ParseIP(host) != nil {
// For IP only setups there is no need for DNS lookups.
return baseDialCtx(ctx, network, addr)
}
ips, err := resolver.LookupHost(ctx, host)
if err != nil {
return nil, err
}
for _, ip := range ips {
conn, err = baseDialCtx(ctx, network, net.JoinHostPort(ip, port))
if err == nil {
break
}
}
return
}
}
// DialContext is a function to make custom Dial for internode communications
type DialContext func(ctx context.Context, network, address string) (net.Conn, error)
// newProxyDialContext setups a custom dialer for internode communication
func newProxyDialContext(dialTimeout time.Duration) DialContext {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: dialTimeout,
Control: setTCPParameters,
}
return dialer.DialContext(ctx, network, addr)
}
}
// tlsClientSessionCacheSize is the cache size for TLS client sessions.
const tlsClientSessionCacheSize = 100
func clientTransport(ctx *cli.Context, tlsMaxVersion uint16, enableTLS bool, hostName string) http.RoundTripper {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialContextWithDNSCache(dnsCache, newProxyDialContext(10*time.Second)),
MaxIdleConnsPerHost: 1024,
WriteBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
ReadBufferSize: 32 << 10, // 32KiB moving up from 4KiB default
IdleConnTimeout: 15 * time.Second,
TLSHandshakeTimeout: 15 * time.Second,
ExpectContinueTimeout: 15 * time.Second,
// Set this value so that the underlying transport round-tripper
// doesn't try to auto decode the body of objects with
// content-encoding set to `gzip`.
//
// Refer:
// https://golang.org/src/net/http/transport.go?h=roundTrip#L1843
DisableCompression: true,
}
if enableTLS {
// Keep TLS config.
tr.TLSClientConfig = &tls.Config{
RootCAs: getCertPool(ctx.GlobalString("cacert")),
Certificates: getCertKeyPair(ctx.GlobalString("client-cert"), ctx.GlobalString("client-key")),
InsecureSkipVerify: ctx.GlobalBool("insecure"),
MinVersion: tls.VersionTLS12,
MaxVersion: tlsMaxVersion,
PreferServerCipherSuites: true,
ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize),
ServerName: hostName,
}
}
return tr
}
func checkMain(ctx *cli.Context) {
if !ctx.Args().Present() {
cli.ShowAppHelpAndExit(ctx, 1)
}
}
func modifyResponse() func(*http.Response) error {
return func(resp *http.Response) error {
resp.Header.Set("X-Proxy", "true")
return nil
}
}
// sortIPs - sort ips based on higher octets.
// The logic to sort by last octet is implemented to
// prefer CIDRs with higher octets, this in-turn skips the
// localhost/loopback address to be not preferred as the
// first ip on the list. Subsequently this list helps us print
// a user friendly message with appropriate values.
func sortIPs(ipList []string) []string {
if len(ipList) == 1 {
return ipList
}
var IPs []net.IP
var nonIPs []string
for _, ip := range ipList {
nip := net.ParseIP(ip)
if nip != nil {
IPs = append(IPs, nip)
} else {
nonIPs = append(nonIPs, ip)
}
}
sort.Slice(IPs, func(i, j int) bool {
// This case is needed when all ips in the list
// have same last octets, Following just ensures that
// 127.0.0.1 is moved to the end of the list.
if IPs[i].IsLoopback() {
return false
}
if IPs[j].IsLoopback() {
return true
}
// Prefer IPv4 over IPv6
if IPs[i].To16() == nil && IPs[j].To16() != nil {
return true
}
if IPs[i].To16() != nil && IPs[j].To16() == nil {
return false
}
if IPs[i].To16() != nil {
return true // TODO: check if any IPv6 order can be preferred
}
// Sort IPs v4 based on higher octets.
return []byte(IPs[i].To4())[3] > []byte(IPs[j].To4())[3]
})
var ips []string
for _, ip := range IPs {
ips = append(ips, ip.String())
}
return append(nonIPs, ips...)
}
func getPublicIP() string {
var IPs []string
addrs, _ := net.InterfaceAddrs()
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok {
IPs = append(IPs, ipNet.IP.String())
}
}
if ips := sortIPs(IPs); len(ips) > 0 {
return ips[0]
}
return "<unknown-address>"
}
// IsLoopback - returns true if given IP is a loopback
func IsLoopback(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
if host == "localhost" || host == "127.0.0.1" || host == "::1" {
return true
}
return net.ParseIP(host).IsLoopback()
}
func configureSite(ctxt context.Context, ctx *cli.Context, siteNum int, siteStrs []string, tlsMaxVersion uint16, opts healthCheckOptions) *site {
var endpoints []string
if ellipses.HasEllipses(siteStrs...) {
argPatterns := make([]ellipses.ArgPattern, len(siteStrs))
for i, arg := range siteStrs {
patterns, err := ellipses.FindEllipsesPatterns(arg)
if err != nil {
console.Fatalln(fmt.Errorf("Unable to parse input arg %s: %s", arg, err))
}
argPatterns[i] = patterns
}
for _, argPattern := range argPatterns {
for _, lbls := range argPattern.Expand() {
endpoints = append(endpoints, strings.Join(lbls, ""))
}
}
} else {
endpoints = siteStrs
}
var backends []*Backend
var prevScheme string
var transport http.RoundTripper
var hostName string
if len(endpoints) == 1 && ctx.GlobalBool("rr-dns-mode") {
console.Infof("RR DNS mode enabled, using %s as hostname", endpoints[0])
// guess it is LB config address
target, err := url.Parse(endpoints[0])
if err != nil {
console.Fatalln(fmt.Errorf("Unable to parse input arg %s: %s", endpoints[0], err))
}
hostName = target.Hostname()
ips, err := net.LookupHost(hostName)
if err != nil {
console.Fatalln(fmt.Errorf("Unable to lookup host %s", hostName))
}
// set the new endpoints
endpoints = []string{}
for _, ip := range ips {
endpoints = append(endpoints, strings.Replace(target.String(), hostName, ip, 1))
}
}
var connStats []*ConnStats
for _, endpoint := range endpoints {
endpoint = strings.TrimSuffix(endpoint, slashSeparator)
connStats = append(connStats, newConnStats(endpoint))
}
globalConnStats.Store(&connStats)
healthOptimistic := ctx.GlobalBool("health-optimistic")
for _, endpoint := range endpoints {
endpoint = strings.TrimSuffix(endpoint, slashSeparator)
target, err := url.Parse(endpoint)
if err != nil {
console.Fatalln(fmt.Errorf("Unable to parse input arg %s: %s", endpoint, err))
}
if target.Scheme == "" {
target.Scheme = "http"
}
if target.Scheme != "http" && target.Scheme != "https" {
console.Fatalln("Unexpected scheme %s, should be http or https, please use '%s --help'",
endpoint, ctx.App.Name)
}
if target.Host == "" {
console.Fatalln(fmt.Errorf("Missing host address %s, please use '%s --help'",
endpoint, ctx.App.Name))
}
if prevScheme == "" {
prevScheme = target.Scheme
}
if prevScheme != target.Scheme {
console.Fatalln(fmt.Errorf("Unexpected scheme %s, please use 'http' or 'http's for all backend endpoints '%s --help'",
endpoint, ctx.App.Name))
}
if transport == nil {
transport = clientTransport(ctx, tlsMaxVersion, target.Scheme == "https", hostName)
}
// this is only used if r.RemoteAddr is localhost which means that
// sidekick endpoint being accessed is 127.0.0.x
realIP := getPublicIP()
proxy := &reverse.Proxy{
Director: func(r *http.Request) {
r.Header.Add("X-Forwarded-Host", r.Host)
host := realIP
if !IsLoopback(r.RemoteAddr) {
host, _, _ = net.SplitHostPort(r.RemoteAddr)
}
r.Header.Add("X-Real-IP", host)
r.Header.Add("X-Forwarded-For", host)
r.URL.Scheme = target.Scheme
r.URL.Host = target.Host
},
Transport: transport,
ModifyResponse: modifyResponse(),