query.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 := NewQueryResults(query, raw)
  52. if results.Error != nil {
  53. ctx.ErrorCollector.Report(results.Error)
  54. }
  55. resCh <- results
  56. }(ctx, resCh)
  57. return resCh
  58. }
  59. // QueryAll returns one QueryResultsChan for each query provided, then runs
  60. // each query concurrently and returns results on each channel, respectively,
  61. // in the order they were provided; i.e. the response to queries[1] will be
  62. // sent on channel resChs[1].
  63. func (ctx *Context) QueryAll(queries ...string) []QueryResultsChan {
  64. resChs := []QueryResultsChan{}
  65. for _, q := range queries {
  66. resChs = append(resChs, ctx.Query(q))
  67. }
  68. return resChs
  69. }
  70. func (ctx *Context) QuerySync(query string) ([]*QueryResult, error) {
  71. raw, err := ctx.query(query)
  72. if err != nil {
  73. return nil, err
  74. }
  75. results := NewQueryResults(query, raw)
  76. if results.Error != nil {
  77. return nil, results.Error
  78. }
  79. return results.Results, nil
  80. }
  81. // QueryURL returns the URL used to query Prometheus
  82. func (ctx *Context) QueryURL() *url.URL {
  83. return ctx.Client.URL(epQuery, nil)
  84. }
  85. func (ctx *Context) query(query string) (interface{}, error) {
  86. u := ctx.Client.URL(epQuery, nil)
  87. q := u.Query()
  88. q.Set("query", query)
  89. u.RawQuery = q.Encode()
  90. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  91. if err != nil {
  92. return nil, err
  93. }
  94. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  95. for _, w := range warnings {
  96. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  97. }
  98. if err != nil {
  99. if resp == nil {
  100. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  101. }
  102. return nil, fmt.Errorf("%d Error %s fetching query %s", resp.StatusCode, err.Error(), query)
  103. }
  104. var toReturn interface{}
  105. err = json.Unmarshal(body, &toReturn)
  106. if err != nil {
  107. return nil, fmt.Errorf("Error %s fetching query %s", err.Error(), query)
  108. }
  109. return toReturn, nil
  110. }
  111. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) QueryResultsChan {
  112. resCh := make(QueryResultsChan)
  113. go func(ctx *Context, resCh QueryResultsChan) {
  114. defer errors.HandlePanic()
  115. raw, promErr := ctx.queryRange(query, start, end, step)
  116. ctx.ErrorCollector.Report(promErr)
  117. results := NewQueryResults(query, raw)
  118. if results.Error != nil {
  119. ctx.ErrorCollector.Report(results.Error)
  120. }
  121. resCh <- results
  122. }(ctx, resCh)
  123. return resCh
  124. }
  125. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) ([]*QueryResult, error) {
  126. raw, err := ctx.queryRange(query, start, end, step)
  127. if err != nil {
  128. return nil, err
  129. }
  130. results := NewQueryResults(query, raw)
  131. if results.Error != nil {
  132. return nil, results.Error
  133. }
  134. return results.Results, nil
  135. }
  136. // QueryRangeURL returns the URL used to query_range Prometheus
  137. func (ctx *Context) QueryRangeURL() *url.URL {
  138. return ctx.Client.URL(epQueryRange, nil)
  139. }
  140. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, error) {
  141. u := ctx.Client.URL(epQueryRange, nil)
  142. q := u.Query()
  143. q.Set("query", query)
  144. q.Set("start", start.Format(time.RFC3339Nano))
  145. q.Set("end", end.Format(time.RFC3339Nano))
  146. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  147. u.RawQuery = q.Encode()
  148. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  149. if err != nil {
  150. return nil, err
  151. }
  152. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  153. for _, w := range warnings {
  154. klog.V(3).Infof("Warning '%s' fetching query '%s'", w, query)
  155. }
  156. if err != nil {
  157. if resp == nil {
  158. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  159. }
  160. 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)
  161. }
  162. // Unsuccessful Status Code, log body and status
  163. statusCode := resp.StatusCode
  164. statusText := http.StatusText(statusCode)
  165. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  166. return nil, fmt.Errorf("%d (%s) Headers: %s, Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), body, query)
  167. }
  168. var toReturn interface{}
  169. err = json.Unmarshal(body, &toReturn)
  170. if err != nil {
  171. return nil, fmt.Errorf("%d (%s) Headers: %s Error: %s Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), err.Error(), body, query)
  172. }
  173. return toReturn, nil
  174. }