-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
http.go
423 lines (371 loc) · 13.3 KB
/
http.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
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package clientconfig
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"path"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
extpromhttp "github.com/thanos-io/thanos/pkg/extprom/http"
"github.com/go-kit/log"
"github.com/mwitkow/go-conntrack"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/common/version"
"github.com/prometheus/prometheus/discovery"
"github.com/prometheus/prometheus/discovery/file"
"github.com/prometheus/prometheus/discovery/targetgroup"
"golang.org/x/net/http2"
"gopkg.in/yaml.v2"
"github.com/thanos-io/thanos/pkg/discovery/cache"
)
// HTTPConfig is a structure that allows pointing to various HTTP endpoint, e.g ruler connecting to queriers.
type HTTPConfig struct {
HTTPClientConfig HTTPClientConfig `yaml:"http_config"`
EndpointsConfig HTTPEndpointsConfig `yaml:",inline"`
}
func (c *HTTPConfig) NotEmpty() bool {
return len(c.EndpointsConfig.FileSDConfigs) > 0 || len(c.EndpointsConfig.StaticAddresses) > 0
}
// HTTPClientConfig configures an HTTP client.
type HTTPClientConfig struct {
// The HTTP basic authentication credentials for the targets.
BasicAuth BasicAuth `yaml:"basic_auth"`
// The bearer token for the targets.
BearerToken string `yaml:"bearer_token"`
// The bearer token file for the targets.
BearerTokenFile string `yaml:"bearer_token_file"`
// HTTP proxy server to use to connect to the targets.
ProxyURL string `yaml:"proxy_url"`
// TLSConfig to use to connect to the targets.
TLSConfig TLSConfig `yaml:"tls_config"`
// TransportConfig for Client transport properties
TransportConfig TransportConfig `yaml:"transport_config"`
// ClientMetrics contains metrics that will be used to instrument
// the client that will be created with this config.
ClientMetrics *extpromhttp.ClientMetrics `yaml:"-"`
}
// TLSConfig configures TLS connections.
type TLSConfig struct {
// The CA cert to use for the targets.
CAFile string `yaml:"ca_file"`
// The client cert file for the targets.
CertFile string `yaml:"cert_file"`
// The client key file for the targets.
KeyFile string `yaml:"key_file"`
// Used to verify the hostname for the targets. See https://tools.ietf.org/html/rfc4366#section-3.1
ServerName string `yaml:"server_name"`
// Disable target certificate validation.
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
}
// BasicAuth configures basic authentication for HTTP clients.
type BasicAuth struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
PasswordFile string `yaml:"password_file"`
}
// IsZero returns false if basic authentication isn't enabled.
func (b BasicAuth) IsZero() bool {
return b.Username == "" && b.Password == "" && b.PasswordFile == ""
}
// TransportConfig configures client's transport properties.
type TransportConfig struct {
MaxIdleConns int `yaml:"max_idle_conns"`
MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host"`
IdleConnTimeout int64 `yaml:"idle_conn_timeout"`
ResponseHeaderTimeout int64 `yaml:"response_header_timeout"`
ExpectContinueTimeout int64 `yaml:"expect_continue_timeout"`
MaxConnsPerHost int `yaml:"max_conns_per_host"`
DisableCompression bool `yaml:"disable_compression"`
TLSHandshakeTimeout int64 `yaml:"tls_handshake_timeout"`
DialerTimeout int64 `yaml:"dialer_timeout"`
}
var defaultTransportConfig TransportConfig = TransportConfig{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 2,
ResponseHeaderTimeout: 0,
MaxConnsPerHost: 0,
IdleConnTimeout: int64(90 * time.Second),
ExpectContinueTimeout: int64(10 * time.Second),
DisableCompression: false,
TLSHandshakeTimeout: int64(10 * time.Second),
DialerTimeout: int64(5 * time.Second),
}
func NewDefaultHTTPClientConfig() HTTPClientConfig {
return HTTPClientConfig{TransportConfig: defaultTransportConfig}
}
func NewHTTPClientConfigFromYAML(cfg []byte) (*HTTPClientConfig, error) {
conf := &HTTPClientConfig{TransportConfig: defaultTransportConfig}
if err := yaml.Unmarshal(cfg, conf); err != nil {
return nil, err
}
return conf, nil
}
// NewRoundTripperFromConfig returns a new HTTP RoundTripper configured for the
// given http.HTTPClientConfig and http.HTTPClientOption.
func NewRoundTripperFromConfig(cfg config_util.HTTPClientConfig, transportConfig TransportConfig, name string) (http.RoundTripper, error) {
newRT := func(tlsConfig *tls.Config) (http.RoundTripper, error) {
var rt http.RoundTripper = &http.Transport{
Proxy: http.ProxyURL(cfg.ProxyURL.URL),
MaxIdleConns: transportConfig.MaxIdleConns,
MaxIdleConnsPerHost: transportConfig.MaxIdleConnsPerHost,
MaxConnsPerHost: transportConfig.MaxConnsPerHost,
TLSClientConfig: tlsConfig,
DisableCompression: transportConfig.DisableCompression,
IdleConnTimeout: time.Duration(transportConfig.IdleConnTimeout),
ResponseHeaderTimeout: time.Duration(transportConfig.ResponseHeaderTimeout),
ExpectContinueTimeout: time.Duration(transportConfig.ExpectContinueTimeout),
TLSHandshakeTimeout: time.Duration(transportConfig.TLSHandshakeTimeout),
DialContext: conntrack.NewDialContextFunc(
conntrack.DialWithDialer(&net.Dialer{
Timeout: time.Duration(transportConfig.DialerTimeout),
}),
conntrack.DialWithTracing(),
conntrack.DialWithName(name)),
}
// HTTP/2 support is golang has many problematic cornercases where
// dead connections would be kept and used in connection pools.
// https://github.com/golang/go/issues/32388
// https://github.com/golang/go/issues/39337
// https://github.com/golang/go/issues/39750
// TODO: Re-Enable HTTP/2 once upstream issue is fixed.
// TODO: use ForceAttemptHTTP2 when we move to Go 1.13+.
err := http2.ConfigureTransport(rt.(*http.Transport))
if err != nil {
return nil, err
}
// If an authorization_credentials is provided, create a round tripper that will set the
// Authorization header correctly on each request.
if cfg.Authorization != nil && len(cfg.Authorization.Credentials) > 0 {
rt = config_util.NewAuthorizationCredentialsRoundTripper(cfg.Authorization.Type, cfg.Authorization.Credentials, rt)
} else if cfg.Authorization != nil && len(cfg.Authorization.CredentialsFile) > 0 {
rt = config_util.NewAuthorizationCredentialsFileRoundTripper(cfg.Authorization.Type, cfg.Authorization.CredentialsFile, rt)
}
// Backwards compatibility, be nice with importers who would not have
// called Validate().
if len(cfg.BearerToken) > 0 {
rt = config_util.NewAuthorizationCredentialsRoundTripper("Bearer", cfg.BearerToken, rt)
} else if len(cfg.BearerTokenFile) > 0 {
rt = config_util.NewAuthorizationCredentialsFileRoundTripper("Bearer", cfg.BearerTokenFile, rt)
}
if cfg.BasicAuth != nil {
// TODO(yeya24): expose UsernameFile as a config.
rt = config_util.NewBasicAuthRoundTripper(cfg.BasicAuth.Username, cfg.BasicAuth.Password, "", cfg.BasicAuth.PasswordFile, rt)
}
// Return a new configured RoundTripper.
return rt, nil
}
tlsConfig, err := config_util.NewTLSConfig(&cfg.TLSConfig)
if err != nil {
return nil, err
}
if len(cfg.TLSConfig.CAFile) == 0 {
// No need for a RoundTripper that reloads the CA file automatically.
return newRT(tlsConfig)
}
return config_util.NewTLSRoundTripper(tlsConfig, config_util.TLSRoundTripperSettings{
CAFile: cfg.TLSConfig.CAFile,
CertFile: cfg.TLSConfig.CertFile,
KeyFile: cfg.TLSConfig.KeyFile,
}, newRT)
}
// NewHTTPClient returns a new HTTP client.
func NewHTTPClient(cfg HTTPClientConfig, name string) (*http.Client, error) {
httpClientConfig := config_util.HTTPClientConfig{
BearerToken: config_util.Secret(cfg.BearerToken),
BearerTokenFile: cfg.BearerTokenFile,
TLSConfig: config_util.TLSConfig{
CAFile: cfg.TLSConfig.CAFile,
CertFile: cfg.TLSConfig.CertFile,
KeyFile: cfg.TLSConfig.KeyFile,
ServerName: cfg.TLSConfig.ServerName,
InsecureSkipVerify: cfg.TLSConfig.InsecureSkipVerify,
},
}
if cfg.ProxyURL != "" {
var proxy config_util.URL
err := yaml.Unmarshal([]byte(cfg.ProxyURL), &proxy)
if err != nil {
return nil, err
}
httpClientConfig.ProxyURL = proxy
}
if !cfg.BasicAuth.IsZero() {
httpClientConfig.BasicAuth = &config_util.BasicAuth{
Username: cfg.BasicAuth.Username,
Password: config_util.Secret(cfg.BasicAuth.Password),
PasswordFile: cfg.BasicAuth.PasswordFile,
}
}
if cfg.BearerToken != "" {
httpClientConfig.BearerToken = config_util.Secret(cfg.BearerToken)
}
if cfg.BearerTokenFile != "" {
httpClientConfig.BearerTokenFile = cfg.BearerTokenFile
}
if err := httpClientConfig.Validate(); err != nil {
return nil, err
}
rt, err := NewRoundTripperFromConfig(
httpClientConfig,
cfg.TransportConfig,
name,
)
if err != nil {
return nil, err
}
if cfg.ClientMetrics != nil {
rt = extpromhttp.InstrumentedRoundTripper(rt, cfg.ClientMetrics)
}
rt = &userAgentRoundTripper{name: ThanosUserAgent, rt: rt}
client := &http.Client{Transport: rt}
return client, nil
}
var ThanosUserAgent = fmt.Sprintf("Thanos/%s", version.Version)
type userAgentRoundTripper struct {
name string
rt http.RoundTripper
}
// RoundTrip implements the http.RoundTripper interface.
func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
if r.UserAgent() == "" {
// The specification of http.RoundTripper says that it shouldn't mutate
// the request so make a copy of req.Header since this is all that is
// modified.
r2 := new(http.Request)
*r2 = *r
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
r2.Header.Set("User-Agent", u.name)
r = r2
}
return u.rt.RoundTrip(r)
}
// HTTPEndpointsConfig configures a cluster of HTTP endpoints from static addresses and
// file service discovery.
type HTTPEndpointsConfig struct {
// List of addresses with DNS prefixes.
StaticAddresses []string `yaml:"static_configs"`
// List of file configurations (our FileSD supports different DNS lookups).
FileSDConfigs []HTTPFileSDConfig `yaml:"file_sd_configs"`
// The URL scheme to use when talking to targets.
Scheme string `yaml:"scheme"`
// Path prefix to add in front of the endpoint path.
PathPrefix string `yaml:"path_prefix"`
}
// HTTPFileSDConfig represents a file service discovery configuration.
type HTTPFileSDConfig struct {
Files []string `yaml:"files"`
RefreshInterval model.Duration `yaml:"refresh_interval"`
}
func (c HTTPFileSDConfig) convert() (file.SDConfig, error) {
var fileSDConfig file.SDConfig
b, err := yaml.Marshal(c)
if err != nil {
return fileSDConfig, err
}
err = yaml.Unmarshal(b, &fileSDConfig)
return fileSDConfig, err
}
type AddressProvider interface {
Resolve(context.Context, []string) error
Addresses() []string
}
// HTTPClient represents a client that can send requests to a cluster of HTTP-based endpoints.
type HTTPClient struct {
logger log.Logger
httpClient *http.Client
scheme string
prefix string
staticAddresses []string
fileSDCache *cache.Cache
fileDiscoverers []*file.Discovery
provider AddressProvider
}
// NewClient returns a new Client.
func NewClient(logger log.Logger, cfg HTTPEndpointsConfig, client *http.Client, provider AddressProvider) (*HTTPClient, error) {
if logger == nil {
logger = log.NewNopLogger()
}
var discoverers []*file.Discovery
for _, sdCfg := range cfg.FileSDConfigs {
fileSDCfg, err := sdCfg.convert()
if err != nil {
return nil, err
}
// We provide an empty registry and ignore metrics for now.
sdReg := prometheus.NewRegistry()
fileSD, err := file.NewDiscovery(&fileSDCfg, logger, fileSDCfg.NewDiscovererMetrics(sdReg, discovery.NewRefreshMetrics(sdReg)))
if err != nil {
return nil, err
}
discoverers = append(discoverers, fileSD)
}
return &HTTPClient{
logger: logger,
httpClient: client,
scheme: cfg.Scheme,
prefix: cfg.PathPrefix,
staticAddresses: cfg.StaticAddresses,
fileSDCache: cache.New(),
fileDiscoverers: discoverers,
provider: provider,
}, nil
}
// Do executes an HTTP request with the underlying HTTP client.
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
return c.httpClient.Do(req)
}
// Endpoints returns the list of known endpoints.
func (c *HTTPClient) Endpoints() []*url.URL {
var urls []*url.URL
for _, addr := range c.provider.Addresses() {
urls = append(urls,
&url.URL{
Scheme: c.scheme,
Host: addr,
Path: path.Join("/", c.prefix),
},
)
}
return urls
}
// Discover runs the service to discover endpoints until the given context is done.
func (c *HTTPClient) Discover(ctx context.Context) {
var wg sync.WaitGroup
ch := make(chan []*targetgroup.Group)
for _, d := range c.fileDiscoverers {
wg.Add(1)
go func(d *file.Discovery) {
d.Run(ctx, ch)
wg.Done()
}(d)
}
func() {
for {
select {
case update := <-ch:
// Discoverers sometimes send nil updates so need to check for it to avoid panics.
if update == nil {
continue
}
c.fileSDCache.Update(update)
case <-ctx.Done():
return
}
}
}()
wg.Wait()
}
// Resolve refreshes and resolves the list of targets.
func (c *HTTPClient) Resolve(ctx context.Context) error {
return c.provider.Resolve(ctx, append(c.fileSDCache.Addresses(), c.staticAddresses...))
}