query.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/log"
  12. "github.com/kubecost/cost-model/pkg/util"
  13. prometheus "github.com/prometheus/client_golang/api"
  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 runQuery(query, ctx, resCh, "")
  48. return resCh
  49. }
  50. // ProfileQuery returns a QueryResultsChan, then runs the given query with a profile
  51. // label and sends the results on the provided channel. Receiver is responsible for closing the
  52. // channel, preferably using the Read method.
  53. func (ctx *Context) ProfileQuery(query string, profileLabel string) QueryResultsChan {
  54. resCh := make(QueryResultsChan)
  55. go runQuery(query, ctx, resCh, profileLabel)
  56. return resCh
  57. }
  58. // QueryAll returns one QueryResultsChan for each query provided, then runs
  59. // each query concurrently and returns results on each channel, respectively,
  60. // in the order they were provided; i.e. the response to queries[1] will be
  61. // sent on channel resChs[1].
  62. func (ctx *Context) QueryAll(queries ...string) []QueryResultsChan {
  63. resChs := []QueryResultsChan{}
  64. for _, q := range queries {
  65. resChs = append(resChs, ctx.Query(q))
  66. }
  67. return resChs
  68. }
  69. // ProfileQueryAll returns one QueryResultsChan for each query provided, then runs
  70. // each ProfileQuery concurrently and returns results on each channel, respectively,
  71. // in the order they were provided; i.e. the response to queries[1] will be
  72. // sent on channel resChs[1].
  73. func (ctx *Context) ProfileQueryAll(queries ...string) []QueryResultsChan {
  74. resChs := []QueryResultsChan{}
  75. for _, q := range queries {
  76. resChs = append(resChs, ctx.ProfileQuery(q, fmt.Sprintf("Query #%d", len(resChs)+1)))
  77. }
  78. return resChs
  79. }
  80. func (ctx *Context) QuerySync(query string) ([]*QueryResult, error) {
  81. raw, err := ctx.query(query)
  82. if err != nil {
  83. return nil, err
  84. }
  85. results := NewQueryResults(query, raw)
  86. if results.Error != nil {
  87. return nil, results.Error
  88. }
  89. return results.Results, nil
  90. }
  91. // QueryURL returns the URL used to query Prometheus
  92. func (ctx *Context) QueryURL() *url.URL {
  93. return ctx.Client.URL(epQuery, nil)
  94. }
  95. // runQuery executes the prometheus query asynchronously, collects results and
  96. // errors, and passes them through the results channel.
  97. func runQuery(query string, ctx *Context, resCh QueryResultsChan, profileLabel string) {
  98. defer errors.HandlePanic()
  99. startQuery := time.Now()
  100. raw, promErr := ctx.query(query)
  101. ctx.ErrorCollector.Report(promErr)
  102. results := NewQueryResults(query, raw)
  103. if results.Error != nil {
  104. ctx.ErrorCollector.Report(results.Error)
  105. }
  106. if profileLabel != "" {
  107. log.Profile(startQuery, profileLabel)
  108. }
  109. resCh <- results
  110. }
  111. func (ctx *Context) query(query string) (interface{}, error) {
  112. u := ctx.Client.URL(epQuery, nil)
  113. q := u.Query()
  114. q.Set("query", query)
  115. u.RawQuery = q.Encode()
  116. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  117. if err != nil {
  118. return nil, err
  119. }
  120. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  121. for _, w := range warnings {
  122. log.Warningf("fetching query '%s': %s", query, w)
  123. }
  124. if err != nil {
  125. if resp == nil {
  126. return nil, fmt.Errorf("query error: '%s' fetching query '%s'", err.Error(), query)
  127. }
  128. return nil, fmt.Errorf("query error %d: '%s' fetching query '%s'", resp.StatusCode, err.Error(), query)
  129. }
  130. var toReturn interface{}
  131. err = json.Unmarshal(body, &toReturn)
  132. if err != nil {
  133. return nil, fmt.Errorf("query error: '%s' fetching query '%s'", err.Error(), query)
  134. }
  135. return toReturn, nil
  136. }
  137. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) QueryResultsChan {
  138. resCh := make(QueryResultsChan)
  139. go runQueryRange(query, start, end, step, ctx, resCh, "")
  140. return resCh
  141. }
  142. func (ctx *Context) ProfileQueryRange(query string, start, end time.Time, step time.Duration, profileLabel string) QueryResultsChan {
  143. resCh := make(QueryResultsChan)
  144. go runQueryRange(query, start, end, step, ctx, resCh, profileLabel)
  145. return resCh
  146. }
  147. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) ([]*QueryResult, error) {
  148. raw, err := ctx.queryRange(query, start, end, step)
  149. if err != nil {
  150. return nil, err
  151. }
  152. results := NewQueryResults(query, raw)
  153. if results.Error != nil {
  154. return nil, results.Error
  155. }
  156. return results.Results, nil
  157. }
  158. // QueryRangeURL returns the URL used to query_range Prometheus
  159. func (ctx *Context) QueryRangeURL() *url.URL {
  160. return ctx.Client.URL(epQueryRange, nil)
  161. }
  162. // runQueryRange executes the prometheus queryRange asynchronously, collects results and
  163. // errors, and passes them through the results channel.
  164. func runQueryRange(query string, start, end time.Time, step time.Duration, ctx *Context, resCh QueryResultsChan, profileLabel string) {
  165. defer errors.HandlePanic()
  166. startQuery := time.Now()
  167. raw, promErr := ctx.queryRange(query, start, end, step)
  168. ctx.ErrorCollector.Report(promErr)
  169. results := NewQueryResults(query, raw)
  170. if results.Error != nil {
  171. ctx.ErrorCollector.Report(results.Error)
  172. }
  173. if profileLabel != "" {
  174. log.Profile(startQuery, profileLabel)
  175. }
  176. resCh <- results
  177. }
  178. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, error) {
  179. u := ctx.Client.URL(epQueryRange, nil)
  180. q := u.Query()
  181. q.Set("query", query)
  182. q.Set("start", start.Format(time.RFC3339Nano))
  183. q.Set("end", end.Format(time.RFC3339Nano))
  184. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  185. u.RawQuery = q.Encode()
  186. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  187. if err != nil {
  188. return nil, err
  189. }
  190. resp, body, warnings, err := ctx.Client.Do(context.Background(), req)
  191. for _, w := range warnings {
  192. log.Warningf("fetching query '%s': %s", query, w)
  193. }
  194. if err != nil {
  195. if resp == nil {
  196. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  197. }
  198. 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)
  199. }
  200. // Unsuccessful Status Code, log body and status
  201. statusCode := resp.StatusCode
  202. statusText := http.StatusText(statusCode)
  203. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  204. return nil, fmt.Errorf("%d (%s) Headers: %s, Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), body, query)
  205. }
  206. var toReturn interface{}
  207. err = json.Unmarshal(body, &toReturn)
  208. if err != nil {
  209. return nil, fmt.Errorf("%d (%s) Headers: %s Error: %s Body: %s Query: %s", statusCode, statusText, util.HeaderString(resp.Header), err.Error(), body, query)
  210. }
  211. return toReturn, nil
  212. }