httprequest.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package splunk // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/splunk"
  4. import (
  5. "fmt"
  6. "net/http"
  7. "net/http/httputil"
  8. "strconv"
  9. "time"
  10. "go.opentelemetry.io/collector/consumer/consumererror"
  11. "go.opentelemetry.io/collector/exporter/exporterhelper"
  12. "go.uber.org/multierr"
  13. )
  14. const HeaderRetryAfter = "Retry-After"
  15. // HandleHTTPCode handles an http response and returns the right type of error in case of a failure.
  16. func HandleHTTPCode(resp *http.Response) error {
  17. // Splunk accepts all 2XX codes.
  18. if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {
  19. return nil
  20. }
  21. err := fmt.Errorf(
  22. "HTTP %d %q",
  23. resp.StatusCode,
  24. http.StatusText(resp.StatusCode))
  25. switch resp.StatusCode {
  26. // Check for responses that may include "Retry-After" header.
  27. case http.StatusTooManyRequests, http.StatusServiceUnavailable:
  28. // Fallback to 0 if the Retry-After header is not present. This will trigger the
  29. // default backoff policy by our caller (retry handler).
  30. retryAfter := 0
  31. if val := resp.Header.Get(HeaderRetryAfter); val != "" {
  32. if seconds, err2 := strconv.Atoi(val); err2 == nil {
  33. retryAfter = seconds
  34. }
  35. }
  36. // Indicate to our caller to pause for the specified number of seconds.
  37. err = exporterhelper.NewThrottleRetry(err, time.Duration(retryAfter)*time.Second)
  38. // Check for permanent errors.
  39. case http.StatusBadRequest, http.StatusUnauthorized:
  40. dump, err2 := httputil.DumpResponse(resp, true)
  41. if err2 == nil {
  42. err = consumererror.NewPermanent(fmt.Errorf("%w", fmt.Errorf("%q", dump)))
  43. } else {
  44. err = multierr.Append(err, err2)
  45. }
  46. }
  47. return err
  48. }