-
Notifications
You must be signed in to change notification settings - Fork 352
/
Copy pathproxy.go
1490 lines (1266 loc) · 42.1 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
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
package proxy
import (
stdlibcontext "context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptrace"
"net/http/httputil"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"time"
ot "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/zalando/skipper/circuit"
"github.com/zalando/skipper/eskip"
"github.com/zalando/skipper/filters"
al "github.com/zalando/skipper/filters/accesslog"
circuitfilters "github.com/zalando/skipper/filters/circuit"
flowidFilter "github.com/zalando/skipper/filters/flowid"
tracingfilter "github.com/zalando/skipper/filters/tracing"
"github.com/zalando/skipper/loadbalancer"
"github.com/zalando/skipper/logging"
"github.com/zalando/skipper/metrics"
"github.com/zalando/skipper/proxy/fastcgi"
"github.com/zalando/skipper/ratelimit"
"github.com/zalando/skipper/rfc"
"github.com/zalando/skipper/routing"
"github.com/zalando/skipper/scheduler"
"github.com/zalando/skipper/tracing"
)
const (
proxyBufferSize = 8192
unknownRouteID = "_unknownroute_"
unknownRouteBackendType = "<unknown>"
unknownRouteBackend = "<unknown>"
backendIsProxyHeader = "X-Skipper-Proxy"
// Number of loops allowed by default.
DefaultMaxLoopbacks = 9
// The default value set for http.Transport.MaxIdleConnsPerHost.
DefaultIdleConnsPerHost = 64
// The default period at which the idle connections are forcibly
// closed.
DefaultCloseIdleConnsPeriod = 20 * time.Second
// DefaultResponseHeaderTimeout, the default response header timeout
DefaultResponseHeaderTimeout = 60 * time.Second
// DefaultExpectContinueTimeout, the default timeout to expect
// a response for a 100 Continue request
DefaultExpectContinueTimeout = 30 * time.Second
)
// Flags control the behavior of the proxy.
type Flags uint
const (
FlagsNone Flags = 0
// Insecure causes the proxy to ignore the verification of
// the TLS certificates of the backend services.
Insecure Flags = 1 << iota
// PreserveOriginal indicates that filters require the
// preserved original metadata of the request and the response.
PreserveOriginal
// PreserveHost indicates whether the outgoing request to the
// backend should use by default the 'Host' header of the incoming
// request, or the host part of the backend address, in case filters
// don't change it.
PreserveHost
// Debug indicates that the current proxy instance will be used as a
// debug proxy. Debug proxies don't forward the request to the
// route backends, but they execute all filters, and return a
// JSON document with the changes the filters make to the request
// and with the approximate changes they would make to the
// response.
Debug
// HopHeadersRemoval indicates whether the Hop Headers should be removed
// in compliance with RFC 2616
HopHeadersRemoval
// PatchPath instructs the proxy to patch the parsed request path
// if the reserved characters according to RFC 2616 and RFC 3986
// were unescaped by the parser.
PatchPath
)
// Options are deprecated alias for Flags.
type Options Flags
const (
OptionsNone = Options(FlagsNone)
OptionsInsecure = Options(Insecure)
OptionsPreserveOriginal = Options(PreserveOriginal)
OptionsPreserveHost = Options(PreserveHost)
OptionsDebug = Options(Debug)
OptionsHopHeadersRemoval = Options(HopHeadersRemoval)
)
type OpenTracingParams struct {
// Tracer holds the tracer enabled for this proxy instance
Tracer ot.Tracer
// InitialSpan can override the default initial, pre-routing, span name.
// Default: "ingress".
InitialSpan string
// LogFilterEvents enables the behavior to mark start and completion times of filters
// on the span representing request filters being processed.
// Default: false
LogFilterEvents bool
// LogStreamEvents enables the logs that marks the times when response headers & payload are streamed to
// the client
// Default: false
LogStreamEvents bool
// ExcludeTags controls what tags are disabled. Any tag that is listed here will be ignored.
ExcludeTags []string
}
// Proxy initialization options.
type Params struct {
// The proxy expects a routing instance that is used to match
// the incoming requests to routes.
Routing *routing.Routing
// Control flags. See the Flags values.
Flags Flags
// And optional list of priority routes to be used for matching
// before the general lookup tree.
PriorityRoutes []PriorityRoute
// Enable the experimental upgrade protocol feature
ExperimentalUpgrade bool
// ExperimentalUpgradeAudit enables audit log of both the request line
// and the response messages during web socket upgrades.
ExperimentalUpgradeAudit bool
// When set, no access log is printed.
AccessLogDisabled bool
// DualStack sets if the proxy TCP connections to the backend should be dual stack
DualStack bool
// DefaultHTTPStatus is the HTTP status used when no routes are found
// for a request.
DefaultHTTPStatus int
// MaxLoopbacks sets the maximum number of allowed loops. If 0
// the default (9) is applied. To disable looping, set it to
// -1. Note, that disabling looping by this option, may result
// wrong routing depending on the current configuration.
MaxLoopbacks int
// Same as net/http.Transport.MaxIdleConnsPerHost, but the default
// is 64. This value supports scenarios with relatively few remote
// hosts. When the routing table contains different hosts in the
// range of hundreds, it is recommended to set this options to a
// lower value.
IdleConnectionsPerHost int
// MaxIdleConns limits the number of idle connections to all backends, 0 means no limit
MaxIdleConns int
// DisableHTTPKeepalives forces backend to always create a new connection
DisableHTTPKeepalives bool
// CircuitBreakers provides a registry that skipper can use to
// find the matching circuit breaker for backend requests. If not
// set, no circuit breakers are used.
CircuitBreakers *circuit.Registry
// RateLimiters provides a registry that skipper can use to
// find the matching ratelimiter for backend requests. If not
// set, no ratelimits are used.
RateLimiters *ratelimit.Registry
// LoadBalancer to report unhealthy or dead backends to
LoadBalancer *loadbalancer.LB
// Defines the time period of how often the idle connections are
// forcibly closed. The default is 12 seconds. When set to less than
// 0, the proxy doesn't force closing the idle connections.
CloseIdleConnsPeriod time.Duration
// The Flush interval for copying upgraded connections
FlushInterval time.Duration
// Timeout sets the TCP client connection timeout for proxy http connections to the backend
Timeout time.Duration
// ResponseHeaderTimeout sets the HTTP response timeout for
// proxy http connections to the backend.
ResponseHeaderTimeout time.Duration
// ExpectContinueTimeout sets the HTTP timeout to expect a
// response for status Code 100 for proxy http connections to
// the backend.
ExpectContinueTimeout time.Duration
// KeepAlive sets the TCP keepalive for proxy http connections to the backend
KeepAlive time.Duration
// TLSHandshakeTimeout sets the TLS handshake timeout for proxy connections to the backend
TLSHandshakeTimeout time.Duration
// Client TLS to connect to Backends
ClientTLS *tls.Config
// OpenTracing contains parameters related to OpenTracing instrumentation. For default values
// check OpenTracingParams
OpenTracing *OpenTracingParams
// CustomHttpRoundTripperWrap provides ability to wrap http.RoundTripper created by skipper.
// http.RoundTripper is used for making outgoing requests (backends)
// It allows to add additional logic (for example tracing) by providing a wrapper function
// which accepts original skipper http.RoundTripper as an argument and returns a wrapped roundtripper
CustomHttpRoundTripperWrap func(http.RoundTripper) http.RoundTripper
}
type (
maxLoopbackError string
ratelimitError string
routeLookupError string
)
func (e maxLoopbackError) Error() string { return string(e) }
func (e ratelimitError) Error() string { return string(e) }
func (e routeLookupError) Error() string { return string(e) }
const (
errMaxLoopbacksReached = maxLoopbackError("max loopbacks reached")
errRatelimit = ratelimitError("ratelimited")
errRouteLookup = routeLookupError("route lookup failed")
)
var (
errRouteLookupFailed = &proxyError{err: errRouteLookup}
errCircuitBreakerOpen = &proxyError{
err: errors.New("circuit breaker open"),
code: http.StatusServiceUnavailable,
additionalHeader: http.Header{"X-Circuit-Open": []string{"true"}},
}
disabledAccessLog = al.AccessLogFilter{Enable: false, Prefixes: nil}
enabledAccessLog = al.AccessLogFilter{Enable: true, Prefixes: nil}
hopHeaders = map[string]bool{
"Te": true,
"Connection": true,
"Proxy-Connection": true,
"Keep-Alive": true,
"Proxy-Authenticate": true,
"Proxy-Authorization": true,
"Trailer": true,
"Transfer-Encoding": true,
"Upgrade": true,
}
)
// When set, the proxy will skip the TLS verification on outgoing requests.
func (f Flags) Insecure() bool { return f&Insecure != 0 }
// When set, the filters will receive an unmodified clone of the original
// incoming request and response.
func (f Flags) PreserveOriginal() bool { return f&(PreserveOriginal|Debug) != 0 }
// When set, the proxy will set the, by default, the Host header value
// of the outgoing requests to the one of the incoming request.
func (f Flags) PreserveHost() bool { return f&PreserveHost != 0 }
// When set, the proxy runs in debug mode.
func (f Flags) Debug() bool { return f&Debug != 0 }
// When set, the proxy will remove the Hop Headers
func (f Flags) HopHeadersRemoval() bool { return f&HopHeadersRemoval != 0 }
func (f Flags) patchPath() bool { return f&PatchPath != 0 }
// Priority routes are custom route implementations that are matched against
// each request before the routes in the general lookup tree.
type PriorityRoute interface {
// If the request is matched, returns a route, otherwise nil.
// Additionally it may return a parameter map used by the filters
// in the route.
Match(*http.Request) (*routing.Route, map[string]string)
}
// Proxy instances implement Skipper proxying functionality. For
// initializing, see the WithParams the constructor and Params.
type Proxy struct {
experimentalUpgrade bool
experimentalUpgradeAudit bool
accessLogDisabled bool
maxLoops int
defaultHTTPStatus int
routing *routing.Routing
roundTripper http.RoundTripper
priorityRoutes []PriorityRoute
flags Flags
metrics metrics.Metrics
quit chan struct{}
flushInterval time.Duration
breakers *circuit.Registry
limiters *ratelimit.Registry
log logging.Logger
tracing *proxyTracing
lb *loadbalancer.LB
upgradeAuditLogOut io.Writer
upgradeAuditLogErr io.Writer
auditLogHook chan struct{}
clientTLS *tls.Config
hostname string
}
// proxyError is used to wrap errors during proxying and to indicate
// the required status code for the response sent from the main
// ServeHTTP method. Alternatively, it can indicate that the request
// was already handled, e.g. in case of deprecated shunting or the
// upgrade request.
type proxyError struct {
err error
code int
handled bool
dialingFailed bool
additionalHeader http.Header
}
func (e proxyError) Error() string {
if e.err != nil {
return fmt.Sprintf("dialing failed %v: %v", e.DialError(), e.err.Error())
}
if e.handled {
return "request handled in a non-standard way"
}
code := e.code
if code == 0 {
code = http.StatusInternalServerError
}
return fmt.Sprintf("proxy error: %d", code)
}
// DialError returns true if the error was caused while dialing TCP or
// TLS connections, before HTTP data was sent. It is safe to retry
// a call, if this returns true.
func (e *proxyError) DialError() bool {
return e.dialingFailed
}
func (e *proxyError) NetError() net.Error {
if perr, ok := e.err.(net.Error); ok {
return perr
}
return nil
}
func copyHeader(to, from http.Header) {
for k, v := range from {
to[http.CanonicalHeaderKey(k)] = v
}
}
func copyHeaderExcluding(to, from http.Header, excludeHeaders map[string]bool) {
for k, v := range from {
// The http package converts header names to their canonical version.
// Meaning that the lookup below will be done using the canonical version of the header.
if _, ok := excludeHeaders[k]; !ok {
to[http.CanonicalHeaderKey(k)] = v
}
}
}
func cloneHeader(h http.Header) http.Header {
hh := make(http.Header)
copyHeader(hh, h)
return hh
}
func cloneHeaderExcluding(h http.Header, excludeList map[string]bool) http.Header {
hh := make(http.Header)
copyHeaderExcluding(hh, h, excludeList)
return hh
}
type flusher struct {
w flushedResponseWriter
}
func (f *flusher) Write(p []byte) (n int, err error) {
n, err = f.w.Write(p)
if err == nil {
f.w.Flush()
}
return
}
func copyStream(to flushedResponseWriter, from io.Reader) (int64, error) {
b := make([]byte, proxyBufferSize)
return io.CopyBuffer(&flusher{to}, from, b)
}
func schemeFromRequest(r *http.Request) string {
if r.TLS != nil {
return "https"
}
return "http"
}
func setRequestURLFromRequest(u *url.URL, r *http.Request) {
if u.Host == "" {
u.Host = r.Host
}
if u.Scheme == "" {
u.Scheme = schemeFromRequest(r)
}
}
func setRequestURLForDynamicBackend(u *url.URL, stateBag map[string]interface{}) {
dbu, ok := stateBag[filters.DynamicBackendURLKey].(string)
if ok && dbu != "" {
bu, err := url.ParseRequestURI(dbu)
if err == nil {
u.Host = bu.Host
u.Scheme = bu.Scheme
}
} else {
host, ok := stateBag[filters.DynamicBackendHostKey].(string)
if ok && host != "" {
u.Host = host
}
scheme, ok := stateBag[filters.DynamicBackendSchemeKey].(string)
if ok && scheme != "" {
u.Scheme = scheme
}
}
}
func setRequestURLForLoadBalancedBackend(u *url.URL, rt *routing.Route, lbctx *routing.LBContext) *routing.LBEndpoint {
e := rt.LBAlgorithm.Apply(lbctx)
u.Scheme = e.Scheme
u.Host = e.Host
return &e
}
// creates an outgoing http request to be forwarded to the route endpoint
// based on the augmented incoming request
func mapRequest(r *http.Request, rt *routing.Route, host string, removeHopHeaders bool, stateBag map[string]interface{}) (*http.Request, *routing.LBEndpoint, error) {
var endpoint *routing.LBEndpoint
u := r.URL
switch rt.BackendType {
case eskip.DynamicBackend:
setRequestURLFromRequest(u, r)
setRequestURLForDynamicBackend(u, stateBag)
case eskip.LBBackend:
endpoint = setRequestURLForLoadBalancedBackend(u, rt, routing.NewLBContext(r, rt))
default:
u.Scheme = rt.Scheme
u.Host = rt.Host
}
body := r.Body
if r.ContentLength == 0 {
body = nil
}
rr, err := http.NewRequest(r.Method, u.String(), body)
if err != nil {
return nil, endpoint, err
}
rr = rr.WithContext(r.Context())
rr.ContentLength = r.ContentLength
if removeHopHeaders {
rr.Header = cloneHeaderExcluding(r.Header, hopHeaders)
} else {
rr.Header = cloneHeader(r.Header)
}
rr.Host = host
// If there is basic auth configured in the URL we add them as headers
if u.User != nil {
up := u.User.String()
upBase64 := base64.StdEncoding.EncodeToString([]byte(up))
rr.Header.Add("Authorization", fmt.Sprintf("Basic %s", upBase64))
}
if _, ok := stateBag[filters.BackendIsProxyKey]; ok {
forwardToProxy(r, rr)
}
ctxspan := ot.SpanFromContext(r.Context())
if ctxspan != nil {
rr = rr.WithContext(ot.ContextWithSpan(rr.Context(), ctxspan))
}
return rr, endpoint, nil
}
func forwardToProxy(incoming, outgoing *http.Request) {
proxyURL := &url.URL{
Scheme: outgoing.URL.Scheme,
Host: outgoing.URL.Host,
}
outgoing.URL.Host = incoming.Host
outgoing.URL.Scheme = schemeFromRequest(incoming)
outgoing.Header.Set(backendIsProxyHeader, proxyURL.String())
}
type skipperDialer struct {
net.Dialer
f func(ctx stdlibcontext.Context, network, addr string) (net.Conn, error)
}
func newSkipperDialer(d net.Dialer) *skipperDialer {
return &skipperDialer{
Dialer: d,
f: d.DialContext,
}
}
// DialContext wraps net.Dialer's DialContext and returns an error,
// that can be checked if it was a Transport (TCP/TLS handshake) error
// or timeout, or a timeout from http, which is not in general
// not possible to retry.
func (dc *skipperDialer) DialContext(ctx stdlibcontext.Context, network, addr string) (net.Conn, error) {
span := ot.SpanFromContext(ctx)
if span != nil {
span.LogKV("dial_context", "start")
}
con, err := dc.f(ctx, network, addr)
if span != nil {
span.LogKV("dial_context", "done")
}
if err != nil {
return nil, &proxyError{
err: err,
code: -1, // omit 0 handling in proxy.Error()
dialingFailed: true, // indicate error happened before http
}
} else if cerr := ctx.Err(); cerr != nil {
// unclear when this is being triggered
return nil, &proxyError{
err: fmt.Errorf("err from dial context: %v", cerr),
code: http.StatusGatewayTimeout,
}
}
return con, nil
}
// New returns an initialized Proxy.
// Deprecated, see WithParams and Params instead.
func New(r *routing.Routing, options Options, pr ...PriorityRoute) *Proxy {
return WithParams(Params{
Routing: r,
Flags: Flags(options),
PriorityRoutes: pr,
CloseIdleConnsPeriod: -time.Second,
})
}
// WithParams returns an initialized Proxy.
func WithParams(p Params) *Proxy {
if p.IdleConnectionsPerHost <= 0 {
p.IdleConnectionsPerHost = DefaultIdleConnsPerHost
}
if p.CloseIdleConnsPeriod == 0 {
p.CloseIdleConnsPeriod = DefaultCloseIdleConnsPeriod
}
if p.ResponseHeaderTimeout == 0 {
p.ResponseHeaderTimeout = DefaultResponseHeaderTimeout
}
if p.ExpectContinueTimeout == 0 {
p.ExpectContinueTimeout = DefaultExpectContinueTimeout
}
if p.CustomHttpRoundTripperWrap == nil {
// default wrapper which does nothing
p.CustomHttpRoundTripperWrap = func(original http.RoundTripper) http.RoundTripper {
return original
}
}
tr := &http.Transport{
DialContext: newSkipperDialer(net.Dialer{
Timeout: p.Timeout,
KeepAlive: p.KeepAlive,
DualStack: p.DualStack,
}).DialContext,
TLSHandshakeTimeout: p.TLSHandshakeTimeout,
ResponseHeaderTimeout: p.ResponseHeaderTimeout,
ExpectContinueTimeout: p.ExpectContinueTimeout,
MaxIdleConns: p.MaxIdleConns,
MaxIdleConnsPerHost: p.IdleConnectionsPerHost,
IdleConnTimeout: p.CloseIdleConnsPeriod,
DisableKeepAlives: p.DisableHTTPKeepalives,
Proxy: proxyFromHeader,
}
quit := make(chan struct{})
// We need this to reliably fade on DNS change, which is right
// now not fixed with IdleConnTimeout in the http.Transport.
// https://github.com/golang/go/issues/23427
if p.CloseIdleConnsPeriod > 0 {
go func() {
for {
select {
case <-time.After(p.CloseIdleConnsPeriod):
tr.CloseIdleConnections()
case <-quit:
return
}
}
}()
}
if p.ClientTLS != nil {
tr.TLSClientConfig = p.ClientTLS
}
if p.Flags.Insecure() {
if tr.TLSClientConfig == nil {
/* #nosec */
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
} else {
/* #nosec */
tr.TLSClientConfig.InsecureSkipVerify = true
}
}
m := metrics.Default
if p.Flags.Debug() {
m = metrics.Void
}
if p.MaxLoopbacks == 0 {
p.MaxLoopbacks = DefaultMaxLoopbacks
} else if p.MaxLoopbacks < 0 {
p.MaxLoopbacks = 0
}
defaultHTTPStatus := http.StatusNotFound
if p.DefaultHTTPStatus >= http.StatusContinue && p.DefaultHTTPStatus <= http.StatusNetworkAuthenticationRequired {
defaultHTTPStatus = p.DefaultHTTPStatus
}
hostname := os.Getenv("HOSTNAME")
return &Proxy{
routing: p.Routing,
roundTripper: p.CustomHttpRoundTripperWrap(tr),
priorityRoutes: p.PriorityRoutes,
flags: p.Flags,
metrics: m,
quit: quit,
flushInterval: p.FlushInterval,
experimentalUpgrade: p.ExperimentalUpgrade,
experimentalUpgradeAudit: p.ExperimentalUpgradeAudit,
maxLoops: p.MaxLoopbacks,
breakers: p.CircuitBreakers,
lb: p.LoadBalancer,
limiters: p.RateLimiters,
log: &logging.DefaultLog{},
defaultHTTPStatus: defaultHTTPStatus,
tracing: newProxyTracing(p.OpenTracing),
accessLogDisabled: p.AccessLogDisabled,
upgradeAuditLogOut: os.Stdout,
upgradeAuditLogErr: os.Stderr,
clientTLS: tr.TLSClientConfig,
hostname: hostname,
}
}
var caughtPanic = false
// tryCatch executes function `p` and `onErr` if `p` panics
// onErr will receive a stack trace string of the first panic
// further panics are ignored for efficiency reasons
func tryCatch(p func(), onErr func(err interface{}, stack string)) {
defer func() {
if err := recover(); err != nil {
s := ""
if !caughtPanic {
buf := make([]byte, 1024)
l := runtime.Stack(buf, false)
s = string(buf[:l])
caughtPanic = true
}
onErr(err, s)
}
}()
p()
}
func proxyFromHeader(req *http.Request) (*url.URL, error) {
if u := req.Header.Get(backendIsProxyHeader); u != "" {
req.Header.Del(backendIsProxyHeader)
return url.Parse(u)
}
return nil, nil
}
// applies filters to a request
func (p *Proxy) applyFiltersToRequest(f []*routing.RouteFilter, ctx *context) []*routing.RouteFilter {
if len(f) == 0 {
return f
}
filtersStart := time.Now()
filtersSpan := tracing.CreateSpan("request_filters", ctx.request.Context(), p.tracing.tracer)
defer filtersSpan.Finish()
ctx.parentSpan = filtersSpan
var filters = make([]*routing.RouteFilter, 0, len(f))
for _, fi := range f {
start := time.Now()
p.tracing.logFilterStart(filtersSpan, fi.Name)
tryCatch(func() {
ctx.setMetricsPrefix(fi.Name)
fi.Request(ctx)
p.metrics.MeasureFilterRequest(fi.Name, start)
}, func(err interface{}, stack string) {
if p.flags.Debug() {
// these errors are collected for the debug mode to be able
// to report in the response which filters failed.
ctx.debugFilterPanics = append(ctx.debugFilterPanics, err)
return
}
p.log.Errorf("error while processing filter during request: %s: %v (%s)", fi.Name, err, stack)
})
p.tracing.logFilterEnd(filtersSpan, fi.Name)
filters = append(filters, fi)
if ctx.deprecatedShunted() || ctx.shunted() {
break
}
}
p.metrics.MeasureAllFiltersRequest(ctx.route.Id, filtersStart)
return filters
}
// applies filters to a response in reverse order
func (p *Proxy) applyFiltersToResponse(filters []*routing.RouteFilter, ctx *context) {
filtersStart := time.Now()
filtersSpan := tracing.CreateSpan("response_filters", ctx.request.Context(), p.tracing.tracer)
defer filtersSpan.Finish()
ctx.parentSpan = filtersSpan
last := len(filters) - 1
for i := range filters {
fi := filters[last-i]
start := time.Now()
p.tracing.logFilterStart(filtersSpan, fi.Name)
tryCatch(func() {
ctx.setMetricsPrefix(fi.Name)
fi.Response(ctx)
p.metrics.MeasureFilterResponse(fi.Name, start)
}, func(err interface{}, stack string) {
if p.flags.Debug() {
// these errors are collected for the debug mode to be able
// to report in the response which filters failed.
ctx.debugFilterPanics = append(ctx.debugFilterPanics, err)
return
}
p.log.Errorf("error while processing filters during response: %s: %v (%s)", fi.Name, err, stack)
})
p.tracing.logFilterEnd(filtersSpan, fi.Name)
}
p.metrics.MeasureAllFiltersResponse(ctx.route.Id, filtersStart)
}
// addBranding overwrites any existing `X-Powered-By` or `Server` header from headerMap
func addBranding(headerMap http.Header) {
if headerMap.Get("Server") == "" {
headerMap.Set("Server", "Skipper")
}
}
func (p *Proxy) lookupRoute(ctx *context) (rt *routing.Route, params map[string]string) {
for _, prt := range p.priorityRoutes {
rt, params = prt.Match(ctx.request)
if rt != nil {
return rt, params
}
}
return ctx.routeLookup.Do(ctx.request)
}
// send a premature error response
func (p *Proxy) sendError(c *context, id string, code int) {
addBranding(c.responseWriter.Header())
text := http.StatusText(code) + "\n"
c.responseWriter.Header().Set("Content-Length", strconv.Itoa(len(text)))
c.responseWriter.Header().Set("Content-Type", "text/plain; charset=utf-8")
c.responseWriter.Header().Set("X-Content-Type-Options", "nosniff")
c.responseWriter.WriteHeader(code)
c.responseWriter.Write([]byte(text))
p.metrics.MeasureServe(
id,
c.metricsHost(),
c.request.Method,
code,
c.startServe,
)
}
func (p *Proxy) makeUpgradeRequest(ctx *context, req *http.Request) error {
backendURL := req.URL
reverseProxy := httputil.NewSingleHostReverseProxy(backendURL)
reverseProxy.FlushInterval = p.flushInterval
upgradeProxy := upgradeProxy{
backendAddr: backendURL,
reverseProxy: reverseProxy,
insecure: p.flags.Insecure(),
tlsClientConfig: p.clientTLS,
useAuditLog: p.experimentalUpgradeAudit,
auditLogOut: p.upgradeAuditLogOut,
auditLogErr: p.upgradeAuditLogErr,
auditLogHook: p.auditLogHook,
}
upgradeProxy.serveHTTP(ctx.responseWriter, req)
ctx.successfulUpgrade = true
p.log.Debugf("finished upgraded protocol %s session", getUpgradeRequest(ctx.request))
return nil
}
func (p *Proxy) makeBackendRequest(ctx *context) (*http.Response, *proxyError) {
req, endpoint, err := mapRequest(ctx.request, ctx.route, ctx.outgoingHost, p.flags.HopHeadersRemoval(), ctx.StateBag())
if err != nil {
p.log.Errorf("could not map backend request, caused by: %v", err)
return nil, &proxyError{err: err}
}
if endpoint != nil {
endpoint.Metrics.IncInflightRequest()
defer endpoint.Metrics.DecInflightRequest()
}
if p.experimentalUpgrade && isUpgradeRequest(req) {
if err = p.makeUpgradeRequest(ctx, req); err != nil {
return nil, &proxyError{err: err}
}
// We are not owner of the connection anymore.
return nil, &proxyError{handled: true}
}
roundTripper, err := p.getRoundTripper(ctx, req)
if err != nil {
p.log.Errorf("Failed to get roundtripper: %v", err)
return nil, &proxyError{err: err, code: http.StatusBadGateway}
}
bag := ctx.StateBag()
spanName, ok := bag[tracingfilter.OpenTracingProxySpanKey].(string)
if !ok {
spanName = "proxy"
}
ctx.proxySpan = tracing.CreateSpan(spanName, req.Context(), p.tracing.tracer)
p.tracing.
setTag(ctx.proxySpan, SpanKindTag, SpanKindClient).
setTag(ctx.proxySpan, SkipperRouteIDTag, ctx.route.Id).
setTag(ctx.proxySpan, SkipperRouteTag, ctx.route.String())
u := cloneURL(req.URL)
u.RawQuery = ""
p.setCommonSpanInfo(u, req, ctx.proxySpan)
carrier := ot.HTTPHeadersCarrier(req.Header)
_ = p.tracing.tracer.Inject(ctx.proxySpan.Context(), ot.HTTPHeaders, carrier)
req = req.WithContext(ot.ContextWithSpan(req.Context(), ctx.proxySpan))
p.metrics.IncCounter("outgoing." + req.Proto)
ctx.proxySpan.LogKV("http_roundtrip", StartEvent)
req = injectClientTrace(req, ctx.proxySpan)
response, err := roundTripper.RoundTrip(req)
ctx.proxySpan.LogKV("http_roundtrip", EndEvent)
if err != nil {
p.tracing.setTag(ctx.proxySpan, ErrorTag, true)
// Check if the request has been cancelled or timed out
// The roundtrip error `err` may be different
if cerr := req.Context().Err(); cerr != nil {
ctx.proxySpan.LogKV("event", "error", "message", cerr.Error())
return nil, &proxyError{err: cerr, code: 499}
}
ctx.proxySpan.LogKV("event", "error", "message", err.Error())
if perr, ok := err.(*proxyError); ok {
p.log.Errorf("Failed to do backend roundtrip to %s: %v", ctx.route.Backend, perr)
//p.lb.AddHealthcheck(ctx.route.Backend)
return nil, perr
} else if nerr, ok := err.(net.Error); ok {
p.log.Errorf("net.Error during backend roundtrip to %s: timeout=%v temporary=%v: %v", ctx.route.Backend, nerr.Timeout(), nerr.Temporary(), err)
//p.lb.AddHealthcheck(ctx.route.Backend)
var status int
if nerr.Timeout() {
status = http.StatusGatewayTimeout
} else {
status = http.StatusServiceUnavailable
}
p.tracing.setTag(ctx.proxySpan, HTTPStatusCodeTag, uint16(status))
return nil, &proxyError{err: err, code: status}
}
p.log.Errorf("Unexpected error from Go stdlib net/http package during roundtrip: %v", err)
return nil, &proxyError{err: err}
}
p.tracing.setTag(ctx.proxySpan, HTTPStatusCodeTag, uint16(response.StatusCode))
return response, nil
}
func (p *Proxy) getRoundTripper(ctx *context, req *http.Request) (http.RoundTripper, error) {
switch req.URL.Scheme {
case "fastcgi":
f := "index.php"
if sf, ok := ctx.StateBag()["fastCgiFilename"]; ok {
f = sf.(string)
}
rt, err := fastcgi.NewRoundTripper(p.log, req.URL.Host, f)
if err != nil {
return nil, err
}
// FastCgi expects the Host to be in form host:port
// It will then be split and added as 2 separate params to the backend process
if _, _, err := net.SplitHostPort(req.Host); err != nil {
req.Host = req.Host + ":" + req.URL.Port()
}
// RemoteAddr is needed to pass to the backend process as param
req.RemoteAddr = ctx.request.RemoteAddr
return rt, nil
default:
return p.roundTripper, nil
}
}
func (p *Proxy) checkBreaker(c *context) (func(bool), bool) {
if p.breakers == nil {
return nil, true
}
settings, _ := c.stateBag[circuitfilters.RouteSettingsKey].(circuit.BreakerSettings)
settings.Host = c.outgoingHost
b := p.breakers.Get(settings)
if b == nil {
return nil, true
}
done, ok := b.Allow()