query.go 8.6 KB

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