query.go 5.7 KB

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