query.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 {
  147. q.Set("time", time.Now().UTC().Add(-promQueryOffset).Format(time.RFC3339))
  148. }
  149. u.RawQuery = q.Encode()
  150. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  151. if err != nil {
  152. return nil, err
  153. }
  154. // Set QueryContext name if non empty
  155. if ctx.name != "" {
  156. req = httputil.SetName(req, ctx.name)
  157. }
  158. req = httputil.SetQuery(req, query)
  159. // Note that the warnings return value from client.Do() is always nil using this
  160. // version of the prometheus client library. We parse the warnings out of the response
  161. // body after json decodidng completes.
  162. resp, body, _, err := ctx.Client.Do(context.Background(), req)
  163. if err != nil {
  164. if resp == nil {
  165. return nil, fmt.Errorf("query error: '%s' fetching query '%s'", err.Error(), query)
  166. }
  167. return nil, fmt.Errorf("query error %d: '%s' fetching query '%s'", resp.StatusCode, err.Error(), query)
  168. }
  169. // Unsuccessful Status Code, log body and status
  170. statusCode := resp.StatusCode
  171. statusText := http.StatusText(statusCode)
  172. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  173. 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)
  174. }
  175. return body, err
  176. }
  177. func (ctx *Context) query(query string) (interface{}, prometheus.Warnings, error) {
  178. body, err := ctx.RawQuery(query)
  179. if err != nil {
  180. return nil, nil, err
  181. }
  182. var toReturn interface{}
  183. err = json.Unmarshal(body, &toReturn)
  184. if err != nil {
  185. return nil, nil, fmt.Errorf("Unmarshal Error: %s\nQuery: %s", err, query)
  186. }
  187. warnings := warningsFrom(toReturn)
  188. for _, w := range warnings {
  189. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  190. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  191. // this warning and convert it to an error.
  192. if IsNoStoreAPIWarning(w) {
  193. return nil, warnings, CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  194. }
  195. log.Warningf("fetching query '%s': %s", query, w)
  196. }
  197. return toReturn, warnings, nil
  198. }
  199. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) QueryResultsChan {
  200. resCh := make(QueryResultsChan)
  201. go runQueryRange(query, start, end, step, ctx, resCh, "")
  202. return resCh
  203. }
  204. func (ctx *Context) ProfileQueryRange(query string, start, end time.Time, step time.Duration, profileLabel string) QueryResultsChan {
  205. resCh := make(QueryResultsChan)
  206. go runQueryRange(query, start, end, step, ctx, resCh, profileLabel)
  207. return resCh
  208. }
  209. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) ([]*QueryResult, prometheus.Warnings, error) {
  210. raw, warnings, err := ctx.queryRange(query, start, end, step)
  211. if err != nil {
  212. return nil, warnings, err
  213. }
  214. results := NewQueryResults(query, raw)
  215. if results.Error != nil {
  216. return nil, warnings, results.Error
  217. }
  218. return results.Results, warnings, nil
  219. }
  220. // QueryRangeURL returns the URL used to query_range Prometheus
  221. func (ctx *Context) QueryRangeURL() *url.URL {
  222. return ctx.Client.URL(epQueryRange, nil)
  223. }
  224. // runQueryRange executes the prometheus queryRange asynchronously, collects results and
  225. // errors, and passes them through the results channel.
  226. func runQueryRange(query string, start, end time.Time, step time.Duration, ctx *Context, resCh QueryResultsChan, profileLabel string) {
  227. defer errors.HandlePanic()
  228. startQuery := time.Now()
  229. raw, warnings, requestError := ctx.queryRange(query, start, end, step)
  230. results := NewQueryResults(query, raw)
  231. // report all warnings, request, and parse errors (nils will be ignored)
  232. ctx.errorCollector.Report(query, warnings, requestError, results.Error)
  233. if profileLabel != "" {
  234. log.Profile(startQuery, profileLabel)
  235. }
  236. resCh <- results
  237. }
  238. // RawQuery is a direct query to the prometheus client and returns the body of the response
  239. func (ctx *Context) RawQueryRange(query string, start, end time.Time, step time.Duration) ([]byte, error) {
  240. u := ctx.Client.URL(epQueryRange, nil)
  241. q := u.Query()
  242. q.Set("query", query)
  243. q.Set("start", start.Format(time.RFC3339Nano))
  244. q.Set("end", end.Format(time.RFC3339Nano))
  245. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  246. u.RawQuery = q.Encode()
  247. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  248. if err != nil {
  249. return nil, err
  250. }
  251. // Set QueryContext name if non empty
  252. if ctx.name != "" {
  253. req = httputil.SetName(req, ctx.name)
  254. }
  255. req = httputil.SetQuery(req, query)
  256. // Note that the warnings return value from client.Do() is always nil using this
  257. // version of the prometheus client library. We parse the warnings out of the response
  258. // body after json decodidng completes.
  259. resp, body, _, err := ctx.Client.Do(context.Background(), req)
  260. if err != nil {
  261. if resp == nil {
  262. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  263. }
  264. 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)
  265. }
  266. // Unsuccessful Status Code, log body and status
  267. statusCode := resp.StatusCode
  268. statusText := http.StatusText(statusCode)
  269. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  270. return nil, CommErrorf("%d (%s) Headers: %s, Body: %s Query: %s", statusCode, statusText, httputil.HeaderString(resp.Header), body, query)
  271. }
  272. return body, err
  273. }
  274. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, prometheus.Warnings, error) {
  275. body, err := ctx.RawQueryRange(query, start, end, step)
  276. if err != nil {
  277. return nil, nil, err
  278. }
  279. var toReturn interface{}
  280. err = json.Unmarshal(body, &toReturn)
  281. if err != nil {
  282. return nil, nil, fmt.Errorf("Unmarshal Error: %s\nQuery: %s", err, query)
  283. }
  284. warnings := warningsFrom(toReturn)
  285. for _, w := range warnings {
  286. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  287. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  288. // this warning and convert it to an error.
  289. if IsNoStoreAPIWarning(w) {
  290. return nil, warnings, CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  291. }
  292. log.Warningf("fetching query '%s': %s", query, w)
  293. }
  294. return toReturn, warnings, nil
  295. }
  296. // Extracts the warnings from the resulting json if they exist (part of the prometheus response api).
  297. func warningsFrom(result interface{}) prometheus.Warnings {
  298. var warnings prometheus.Warnings
  299. if resultMap, ok := result.(map[string]interface{}); ok {
  300. if warningProp, ok := resultMap["warnings"]; ok {
  301. if w, ok := warningProp.([]string); ok {
  302. warnings = w
  303. }
  304. }
  305. }
  306. return warnings
  307. }