feat(inputs.kubernetes): Apply timeout for the whole HTTP request (#12918)

This commit is contained in:
Maxim Ivanov 2023-03-22 12:33:53 +00:00 committed by GitHub
parent 3c8277d502
commit 771153e76d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 7 deletions

View File

@ -47,7 +47,7 @@ type Kubernetes struct {
Log telegraf.Logger `toml:"-"`
RoundTripper http.RoundTripper
httpClient *http.Client
}
const (
@ -244,16 +244,22 @@ func (k *Kubernetes) LoadJSON(url string, v interface{}) error {
if err != nil {
return err
}
if k.RoundTripper == nil {
if k.httpClient == nil {
if k.ResponseTimeout < config.Duration(time.Second) {
k.ResponseTimeout = config.Duration(time.Second * 5)
}
k.RoundTripper = &http.Transport{
TLSHandshakeTimeout: 5 * time.Second,
TLSClientConfig: tlsCfg,
ResponseHeaderTimeout: time.Duration(k.ResponseTimeout),
k.httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Duration(k.ResponseTimeout),
}
}
if k.BearerToken != "" {
token, err := os.ReadFile(k.BearerToken)
if err != nil {
@ -263,7 +269,7 @@ func (k *Kubernetes) LoadJSON(url string, v interface{}) error {
}
req.Header.Set("Authorization", "Bearer "+k.BearerTokenString)
req.Header.Add("Accept", "application/json")
resp, err = k.RoundTripper.RoundTrip(req)
resp, err = k.httpClient.Do(req)
if err != nil {
return fmt.Errorf("error making HTTP request to %q: %w", url, err)
}