query.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package prom
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/errors"
  10. "github.com/kubecost/cost-model/pkg/util"
  11. prometheus "github.com/prometheus/client_golang/api"
  12. "k8s.io/klog"
  13. )
  14. const (
  15. apiPrefix = "/api/v1"
  16. epQuery = apiPrefix + "/query"
  17. )
  18. // Context wraps a Prometheus client and provides methods for querying and
  19. // parsing query responses and errors.
  20. type Context struct {
  21. Client prometheus.Client
  22. ErrorCollector *errors.ErrorCollector
  23. }
  24. // NewContext creates a new Promethues querying context from the given client
  25. func NewContext(client prometheus.Client) *Context {
  26. var ec errors.ErrorCollector
  27. return &Context{
  28. Client: client,
  29. ErrorCollector: &ec,
  30. }
  31. }
  32. // Errors returns the errors collected from the Context's ErrorCollector
  33. func (ctx *Context) Errors() []error {
  34. return ctx.ErrorCollector.Errors()
  35. }
  36. // HasErrors returns true if the ErrorCollector has errors
  37. func (ctx *Context) HasErrors() bool {
  38. return ctx.ErrorCollector.IsError()
  39. }
  40. // Query returns a QueryResultsChan, then runs the given query and sends the
  41. // results on the provided channel. Receiver is responsible for closing the
  42. // channel, preferably using the Read method.
  43. func (ctx *Context) Query(query string) QueryResultsChan {
  44. resCh := make(QueryResultsChan)
  45. go func(ctx *Context, resCh QueryResultsChan) {
  46. defer errors.HandlePanic()
  47. raw, promErr := ctx.query(query)
  48. ctx.ErrorCollector.Report(promErr)
  49. results, parseErr := NewQueryResults(query, raw)
  50. ctx.ErrorCollector.Report(parseErr)
  51. resCh <- results
  52. }(ctx, resCh)
  53. return resCh
  54. }
  55. // QueryAll returns one QueryResultsChan for each query provided, then runs
  56. // each query concurrently and returns results on each channel, respectively,
  57. // in the order they were provided; i.e. the response to queries[1] will be
  58. // sent on channel resChs[1].
  59. func (ctx *Context) QueryAll(queries ...string) []QueryResultsChan {
  60. resChs := []QueryResultsChan{}
  61. for _, q := range queries {
  62. resChs = append(resChs, ctx.Query(q))
  63. }
  64. return resChs
  65. }
  66. func (ctx *Context) QuerySync(query string) (*QueryResults, error) {
  67. raw, err := ctx.query(query)
  68. if err != nil {
  69. return nil, err
  70. }
  71. results, err := NewQueryResults(query, raw)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return results, nil
  76. }
  77. func (ctx *Context) query(query string) (interface{}, error) {
  78. u := ctx.Client.URL(epQuery, nil)
  79. q := u.Query()
  80. q.Set("query", query)
  81. u.RawQuery = q.Encode()
  82. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  83. if err != nil {
  84. return nil, err
  85. }
  86. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  87. for _, w := range warnings {
  88. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  89. }
  90. if err != nil {
  91. if resp == nil {
  92. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  93. }
  94. return nil, fmt.Errorf("%d Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  95. }
  96. var toReturn interface{}
  97. err = json.Unmarshal(body, &toReturn)
  98. if err != nil {
  99. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  100. }
  101. return toReturn, nil
  102. }
  103. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) QueryResultsChan {
  104. resCh := make(QueryResultsChan)
  105. go func(ctx *Context, resCh QueryResultsChan) {
  106. defer errors.HandlePanic()
  107. raw, promErr := ctx.queryRange(query, start, end, step)
  108. ctx.ErrorCollector.Report(promErr)
  109. results, parseErr := NewQueryResults(query, raw)
  110. ctx.ErrorCollector.Report(parseErr)
  111. resCh <- results
  112. }(ctx, resCh)
  113. return resCh
  114. }
  115. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) (*QueryResults, error) {
  116. raw, err := ctx.queryRange(query, start, end, step)
  117. if err != nil {
  118. return nil, err
  119. }
  120. results, err := NewQueryResults(query, raw)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return results, nil
  125. }
  126. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, error) {
  127. u := ctx.Client.URL(epQuery, nil)
  128. q := u.Query()
  129. q.Set("query", query)
  130. q.Set("start", start.Format(time.RFC3339Nano))
  131. q.Set("end", end.Format(time.RFC3339Nano))
  132. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  133. u.RawQuery = q.Encode()
  134. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  135. if err != nil {
  136. return nil, err
  137. }
  138. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  139. for _, w := range warnings {
  140. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  141. }
  142. if err != nil {
  143. if resp == nil {
  144. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  145. }
  146. 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)
  147. }
  148. // Unsuccessful Status Code, log body and status
  149. statusCode := resp.StatusCode
  150. statusText := http.StatusText(statusCode)
  151. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  152. return nil, fmt.Errorf("%d (%s) Headers: %s, Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), body, query)
  153. }
  154. var toReturn interface{}
  155. err = json.Unmarshal(body, &toReturn)
  156. if err != nil {
  157. return nil, fmt.Errorf("%d (%s) Headers: %s Error: %s Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), err.Error(), body, query)
  158. }
  159. return toReturn, nil
  160. }