| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package confighttp // import "go.opentelemetry.io/collector/config/confighttp" |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"net/http" |
| 11 |
"net/http/cookiejar" |
| 12 |
"net/url" |
| 13 |
"time" |
| 14 |
|
| 15 |
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 16 |
"go.opentelemetry.io/otel" |
| 17 |
"golang.org/x/net/http2" |
| 18 |
"golang.org/x/net/publicsuffix" |
| 19 |
|
| 20 |
"go.opentelemetry.io/collector/component" |
| 21 |
"go.opentelemetry.io/collector/config/configauth" |
| 22 |
"go.opentelemetry.io/collector/config/configcompression" |
| 23 |
"go.opentelemetry.io/collector/config/configmiddleware" |
| 24 |
"go.opentelemetry.io/collector/config/configopaque" |
| 25 |
"go.opentelemetry.io/collector/config/configoptional" |
| 26 |
"go.opentelemetry.io/collector/config/configtls" |
| 27 |
) |
| 28 |
|
| 29 |
const ( |
| 30 |
headerContentEncoding = "Content-Encoding" |
| 31 |
) |
| 32 |
|
| 33 |
// ClientConfig defines settings for creating an HTTP client. |
| 34 |
type ClientConfig struct { |
| 35 |
// The target URL to send data to (e.g.: http://some.url:9411/v1/traces). |
| 36 |
Endpoint string `mapstructure:"endpoint,omitempty"` |
| 37 |
|
| 38 |
// ProxyURL setting for the collector |
| 39 |
ProxyURL string `mapstructure:"proxy_url,omitempty"` |
| 40 |
|
| 41 |
// TLS struct exposes TLS client configuration. |
| 42 |
TLS configtls.ClientConfig `mapstructure:"tls,omitempty"` |
| 43 |
|
| 44 |
// ReadBufferSize for HTTP client. See http.Transport.ReadBufferSize. |
| 45 |
// Default is 0. |
| 46 |
ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"` |
| 47 |
|
| 48 |
// WriteBufferSize for HTTP client. See http.Transport.WriteBufferSize. |
| 49 |
// Default is 0. |
| 50 |
WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"` |
| 51 |
|
| 52 |
// Timeout parameter configures `http.Client.Timeout`. |
| 53 |
// Default is 0 (unlimited). |
| 54 |
Timeout time.Duration `mapstructure:"timeout,omitempty"` |
| 55 |
|
| 56 |
// Additional headers attached to each HTTP request sent by the client. |
| 57 |
// Existing header values are overwritten if collision happens. |
| 58 |
// Header values are opaque since they may be sensitive. |
| 59 |
Headers configopaque.MapList `mapstructure:"headers,omitempty"` |
| 60 |
|
| 61 |
// Auth configuration for outgoing HTTP calls. |
| 62 |
Auth configoptional.Optional[configauth.Config] `mapstructure:"auth,omitempty"` |
| 63 |
|
| 64 |
// The compression key for supported compression types within collector. |
| 65 |
Compression configcompression.Type `mapstructure:"compression,omitempty"` |
| 66 |
|
| 67 |
// Advanced configuration options for the Compression |
| 68 |
CompressionParams configcompression.CompressionParams `mapstructure:"compression_params,omitempty"` |
| 69 |
|
| 70 |
// MaxIdleConns is used to set a limit to the maximum idle HTTP connections the client can keep open. |
| 71 |
// By default, it is set to 100. Zero means no limit. |
| 72 |
MaxIdleConns int `mapstructure:"max_idle_conns"` |
| 73 |
|
| 74 |
// MaxIdleConnsPerHost is used to set a limit to the maximum idle HTTP connections the host can keep open. |
| 75 |
// If zero, [net/http.DefaultMaxIdleConnsPerHost] is used. |
| 76 |
MaxIdleConnsPerHost int `mapstructure:"max_idle_conns_per_host,omitempty"` |
| 77 |
|
| 78 |
// MaxConnsPerHost limits the total number of connections per host, including connections in the dialing, |
| 79 |
// active, and idle states. Default is 0 (unlimited). |
| 80 |
MaxConnsPerHost int `mapstructure:"max_conns_per_host,omitempty"` |
| 81 |
|
| 82 |
// IdleConnTimeout is the maximum amount of time a connection will remain open before closing itself. |
| 83 |
// By default, it is set to 90 seconds. |
| 84 |
IdleConnTimeout time.Duration `mapstructure:"idle_conn_timeout"` |
| 85 |
|
| 86 |
// DisableKeepAlives, if true, disables HTTP keep-alives and will only use the connection to the server |
| 87 |
// for a single HTTP request. |
| 88 |
// |
| 89 |
// WARNING: enabling this option can result in significant overhead establishing a new HTTP(S) |
| 90 |
// connection for every request. Before enabling this option please consider whether changes |
| 91 |
// to idle connection settings can achieve your goal. |
| 92 |
DisableKeepAlives bool `mapstructure:"disable_keep_alives,omitempty"` |
| 93 |
|
| 94 |
// This is needed in case you run into |
| 95 |
// https://github.com/golang/go/issues/59690 |
| 96 |
// https://github.com/golang/go/issues/36026 |
| 97 |
// HTTP2ReadIdleTimeout if the connection has been idle for the configured value send a ping frame for health check |
| 98 |
// 0s means no health check will be performed. |
| 99 |
HTTP2ReadIdleTimeout time.Duration `mapstructure:"http2_read_idle_timeout,omitempty"` |
| 100 |
// HTTP2PingTimeout if there's no response to the ping within the configured value, the connection will be closed. |
| 101 |
// If not set or set to 0, it defaults to 15s. |
| 102 |
HTTP2PingTimeout time.Duration `mapstructure:"http2_ping_timeout,omitempty"` |
| 103 |
// Cookies configures the cookie management of the HTTP client. |
| 104 |
Cookies configoptional.Optional[CookiesConfig] `mapstructure:"cookies,omitempty"` |
| 105 |
|
| 106 |
// Enabling ForceAttemptHTTP2 forces the HTTP transport to use the HTTP/2 protocol. |
| 107 |
// By default, this is set to true. |
| 108 |
// NOTE: HTTP/2 does not support settings such as MaxConnsPerHost, MaxIdleConnsPerHost and MaxIdleConns. |
| 109 |
ForceAttemptHTTP2 bool `mapstructure:"force_attempt_http2,omitempty"` |
| 110 |
|
| 111 |
// Middlewares are used to add custom functionality to the HTTP client. |
| 112 |
// Middleware handlers are called in the order they appear in this list, |
| 113 |
// with the first middleware becoming the outermost handler. |
| 114 |
Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"` |
| 115 |
} |
| 116 |
|
| 117 |
// CookiesConfig defines the configuration of the HTTP client regarding cookies served by the server. |
| 118 |
type CookiesConfig struct { |
| 119 |
_ struct{} |
| 120 |
} |
| 121 |
|
| 122 |
// NewDefaultClientConfig returns ClientConfig type object with |
| 123 |
// the default values of 'MaxIdleConns' and 'IdleConnTimeout', as well as [http.DefaultTransport] values. |
| 124 |
// Other config options are not added as they are initialized with 'zero value' by GoLang as default. |
| 125 |
// We encourage to use this function to create an object of ClientConfig. |
| 126 |
func NewDefaultClientConfig() ClientConfig { |
| 127 |
// The default values are taken from the values of 'DefaultTransport' of 'http' package. |
| 128 |
defaultTransport := http.DefaultTransport.(*http.Transport) |
| 129 |
|
| 130 |
return ClientConfig{ |
| 131 |
MaxIdleConns: defaultTransport.MaxIdleConns, |
| 132 |
IdleConnTimeout: defaultTransport.IdleConnTimeout, |
| 133 |
ForceAttemptHTTP2: true, |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
func (cc *ClientConfig) Validate() error { |
| 138 |
if cc.Compression.IsCompressed() { |
| 139 |
if err := cc.Compression.ValidateParams(cc.CompressionParams); err != nil { |
| 140 |
return err |
| 141 |
} |
| 142 |
} |
| 143 |
return nil |
| 144 |
} |
| 145 |
|
| 146 |
// ToClientOption is an option to change the behavior of the HTTP client |
| 147 |
// returned by ClientConfig.ToClient(). |
| 148 |
// There are currently no available options. |
| 149 |
type ToClientOption interface { |
| 150 |
sealed() |
| 151 |
} |
| 152 |
|
| 153 |
// ToClient creates an HTTP client. |
| 154 |
// |
| 155 |
// To allow the configuration to reference middleware or authentication extensions, |
| 156 |
// the `extensions` argument should be the output of `host.GetExtensions()`. |
| 157 |
// It may also be `nil` in tests where no such extension is expected to be used. |
| 158 |
func (cc *ClientConfig) ToClient(ctx context.Context, extensions map[component.ID]component.Component, settings component.TelemetrySettings, _ ...ToClientOption) (*http.Client, error) { |
| 159 |
tlsCfg, err := cc.TLS.LoadTLSConfig(ctx) |
| 160 |
if err != nil { |
| 161 |
return nil, err |
| 162 |
} |
| 163 |
transport := http.DefaultTransport.(*http.Transport).Clone() |
| 164 |
if tlsCfg != nil { |
| 165 |
transport.TLSClientConfig = tlsCfg |
| 166 |
} |
| 167 |
if cc.ReadBufferSize > 0 { |
| 168 |
transport.ReadBufferSize = cc.ReadBufferSize |
| 169 |
} |
| 170 |
if cc.WriteBufferSize > 0 { |
| 171 |
transport.WriteBufferSize = cc.WriteBufferSize |
| 172 |
} |
| 173 |
|
| 174 |
transport.MaxIdleConns = cc.MaxIdleConns |
| 175 |
transport.MaxIdleConnsPerHost = cc.MaxIdleConnsPerHost |
| 176 |
transport.MaxConnsPerHost = cc.MaxConnsPerHost |
| 177 |
transport.IdleConnTimeout = cc.IdleConnTimeout |
| 178 |
transport.ForceAttemptHTTP2 = cc.ForceAttemptHTTP2 |
| 179 |
|
| 180 |
// Setting the Proxy URL |
| 181 |
if cc.ProxyURL != "" { |
| 182 |
proxyURL, parseErr := url.ParseRequestURI(cc.ProxyURL) |
| 183 |
if parseErr != nil { |
| 184 |
return nil, parseErr |
| 185 |
} |
| 186 |
transport.Proxy = http.ProxyURL(proxyURL) |
| 187 |
} |
| 188 |
|
| 189 |
transport.DisableKeepAlives = cc.DisableKeepAlives |
| 190 |
|
| 191 |
if cc.HTTP2ReadIdleTimeout > 0 { |
| 192 |
transport2, transportErr := http2.ConfigureTransports(transport) |
| 193 |
if transportErr != nil { |
| 194 |
return nil, fmt.Errorf("failed to configure http2 transport: %w", transportErr) |
| 195 |
} |
| 196 |
transport2.ReadIdleTimeout = cc.HTTP2ReadIdleTimeout |
| 197 |
transport2.PingTimeout = cc.HTTP2PingTimeout |
| 198 |
} |
| 199 |
|
| 200 |
clientTransport := http.RoundTripper(transport) |
| 201 |
|
| 202 |
// Apply middlewares in reverse order so they execute in |
| 203 |
// forward order. The first middleware runs after authentication. |
| 204 |
if len(cc.Middlewares) > 0 && extensions == nil { |
| 205 |
return nil, errors.New("middlewares were configured but this component or its host does not support extensions") |
| 206 |
} |
| 207 |
for i := len(cc.Middlewares) - 1; i >= 0; i-- { |
| 208 |
var wrapper func(http.RoundTripper) (http.RoundTripper, error) |
| 209 |
wrapper, err = cc.Middlewares[i].GetHTTPClientRoundTripper(ctx, extensions) |
| 210 |
// If we failed to get the middleware |
| 211 |
if err != nil { |
| 212 |
return nil, err |
| 213 |
} |
| 214 |
clientTransport, err = wrapper(clientTransport) |
| 215 |
// If we failed to construct a wrapper |
| 216 |
if err != nil { |
| 217 |
return nil, err |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// The Auth RoundTripper should always be the innermost to ensure that |
| 222 |
// request signing-based auth mechanisms operate after compression |
| 223 |
// and header middleware modifies the request |
| 224 |
if cc.Auth.HasValue() { |
| 225 |
if extensions == nil { |
| 226 |
return nil, errors.New("authentication was configured but this component or its host does not support extensions") |
| 227 |
} |
| 228 |
|
| 229 |
auth := cc.Auth.Get() |
| 230 |
httpCustomAuthRoundTripper, aerr := auth.GetHTTPClientAuthenticator(ctx, extensions) |
| 231 |
if aerr != nil { |
| 232 |
return nil, aerr |
| 233 |
} |
| 234 |
|
| 235 |
clientTransport, err = httpCustomAuthRoundTripper.RoundTripper(clientTransport) |
| 236 |
if err != nil { |
| 237 |
return nil, err |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
if len(cc.Headers) > 0 { |
| 242 |
clientTransport = &headerRoundTripper{ |
| 243 |
transport: clientTransport, |
| 244 |
headers: cc.Headers, |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
// Compress the body using specified compression methods if non-empty string is provided. |
| 249 |
// Supporting gzip, zlib, deflate, snappy, and zstd; none is treated as uncompressed. |
| 250 |
if cc.Compression.IsCompressed() { |
| 251 |
// If the compression level is not set, use the default level. |
| 252 |
if cc.CompressionParams.Level == 0 { |
| 253 |
cc.CompressionParams.Level = configcompression.DefaultCompressionLevel |
| 254 |
} |
| 255 |
clientTransport, err = newCompressRoundTripper(clientTransport, cc.Compression, cc.CompressionParams) |
| 256 |
if err != nil { |
| 257 |
return nil, err |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
otelOpts := []otelhttp.Option{ |
| 262 |
otelhttp.WithTracerProvider(settings.TracerProvider), |
| 263 |
otelhttp.WithPropagators(otel.GetTextMapPropagator()), |
| 264 |
otelhttp.WithMeterProvider(settings.MeterProvider), |
| 265 |
} |
| 266 |
// wrapping http transport with otelhttp transport to enable otel instrumentation |
| 267 |
if settings.TracerProvider != nil && settings.MeterProvider != nil { |
| 268 |
clientTransport = otelhttp.NewTransport(clientTransport, otelOpts...) |
| 269 |
} |
| 270 |
|
| 271 |
var jar http.CookieJar |
| 272 |
if cc.Cookies.HasValue() { |
| 273 |
jar, err = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) |
| 274 |
if err != nil { |
| 275 |
return nil, err |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
return &http.Client{ |
| 280 |
Transport: clientTransport, |
| 281 |
Timeout: cc.Timeout, |
| 282 |
Jar: jar, |
| 283 |
}, nil |
| 284 |
} |
| 285 |
|
| 286 |
// Custom RoundTripper that adds headers. |
| 287 |
type headerRoundTripper struct { |
| 288 |
transport http.RoundTripper |
| 289 |
headers configopaque.MapList |
| 290 |
} |
| 291 |
|
| 292 |
// RoundTrip is a custom RoundTripper that adds headers to the request. |
| 293 |
func (interceptor *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 294 |
// Set Host header if provided |
| 295 |
hostHeader, found := interceptor.headers.Get("Host") |
| 296 |
if found && hostHeader != "" { |
| 297 |
// `Host` field should be set to override default `Host` header value which is Endpoint |
| 298 |
req.Host = string(hostHeader) |
| 299 |
} |
| 300 |
for k, v := range interceptor.headers.Iter { |
| 301 |
req.Header.Set(k, string(v)) |
| 302 |
} |
| 303 |
|
| 304 |
// Send the request to next transport. |
| 305 |
return interceptor.transport.RoundTrip(req) |
| 306 |
} |