prom.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package prom
  2. import (
  3. "context"
  4. "net/http"
  5. "net/url"
  6. "github.com/kubecost/cost-model/pkg/util"
  7. prometheus "github.com/prometheus/client_golang/api"
  8. )
  9. // NewRateLimitedClient creates a prometheus client which limits the number of concurrent outbound
  10. // prometheus requests.
  11. func NewRateLimitedClient(config prometheus.Config, maxConcurrency int) (prometheus.Client, error) {
  12. c, err := prometheus.NewClient(config)
  13. if err != nil {
  14. return nil, err
  15. }
  16. limiter := util.NewSemaphore(maxConcurrency)
  17. return &RateLimitedPrometheusClient{
  18. client: c,
  19. limiter: limiter,
  20. }, nil
  21. }
  22. // Creates a new prometheus client which limits the total number of concurrent outbound requests
  23. // allowed at a given moment.
  24. type RateLimitedPrometheusClient struct {
  25. client prometheus.Client
  26. limiter *util.Semaphore
  27. }
  28. // Passthrough to the prometheus client API
  29. func (rlpc *RateLimitedPrometheusClient) URL(ep string, args map[string]string) *url.URL {
  30. return rlpc.client.URL(ep, args)
  31. }
  32. // Rate limit and passthrough to prometheus client API
  33. func (rlpc *RateLimitedPrometheusClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, prometheus.Warnings, error) {
  34. rlpc.limiter.Acquire()
  35. defer rlpc.limiter.Return()
  36. return rlpc.client.Do(ctx, req)
  37. }