query.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package prom
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "github.com/kubecost/cost-model/pkg/util"
  8. prometheus "github.com/prometheus/client_golang/api"
  9. "k8s.io/klog"
  10. )
  11. const (
  12. apiPrefix = "/api/v1"
  13. epQuery = apiPrefix + "/query"
  14. )
  15. // Context wraps a Prometheus client and provides methods for querying and
  16. // parsing query responses and errors.
  17. type Context struct {
  18. Client prometheus.Client
  19. ErrorCollector *util.ErrorCollector
  20. semaphore *util.Semaphore
  21. }
  22. // NewContext creates a new Promethues querying context from the given client
  23. func NewContext(client prometheus.Client) *Context {
  24. var ec util.ErrorCollector
  25. // By deafult, allow 20 concurrent queries, which is the Prometheus default
  26. sem := util.NewSemaphore(20)
  27. return &Context{
  28. Client: client,
  29. ErrorCollector: &ec,
  30. semaphore: sem,
  31. }
  32. }
  33. // Errors returns the errors collected from the Context's ErrorCollector
  34. func (ctx *Context) Errors() []error {
  35. return ctx.ErrorCollector.Errors()
  36. }
  37. // TODO SetMaxConcurrency
  38. // QueryAll returns one QueryResultsChan for each query provided, then runs
  39. // each query concurrently and returns results on each channel, respectively,
  40. // in the order they were provided; i.e. the response to queries[1] will be
  41. // sent on channel resChs[1].
  42. func (ctx *Context) QueryAll(queries ...string) []QueryResultsChan {
  43. resChs := []QueryResultsChan{}
  44. for _, q := range queries {
  45. resChs = append(resChs, ctx.Query(q))
  46. }
  47. return resChs
  48. }
  49. // Query returns a QueryResultsChan, then runs the given query and sends the
  50. // results on the provided channel. Receiver is responsible for closing the
  51. // channel, preferably using the Read method.
  52. func (ctx *Context) Query(query string) QueryResultsChan {
  53. resCh := make(QueryResultsChan)
  54. go func(ctx *Context, resCh QueryResultsChan) {
  55. raw, promErr := ctx.query(query)
  56. ctx.ErrorCollector.Report(promErr)
  57. results, parseErr := NewQueryResults(raw)
  58. ctx.ErrorCollector.Report(parseErr)
  59. resCh <- results
  60. }(ctx, resCh)
  61. return resCh
  62. }
  63. func (ctx *Context) query(query string) (interface{}, error) {
  64. ctx.semaphore.Acquire()
  65. defer ctx.semaphore.Return()
  66. u := ctx.Client.URL(epQuery, nil)
  67. q := u.Query()
  68. q.Set("query", query)
  69. u.RawQuery = q.Encode()
  70. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  71. if err != nil {
  72. return nil, err
  73. }
  74. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  75. for _, w := range warnings {
  76. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  77. }
  78. if err != nil {
  79. if resp == nil {
  80. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  81. }
  82. return nil, fmt.Errorf("%d Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  83. }
  84. var toReturn interface{}
  85. err = json.Unmarshal(body, &toReturn)
  86. if err != nil {
  87. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  88. }
  89. return toReturn, nil
  90. }