/
httpclient.go
398 lines (355 loc) · 11.6 KB
/
httpclient.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
package net
import (
"crypto/tls"
"io"
"net/http"
"net/http/httptrace"
"net/url"
"strings"
"time"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/zalando/skipper/logging"
"github.com/zalando/skipper/secrets"
)
const (
defaultIdleConnTimeout = 30 * time.Second
defaultRefreshInterval = 5 * time.Minute
)
// Client adds additional features like Bearer token injection, and
// opentracing to the wrapped http.Client with the same interface as
// http.Client from the stdlib.
type Client struct {
client http.Client
tr *Transport
log logging.Logger
sr secrets.SecretsReader
}
// NewClient creates a wrapped http.Client and uses Transport to
// support OpenTracing. On teardown you have to use Close() to
// not leak a goroutine.
//
// If secrets.SecretsReader is nil, but BearerTokenFile is not empty
// string, it creates StaticDelegateSecret with a wrapped
// secrets.SecretPaths, which can be used with Kubernetes secrets to
// read from the secret an automatically updated Bearer token.
func NewClient(o Options) *Client {
if o.Log == nil {
o.Log = &logging.DefaultLog{}
}
tr := NewTransport(o)
sr := o.SecretsReader
if sr == nil && o.BearerTokenFile != "" {
if o.BearerTokenRefreshInterval == 0 {
o.BearerTokenRefreshInterval = defaultRefreshInterval
}
sp := secrets.NewSecretPaths(o.BearerTokenRefreshInterval)
if err := sp.Add(o.BearerTokenFile); err != nil {
o.Log.Errorf("failed to read secret: %v", err)
}
sr = secrets.NewStaticDelegateSecret(sp, o.BearerTokenFile)
}
c := &Client{
client: http.Client{
Transport: tr,
},
tr: tr,
log: o.Log,
sr: sr,
}
return c
}
func (c *Client) Close() {
c.tr.Close()
if c.sr != nil {
c.sr.Close()
}
}
func (c *Client) Head(url string) (*http.Response, error) {
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *Client) Get(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *Client) Post(url, contentType string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
return c.Do(req)
}
func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
// Do delegates the given http.Request to the underlying http.Client
// and adds a Bearer token to the authorization header, if Client has
// a secrets.SecretsReader and the request does not contain an
// Authorization header.
func (c *Client) Do(req *http.Request) (*http.Response, error) {
if c.sr != nil && req.Header.Get("Authorization") == "" {
if b, ok := c.sr.GetSecret(req.URL.String()); ok {
req.Header.Set("Authorization", "Bearer "+string(b))
}
}
return c.client.Do(req)
}
// CloseIdleConnections delegates the call to the underlying
// http.Client.
func (c *Client) CloseIdleConnections() {
c.client.CloseIdleConnections()
}
// Options are mostly passed to the http.Transport of the same
// name. Options.Timeout can be used as default for all timeouts, that
// are not set. You can pass an opentracing.Tracer
// https://godoc.org/github.com/opentracing/opentracing-go#Tracer,
// which can be nil to get the
// https://godoc.org/github.com/opentracing/opentracing-go#NoopTracer.
type Options struct {
// DisableKeepAlives see https://golang.org/pkg/net/http/#Transport.DisableKeepAlives
DisableKeepAlives bool
// DisableCompression see https://golang.org/pkg/net/http/#Transport.DisableCompression
DisableCompression bool
// ForceAttemptHTTP2 see https://golang.org/pkg/net/http/#Transport.ForceAttemptHTTP2
ForceAttemptHTTP2 bool
// MaxIdleConns see https://golang.org/pkg/net/http/#Transport.MaxIdleConns
MaxIdleConns int
// MaxIdleConnsPerHost see https://golang.org/pkg/net/http/#Transport.MaxIdleConnsPerHost
MaxIdleConnsPerHost int
// MaxConnsPerHost see https://golang.org/pkg/net/http/#Transport.MaxConnsPerHost
MaxConnsPerHost int
// WriteBufferSize see https://golang.org/pkg/net/http/#Transport.WriteBufferSize
WriteBufferSize int
// ReadBufferSize see https://golang.org/pkg/net/http/#Transport.ReadBufferSize
ReadBufferSize int
// MaxResponseHeaderBytes see
// https://golang.org/pkg/net/http/#Transport.MaxResponseHeaderBytes
MaxResponseHeaderBytes int64
// Timeout sets all Timeouts, that are set to 0 to the given
// value. Basically it's the default timeout value.
Timeout time.Duration
// TLSHandshakeTimeout see
// https://golang.org/pkg/net/http/#Transport.TLSHandshakeTimeout,
// if not set or set to 0, its using Options.Timeout.
TLSHandshakeTimeout time.Duration
// IdleConnTimeout see
// https://golang.org/pkg/net/http/#Transport.IdleConnTimeout,
// if not set or set to 0, its using Options.Timeout.
IdleConnTimeout time.Duration
// ResponseHeaderTimeout see
// https://golang.org/pkg/net/http/#Transport.ResponseHeaderTimeout,
// if not set or set to 0, its using Options.Timeout.
ResponseHeaderTimeout time.Duration
// ExpectContinueTimeout see
// https://golang.org/pkg/net/http/#Transport.ExpectContinueTimeout,
// if not set or set to 0, its using Options.Timeout.
ExpectContinueTimeout time.Duration
// Tracer instance, can be nil to not enable tracing
Tracer opentracing.Tracer
// BearerTokenFile injects bearer token read from file, which
// file path is the given string. In case SecretsReader is
// provided, BearerTokenFile will be ignored.
BearerTokenFile string
// BearerTokenRefreshInterval refresh bearer from
// BearerTokenFile. In case SecretsReader is provided,
// BearerTokenFile will be ignored.
BearerTokenRefreshInterval time.Duration
// SecretsReader is used to read and refresh bearer tokens
SecretsReader secrets.SecretsReader
// Log is used for error logging
Log logging.Logger
// OpentracingComponentTag sets component tag for all requests
OpentracingComponentTag string
// OpentracingSpanName sets span name for all requests
OpentracingSpanName string
}
// Transport wraps an http.Transport and adds support for tracing and
// bearerToken injection.
type Transport struct {
quit chan struct{}
closed bool
tr *http.Transport
tracer opentracing.Tracer
spanName string
componentName string
bearerToken string
}
// NewTransport creates a wrapped http.Transport, with regular DNS
// lookups using CloseIdleConnections on every IdleConnTimeout. You
// can optionally add tracing. On teardown you have to use Close() to
// not leak a goroutine.
func NewTransport(options Options) *Transport {
// set default tracer
if options.Tracer == nil {
options.Tracer = &opentracing.NoopTracer{}
}
// set timeout defaults
if options.TLSHandshakeTimeout == 0 {
options.TLSHandshakeTimeout = options.Timeout
}
if options.IdleConnTimeout == 0 {
if options.Timeout != 0 {
options.IdleConnTimeout = options.Timeout
} else {
options.IdleConnTimeout = defaultIdleConnTimeout
}
}
if options.ResponseHeaderTimeout == 0 {
options.ResponseHeaderTimeout = options.Timeout
}
if options.ExpectContinueTimeout == 0 {
options.ExpectContinueTimeout = options.Timeout
}
htransport := &http.Transport{
DisableKeepAlives: options.DisableKeepAlives,
DisableCompression: options.DisableCompression,
ForceAttemptHTTP2: options.ForceAttemptHTTP2,
MaxIdleConns: options.MaxIdleConns,
MaxIdleConnsPerHost: options.MaxIdleConnsPerHost,
MaxConnsPerHost: options.MaxConnsPerHost,
WriteBufferSize: options.WriteBufferSize,
ReadBufferSize: options.ReadBufferSize,
MaxResponseHeaderBytes: options.MaxResponseHeaderBytes,
ResponseHeaderTimeout: options.ResponseHeaderTimeout,
TLSHandshakeTimeout: options.TLSHandshakeTimeout,
IdleConnTimeout: options.IdleConnTimeout,
ExpectContinueTimeout: options.ExpectContinueTimeout,
}
t := &Transport{
quit: make(chan struct{}),
tr: htransport,
tracer: options.Tracer,
}
if t.tracer != nil {
if options.OpentracingComponentTag != "" {
t = WithComponentTag(t, options.OpentracingComponentTag)
}
if options.OpentracingSpanName != "" {
t = WithSpanName(t, options.OpentracingSpanName)
}
}
go func() {
for {
select {
case <-time.After(options.IdleConnTimeout):
htransport.CloseIdleConnections()
case <-t.quit:
return
}
}
}()
return t
}
// WithSpanName sets the name of the span, if you have an enabled
// tracing Transport.
func WithSpanName(t *Transport, spanName string) *Transport {
tt := t.shallowCopy()
tt.spanName = spanName
return tt
}
// WithComponentTag sets the component name, if you have an enabled
// tracing Transport.
func WithComponentTag(t *Transport, componentName string) *Transport {
tt := t.shallowCopy()
tt.componentName = componentName
return tt
}
// WithBearerToken adds an Authorization header with "Bearer " prefix
// and add the given bearerToken as value to all requests. To regular
// update your token you need to call this method and use the returned
// Transport.
func WithBearerToken(t *Transport, bearerToken string) *Transport {
tt := t.shallowCopy()
tt.bearerToken = bearerToken
return tt
}
func (t *Transport) shallowCopy() *Transport {
tt := *t
return &tt
}
func (t *Transport) Close() {
if !t.closed {
t.closed = true
close(t.quit)
}
}
func (t *Transport) CloseIdleConnections() {
t.tr.CloseIdleConnections()
}
// RoundTrip the request with tracing, bearer token injection and add client
// tracing: DNS, TCP/IP, TLS handshake, connection pool access. Client
// traces are added as logs into the created span.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
var span opentracing.Span
if t.spanName != "" {
req, span = t.injectSpan(req)
defer span.Finish()
req = injectClientTrace(req, span)
span.LogKV("http_do", "start")
}
if t.bearerToken != "" {
req.Header.Set("Authorization", "Bearer "+t.bearerToken)
}
rsp, err := t.tr.RoundTrip(req)
if span != nil {
span.LogKV("http_do", "stop")
if rsp != nil {
ext.HTTPStatusCode.Set(span, uint16(rsp.StatusCode))
}
}
return rsp, err
}
func (t *Transport) injectSpan(req *http.Request) (*http.Request, opentracing.Span) {
parentSpan := opentracing.SpanFromContext(req.Context())
var span opentracing.Span
if parentSpan != nil {
req = req.WithContext(opentracing.ContextWithSpan(req.Context(), parentSpan))
span = t.tracer.StartSpan(t.spanName, opentracing.ChildOf(parentSpan.Context()))
} else {
span = t.tracer.StartSpan(t.spanName)
}
// add Tags
ext.Component.Set(span, t.componentName)
ext.HTTPUrl.Set(span, req.URL.String())
ext.HTTPMethod.Set(span, req.Method)
ext.SpanKind.Set(span, "client")
_ = t.tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
return req, span
}
func injectClientTrace(req *http.Request, span opentracing.Span) *http.Request {
trace := &httptrace.ClientTrace{
DNSStart: func(httptrace.DNSStartInfo) {
span.LogKV("DNS", "start")
},
DNSDone: func(httptrace.DNSDoneInfo) {
span.LogKV("DNS", "end")
},
ConnectStart: func(string, string) {
span.LogKV("connect", "start")
},
ConnectDone: func(string, string, error) {
span.LogKV("connect", "end")
},
TLSHandshakeStart: func() {
span.LogKV("TLS", "start")
},
TLSHandshakeDone: func(tls.ConnectionState, error) {
span.LogKV("TLS", "end")
},
GetConn: func(string) {
span.LogKV("get_conn", "start")
},
GotConn: func(httptrace.GotConnInfo) {
span.LogKV("get_conn", "end")
},
}
return req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
}