query.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. "time"
  9. "github.com/kubecost/cost-model/pkg/env"
  10. "github.com/kubecost/cost-model/pkg/errors"
  11. "github.com/kubecost/cost-model/pkg/log"
  12. "github.com/kubecost/cost-model/pkg/util/httputil"
  13. "github.com/kubecost/cost-model/pkg/util/json"
  14. prometheus "github.com/prometheus/client_golang/api"
  15. )
  16. const (
  17. apiPrefix = "/api/v1"
  18. epQuery = apiPrefix + "/query"
  19. epQueryRange = apiPrefix + "/query_range"
  20. )
  21. // prometheus query offset to apply to each non-range query
  22. // package scope to prevent calling duration parse each use
  23. var promQueryOffset time.Duration = env.GetPrometheusQueryOffset()
  24. // Context wraps a Prometheus client and provides methods for querying and
  25. // parsing query responses and errors.
  26. type Context struct {
  27. Client prometheus.Client
  28. name string
  29. errorCollector *QueryErrorCollector
  30. }
  31. // NewContext creates a new Promethues querying context from the given client
  32. func NewContext(client prometheus.Client) *Context {
  33. var ec QueryErrorCollector
  34. return &Context{
  35. Client: client,
  36. name: "",
  37. errorCollector: &ec,
  38. }
  39. }
  40. // NewNamedContext creates a new named Promethues querying context from the given client
  41. func NewNamedContext(client prometheus.Client, name string) *Context {
  42. ctx := NewContext(client)
  43. ctx.name = name
  44. return ctx
  45. }
  46. // Warnings returns the warnings collected from the Context's ErrorCollector
  47. func (ctx *Context) Warnings() []*QueryWarning {
  48. return ctx.errorCollector.Warnings()
  49. }
  50. // HasWarnings returns true if the ErrorCollector has warnings.
  51. func (ctx *Context) HasWarnings() bool {
  52. return ctx.errorCollector.IsWarning()
  53. }
  54. // Errors returns the errors collected from the Context's ErrorCollector.
  55. func (ctx *Context) Errors() []*QueryError {
  56. return ctx.errorCollector.Errors()
  57. }
  58. // HasErrors returns true if the ErrorCollector has errors
  59. func (ctx *Context) HasErrors() bool {
  60. return ctx.errorCollector.IsError()
  61. }
  62. // ErrorCollection returns the aggregation of errors if there exists errors. Otherwise,
  63. // nil is returned
  64. func (ctx *Context) ErrorCollection() error {
  65. if ctx.errorCollector.IsError() {
  66. // errorCollector implements the error interface
  67. return ctx.errorCollector
  68. }
  69. return nil
  70. }
  71. // Query returns a QueryResultsChan, then runs the given query and sends the
  72. // results on the provided channel. Receiver is responsible for closing the
  73. // channel, preferably using the Read method.
  74. func (ctx *Context) Query(query string) QueryResultsChan {
  75. resCh := make(QueryResultsChan)
  76. go runQuery(query, ctx, resCh, "")
  77. return resCh
  78. }
  79. // ProfileQuery returns a QueryResultsChan, then runs the given query with a profile
  80. // label and sends the results on the provided channel. Receiver is responsible for closing the
  81. // channel, preferably using the Read method.
  82. func (ctx *Context) ProfileQuery(query string, profileLabel string) QueryResultsChan {
  83. resCh := make(QueryResultsChan)
  84. go runQuery(query, ctx, resCh, profileLabel)
  85. return resCh
  86. }
  87. // QueryAll returns one QueryResultsChan for each query provided, then runs
  88. // each query concurrently and returns results on each channel, respectively,
  89. // in the order they were provided; i.e. the response to queries[1] will be
  90. // sent on channel resChs[1].
  91. func (ctx *Context) QueryAll(queries ...string) []QueryResultsChan {
  92. resChs := []QueryResultsChan{}
  93. for _, q := range queries {
  94. resChs = append(resChs, ctx.Query(q))
  95. }
  96. return resChs
  97. }
  98. // ProfileQueryAll returns one QueryResultsChan for each query provided, then runs
  99. // each ProfileQuery concurrently and returns results on each channel, respectively,
  100. // in the order they were provided; i.e. the response to queries[1] will be
  101. // sent on channel resChs[1].
  102. func (ctx *Context) ProfileQueryAll(queries ...string) []QueryResultsChan {
  103. resChs := []QueryResultsChan{}
  104. for _, q := range queries {
  105. resChs = append(resChs, ctx.ProfileQuery(q, fmt.Sprintf("Query #%d", len(resChs)+1)))
  106. }
  107. return resChs
  108. }
  109. func (ctx *Context) QuerySync(query string) ([]*QueryResult, prometheus.Warnings, error) {
  110. raw, warnings, err := ctx.query(query)
  111. if err != nil {
  112. return nil, warnings, err
  113. }
  114. results := NewQueryResults(query, raw)
  115. if results.Error != nil {
  116. return nil, warnings, results.Error
  117. }
  118. return results.Results, warnings, nil
  119. }
  120. // QueryURL returns the URL used to query Prometheus
  121. func (ctx *Context) QueryURL() *url.URL {
  122. return ctx.Client.URL(epQuery, nil)
  123. }
  124. // runQuery executes the prometheus query asynchronously, collects results and
  125. // errors, and passes them through the results channel.
  126. func runQuery(query string, ctx *Context, resCh QueryResultsChan, profileLabel string) {
  127. defer errors.HandlePanic()
  128. startQuery := time.Now()
  129. raw, warnings, requestError := ctx.query(query)
  130. results := NewQueryResults(query, raw)
  131. // report all warnings, request, and parse errors (nils will be ignored)
  132. ctx.errorCollector.Report(query, warnings, requestError, results.Error)
  133. if profileLabel != "" {
  134. log.Profile(startQuery, profileLabel)
  135. }
  136. resCh <- results
  137. }
  138. // RawQuery is a direct query to the prometheus client and returns the body of the response
  139. func (ctx *Context) RawQuery(query string) ([]byte, error) {
  140. u := ctx.Client.URL(epQuery, nil)
  141. q := u.Query()
  142. q.Set("query", query)
  143. // for non-range queries, we set the timestamp for the query to time-offset
  144. // this is a special use case that's typically only used when our primary
  145. // prom db has delayed insertion (thanos, cortex, etc...)
  146. if promQueryOffset != 0 && ctx.name != AllocationContextName {
  147. q.Set("time", time.Now().Add(-promQueryOffset).UTC().Format(time.RFC3339))
  148. } else {
  149. q.Set("time", time.Now().UTC().Format(time.RFC3339))
  150. }
  151. u.RawQuery = q.Encode()
  152. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  153. if err != nil {
  154. return nil, err
  155. }
  156. // Set QueryContext name if non empty
  157. if ctx.name != "" {
  158. req = httputil.SetName(req, ctx.name)
  159. }
  160. req = httputil.SetQuery(req, query)
  161. // Note that the warnings return value from client.Do() is always nil using this
  162. // version of the prometheus client library. We parse the warnings out of the response
  163. // body after json decodidng completes.
  164. resp, body, _, err := ctx.Client.Do(context.Background(), req)
  165. if err != nil {
  166. if resp == nil {
  167. return nil, fmt.Errorf("query error: '%s' fetching query '%s'", err.Error(), query)
  168. }
  169. return nil, fmt.Errorf("query error %d: '%s' fetching query '%s'", resp.StatusCode, err.Error(), query)
  170. }
  171. // Unsuccessful Status Code, log body and status
  172. statusCode := resp.StatusCode
  173. statusText := http.StatusText(statusCode)
  174. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  175. return nil, CommErrorf("%d (%s) URL: '%s', Request Headers: '%s', Headers: '%s', Body: '%s' Query: '%s'", statusCode, statusText, req.URL, req.Header, httputil.HeaderString(resp.Header), body, query)
  176. }
  177. return body, err
  178. }
  179. func (ctx *Context) query(query string) (interface{}, prometheus.Warnings, error) {
  180. body, err := ctx.RawQuery(query)
  181. if err != nil {
  182. return nil, nil, err
  183. }
  184. var toReturn interface{}
  185. err = json.Unmarshal(body, &toReturn)
  186. if err != nil {
  187. return nil, nil, fmt.Errorf("Unmarshal Error: %s\nQuery: %s", err, query)
  188. }
  189. warnings := warningsFrom(toReturn)
  190. for _, w := range warnings {
  191. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  192. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  193. // this warning and convert it to an error.
  194. if IsNoStoreAPIWarning(w) {
  195. return nil, warnings, CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  196. }
  197. log.Warningf("fetching query '%s': %s", query, w)
  198. }
  199. return toReturn, warnings, nil
  200. }
  201. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) QueryResultsChan {
  202. resCh := make(QueryResultsChan)
  203. go runQueryRange(query, start, end, step, ctx, resCh, "")
  204. return resCh
  205. }
  206. func (ctx *Context) ProfileQueryRange(query string, start, end time.Time, step time.Duration, profileLabel string) QueryResultsChan {
  207. resCh := make(QueryResultsChan)
  208. go runQueryRange(query, start, end, step, ctx, resCh, profileLabel)
  209. return resCh
  210. }
  211. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) ([]*QueryResult, prometheus.Warnings, error) {
  212. raw, warnings, err := ctx.queryRange(query, start, end, step)
  213. if err != nil {
  214. return nil, warnings, err
  215. }
  216. results := NewQueryResults(query, raw)
  217. if results.Error != nil {
  218. return nil, warnings, results.Error
  219. }
  220. return results.Results, warnings, nil
  221. }
  222. // QueryRangeURL returns the URL used to query_range Prometheus
  223. func (ctx *Context) QueryRangeURL() *url.URL {
  224. return ctx.Client.URL(epQueryRange, nil)
  225. }
  226. // runQueryRange executes the prometheus queryRange asynchronously, collects results and
  227. // errors, and passes them through the results channel.
  228. func runQueryRange(query string, start, end time.Time, step time.Duration, ctx *Context, resCh QueryResultsChan, profileLabel string) {
  229. defer errors.HandlePanic()
  230. startQuery := time.Now()
  231. raw, warnings, requestError := ctx.queryRange(query, start, end, step)
  232. results := NewQueryResults(query, raw)
  233. // report all warnings, request, and parse errors (nils will be ignored)
  234. ctx.errorCollector.Report(query, warnings, requestError, results.Error)
  235. if profileLabel != "" {
  236. log.Profile(startQuery, profileLabel)
  237. }
  238. resCh <- results
  239. }
  240. // RawQuery is a direct query to the prometheus client and returns the body of the response
  241. func (ctx *Context) RawQueryRange(query string, start, end time.Time, step time.Duration) ([]byte, error) {
  242. u := ctx.Client.URL(epQueryRange, nil)
  243. q := u.Query()
  244. q.Set("query", query)
  245. q.Set("start", start.Format(time.RFC3339Nano))
  246. q.Set("end", end.Format(time.RFC3339Nano))
  247. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  248. u.RawQuery = q.Encode()
  249. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  250. if err != nil {
  251. return nil, err
  252. }
  253. // Set QueryContext name if non empty
  254. if ctx.name != "" {
  255. req = httputil.SetName(req, ctx.name)
  256. }
  257. req = httputil.SetQuery(req, query)
  258. // Note that the warnings return value from client.Do() is always nil using this
  259. // version of the prometheus client library. We parse the warnings out of the response
  260. // body after json decodidng completes.
  261. resp, body, _, err := ctx.Client.Do(context.Background(), req)
  262. if err != nil {
  263. if resp == nil {
  264. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  265. }
  266. return nil, fmt.Errorf("%d (%s) Headers: %s Error: %s Body: %s Query: %s", resp.StatusCode, http.StatusText(resp.StatusCode), httputil.HeaderString(resp.Header), body, err.Error(), query)
  267. }
  268. // Unsuccessful Status Code, log body and status
  269. statusCode := resp.StatusCode
  270. statusText := http.StatusText(statusCode)
  271. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  272. return nil, CommErrorf("%d (%s) Headers: %s, Body: %s Query: %s", statusCode, statusText, httputil.HeaderString(resp.Header), body, query)
  273. }
  274. return body, err
  275. }
  276. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, prometheus.Warnings, error) {
  277. body, err := ctx.RawQueryRange(query, start, end, step)
  278. if err != nil {
  279. return nil, nil, err
  280. }
  281. var toReturn interface{}
  282. err = json.Unmarshal(body, &toReturn)
  283. if err != nil {
  284. return nil, nil, fmt.Errorf("Unmarshal Error: %s\nQuery: %s", err, query)
  285. }
  286. warnings := warningsFrom(toReturn)
  287. for _, w := range warnings {
  288. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  289. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  290. // this warning and convert it to an error.
  291. if IsNoStoreAPIWarning(w) {
  292. return nil, warnings, CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  293. }
  294. log.Warningf("fetching query '%s': %s", query, w)
  295. }
  296. return toReturn, warnings, nil
  297. }
  298. // Extracts the warnings from the resulting json if they exist (part of the prometheus response api).
  299. func warningsFrom(result interface{}) prometheus.Warnings {
  300. var warnings prometheus.Warnings
  301. if resultMap, ok := result.(map[string]interface{}); ok {
  302. if warningProp, ok := resultMap["warnings"]; ok {
  303. if w, ok := warningProp.([]string); ok {
  304. warnings = w
  305. }
  306. }
  307. }
  308. return warnings
  309. }