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