query.go 2.7 KB

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