query.go 2.9 KB

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