query.go 7.6 KB

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