query.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strconv"
  8. "time"
  9. "github.com/opencost/opencost/core/pkg/log"
  10. "github.com/opencost/opencost/core/pkg/source"
  11. "github.com/opencost/opencost/core/pkg/util/httputil"
  12. "github.com/opencost/opencost/core/pkg/util/json"
  13. "github.com/opencost/opencost/pkg/errors"
  14. prometheus "github.com/prometheus/client_golang/api"
  15. v1 "github.com/prometheus/client_golang/api/prometheus/v1"
  16. )
  17. const (
  18. epQuery = apiPrefix + "/query"
  19. epQueryRange = apiPrefix + "/query_range"
  20. )
  21. // ContextFactory is a factory for creating new Contexts for prometheus queries.
  22. type ContextFactory struct {
  23. client prometheus.Client
  24. config *OpenCostPrometheusConfig
  25. }
  26. // NewContextFactory creates a new ContextFactory with the provided prometheus client.
  27. func NewContextFactory(client prometheus.Client, promConfig *OpenCostPrometheusConfig) *ContextFactory {
  28. return &ContextFactory{
  29. client: client,
  30. }
  31. }
  32. // NewContext creates a new prometheus query context.
  33. func (cf *ContextFactory) NewContext() *Context {
  34. return NewContext(cf.client, cf.config)
  35. }
  36. // NewContext creates a new named prometheus query context.
  37. func (cf *ContextFactory) NewNamedContext(name string) *Context {
  38. return NewNamedContext(cf.client, cf.config, name)
  39. }
  40. // Context wraps a Prometheus client and provides methods for querying and
  41. // parsing query responses and errors.
  42. type Context struct {
  43. Client prometheus.Client
  44. config *OpenCostPrometheusConfig
  45. name string
  46. errorCollector *source.QueryErrorCollector
  47. }
  48. // NewContext creates a new Prometheus querying context from the given client
  49. func NewContext(client prometheus.Client, config *OpenCostPrometheusConfig) *Context {
  50. var ec source.QueryErrorCollector
  51. return &Context{
  52. Client: client,
  53. config: config,
  54. name: "",
  55. errorCollector: &ec,
  56. }
  57. }
  58. // NewNamedContext creates a new named Prometheus querying context from the given client
  59. func NewNamedContext(client prometheus.Client, config *OpenCostPrometheusConfig, name string) *Context {
  60. ctx := NewContext(client, config)
  61. ctx.name = name
  62. return ctx
  63. }
  64. // Warnings returns the warnings collected from the Context's ErrorCollector
  65. func (ctx *Context) Warnings() []*source.QueryWarning {
  66. return ctx.errorCollector.Warnings()
  67. }
  68. // HasWarnings returns true if the ErrorCollector has warnings.
  69. func (ctx *Context) HasWarnings() bool {
  70. return ctx.errorCollector.IsWarning()
  71. }
  72. // Errors returns the errors collected from the Context's ErrorCollector.
  73. func (ctx *Context) Errors() []*source.QueryError {
  74. return ctx.errorCollector.Errors()
  75. }
  76. // HasErrors returns true if the ErrorCollector has errors
  77. func (ctx *Context) HasErrors() bool {
  78. return ctx.errorCollector.IsError()
  79. }
  80. // ErrorCollection returns the aggregation of errors if there exists errors. Otherwise,
  81. // nil is returned
  82. func (ctx *Context) ErrorCollection() error {
  83. if ctx.errorCollector.IsError() {
  84. // errorCollector implements the error interface
  85. return ctx.errorCollector
  86. }
  87. return nil
  88. }
  89. // Query returns a QueryResultsChan, then runs the given query and sends the
  90. // results on the provided channel. Receiver is responsible for closing the
  91. // channel, preferably using the Read method.
  92. func (ctx *Context) Query(query string) source.QueryResultsChan {
  93. resCh := make(source.QueryResultsChan)
  94. go runQuery(query, ctx, resCh, time.Now(), "")
  95. return resCh
  96. }
  97. // QueryAtTime returns a QueryResultsChan, then runs the given query at the
  98. // given time (see time parameter here: https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries)
  99. // and sends the results on the provided channel. Receiver is responsible for
  100. // closing the channel, preferably using the Read method.
  101. func (ctx *Context) QueryAtTime(query string, t time.Time) source.QueryResultsChan {
  102. resCh := make(source.QueryResultsChan)
  103. go runQuery(query, ctx, resCh, t, "")
  104. return resCh
  105. }
  106. // ProfileQuery returns a QueryResultsChan, then runs the given query with a profile
  107. // label and sends the results on the provided channel. Receiver is responsible for closing the
  108. // channel, preferably using the Read method.
  109. func (ctx *Context) ProfileQuery(query string, profileLabel string) source.QueryResultsChan {
  110. resCh := make(source.QueryResultsChan)
  111. go runQuery(query, ctx, resCh, time.Now(), profileLabel)
  112. return resCh
  113. }
  114. // QueryAll returns one QueryResultsChan for each query provided, then runs
  115. // each query concurrently and returns results on each channel, respectively,
  116. // in the order they were provided; i.e. the response to queries[1] will be
  117. // sent on channel resChs[1].
  118. func (ctx *Context) QueryAll(queries ...string) []source.QueryResultsChan {
  119. resChs := []source.QueryResultsChan{}
  120. for _, q := range queries {
  121. resChs = append(resChs, ctx.Query(q))
  122. }
  123. return resChs
  124. }
  125. // ProfileQueryAll returns one QueryResultsChan for each query provided, then runs
  126. // each ProfileQuery concurrently and returns results on each channel, respectively,
  127. // in the order they were provided; i.e. the response to queries[1] will be
  128. // sent on channel resChs[1].
  129. func (ctx *Context) ProfileQueryAll(queries ...string) []source.QueryResultsChan {
  130. resChs := []source.QueryResultsChan{}
  131. for _, q := range queries {
  132. resChs = append(resChs, ctx.ProfileQuery(q, fmt.Sprintf("Query #%d", len(resChs)+1)))
  133. }
  134. return resChs
  135. }
  136. func (ctx *Context) QuerySync(query string) ([]*source.QueryResult, v1.Warnings, error) {
  137. raw, warnings, err := ctx.query(query, time.Now())
  138. if err != nil {
  139. return nil, warnings, err
  140. }
  141. // create result keys from custom cluster label
  142. resultKeys := source.ClusterKeyWithDefaults(ctx.config.ClusterLabel)
  143. results := NewQueryResults(query, raw, resultKeys)
  144. if results.Error != nil {
  145. return nil, warnings, results.Error
  146. }
  147. return results.Results, warnings, nil
  148. }
  149. // QueryURL returns the URL used to query Prometheus
  150. func (ctx *Context) QueryURL() *url.URL {
  151. return ctx.Client.URL(epQuery, nil)
  152. }
  153. // runQuery executes the prometheus query asynchronously, collects results and
  154. // errors, and passes them through the results channel.
  155. func runQuery(query string, ctx *Context, resCh source.QueryResultsChan, t time.Time, profileLabel string) {
  156. defer errors.HandlePanic()
  157. startQuery := time.Now()
  158. raw, warnings, requestError := ctx.query(query, t)
  159. var parseError error
  160. var results *source.QueryResults
  161. if requestError != nil {
  162. results = NewQueryResultError(query, requestError)
  163. } else {
  164. // create result keys from custom cluster label
  165. resultKeys := source.ClusterKeyWithDefaults(ctx.config.ClusterLabel)
  166. results = NewQueryResults(query, raw, resultKeys)
  167. parseError = results.Error
  168. }
  169. // report all warnings, request, and parse errors (nils will be ignored)
  170. ctx.errorCollector.Report(query, warnings, requestError, parseError)
  171. if profileLabel != "" {
  172. log.Profile(startQuery, profileLabel)
  173. }
  174. resCh <- results
  175. }
  176. // RawQuery is a direct query to the prometheus client and returns the body of the response
  177. func (ctx *Context) RawQuery(query string, t time.Time) ([]byte, error) {
  178. u := ctx.Client.URL(epQuery, nil)
  179. q := u.Query()
  180. q.Set("query", query)
  181. if t.IsZero() {
  182. t = time.Now()
  183. }
  184. q.Set("time", strconv.FormatInt(t.Unix(), 10))
  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. // Set QueryContext name if non empty
  191. if ctx.name != "" {
  192. req = httputil.SetName(req, ctx.name)
  193. }
  194. req = httputil.SetQuery(req, query)
  195. // Note that the warnings return value from client.Do() is always nil using this
  196. // version of the prometheus client library. We parse the warnings out of the response
  197. // body after json decodidng completes.
  198. resp, body, err := ctx.Client.Do(context.Background(), req)
  199. if err != nil {
  200. if resp == nil {
  201. return nil, fmt.Errorf("query error: '%s' fetching query '%s'", err.Error(), query)
  202. }
  203. return nil, fmt.Errorf("query error %d: '%s' fetching query '%s'", resp.StatusCode, err.Error(), query)
  204. }
  205. // Unsuccessful Status Code, log body and status
  206. statusCode := resp.StatusCode
  207. statusText := http.StatusText(statusCode)
  208. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  209. return nil, source.CommErrorf("%d (%s) URL: '%s', Body: '%s' Query: '%s'", statusCode, statusText, req.URL, body, query)
  210. }
  211. return body, err
  212. }
  213. func (ctx *Context) query(query string, t time.Time) (interface{}, v1.Warnings, error) {
  214. body, err := ctx.RawQuery(query, t)
  215. if err != nil {
  216. return nil, nil, err
  217. }
  218. var toReturn interface{}
  219. err = json.Unmarshal(body, &toReturn)
  220. if err != nil {
  221. return nil, nil, fmt.Errorf("query '%s' caused unmarshal error: %s", query, err)
  222. }
  223. warnings := warningsFrom(toReturn)
  224. for _, w := range warnings {
  225. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  226. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  227. // this warning and convert it to an error.
  228. if source.IsNoStoreAPIWarning(w) {
  229. return nil, warnings, source.CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  230. }
  231. log.Warnf("fetching query '%s': %s", query, w)
  232. }
  233. return toReturn, warnings, nil
  234. }
  235. // isRequestStepAligned will check if the start and end times are aligned with the step
  236. func (ctx *Context) isRequestStepAligned(start, end time.Time, step time.Duration) bool {
  237. startInUnix := start.Unix()
  238. endInUnix := end.Unix()
  239. stepInSeconds := step.Milliseconds() / 1e3
  240. return startInUnix%stepInSeconds == 0 && endInUnix%stepInSeconds == 0
  241. }
  242. func (ctx *Context) QueryRange(query string, start, end time.Time, step time.Duration) source.QueryResultsChan {
  243. resCh := make(source.QueryResultsChan)
  244. if !ctx.isRequestStepAligned(start, end, step) {
  245. start, end = ctx.alignWindow(start, end, step)
  246. }
  247. go runQueryRange(query, start, end, step, ctx, resCh, "")
  248. return resCh
  249. }
  250. func (ctx *Context) ProfileQueryRange(query string, start, end time.Time, step time.Duration, profileLabel string) source.QueryResultsChan {
  251. resCh := make(source.QueryResultsChan)
  252. go runQueryRange(query, start, end, step, ctx, resCh, profileLabel)
  253. return resCh
  254. }
  255. func (ctx *Context) QueryRangeSync(query string, start, end time.Time, step time.Duration) ([]*source.QueryResult, v1.Warnings, error) {
  256. raw, warnings, err := ctx.queryRange(query, start, end, step)
  257. if err != nil {
  258. return nil, warnings, err
  259. }
  260. // create result keys from custom cluster label
  261. resultKeys := source.ClusterKeyWithDefaults(ctx.config.ClusterLabel)
  262. results := NewQueryResults(query, raw, resultKeys)
  263. if results.Error != nil {
  264. return nil, warnings, results.Error
  265. }
  266. return results.Results, warnings, nil
  267. }
  268. // QueryRangeURL returns the URL used to query_range Prometheus
  269. func (ctx *Context) QueryRangeURL() *url.URL {
  270. return ctx.Client.URL(epQueryRange, nil)
  271. }
  272. // runQueryRange executes the prometheus queryRange asynchronously, collects results and
  273. // errors, and passes them through the results channel.
  274. func runQueryRange(query string, start, end time.Time, step time.Duration, ctx *Context, resCh source.QueryResultsChan, profileLabel string) {
  275. defer errors.HandlePanic()
  276. startQuery := time.Now()
  277. raw, warnings, requestError := ctx.queryRange(query, start, end, step)
  278. var parseError error
  279. var results *source.QueryResults
  280. if requestError != nil {
  281. results = NewQueryResultError(query, requestError)
  282. } else {
  283. // create result keys from custom cluster label
  284. resultKeys := source.ClusterKeyWithDefaults(ctx.config.ClusterLabel)
  285. results = NewQueryResults(query, raw, resultKeys)
  286. parseError = results.Error
  287. }
  288. // report all warnings, request, and parse errors (nils will be ignored)
  289. ctx.errorCollector.Report(query, warnings, requestError, parseError)
  290. if profileLabel != "" {
  291. log.Profile(startQuery, profileLabel)
  292. }
  293. resCh <- results
  294. }
  295. // RawQuery is a direct query to the prometheus client and returns the body of the response
  296. func (ctx *Context) RawQueryRange(query string, start, end time.Time, step time.Duration) ([]byte, error) {
  297. u := ctx.Client.URL(epQueryRange, nil)
  298. q := u.Query()
  299. q.Set("query", query)
  300. q.Set("start", start.Format(time.RFC3339Nano))
  301. q.Set("end", end.Format(time.RFC3339Nano))
  302. q.Set("step", strconv.FormatFloat(step.Seconds(), 'f', 3, 64))
  303. u.RawQuery = q.Encode()
  304. req, err := http.NewRequest(http.MethodPost, u.String(), nil)
  305. if err != nil {
  306. return nil, err
  307. }
  308. // Set QueryContext name if non empty
  309. if ctx.name != "" {
  310. req = httputil.SetName(req, ctx.name)
  311. }
  312. req = httputil.SetQuery(req, query)
  313. // Note that the warnings return value from client.Do() is always nil using this
  314. // version of the prometheus client library. We parse the warnings out of the response
  315. // body after json decodidng completes.
  316. resp, body, err := ctx.Client.Do(context.Background(), req)
  317. if err != nil {
  318. if resp == nil {
  319. return nil, fmt.Errorf("Error: %s, Body: %s Query: %s", err.Error(), body, query)
  320. }
  321. return nil, fmt.Errorf("%d (%s) Error: %s Body: %s Query: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body, err.Error(), query)
  322. }
  323. // Unsuccessful Status Code, log body and status
  324. statusCode := resp.StatusCode
  325. statusText := http.StatusText(statusCode)
  326. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  327. return nil, source.CommErrorf("%d (%s) Body: %s Query: %s", statusCode, statusText, body, query)
  328. }
  329. return body, err
  330. }
  331. func (ctx *Context) queryRange(query string, start, end time.Time, step time.Duration) (interface{}, v1.Warnings, error) {
  332. body, err := ctx.RawQueryRange(query, start, end, step)
  333. if err != nil {
  334. return nil, nil, err
  335. }
  336. var toReturn interface{}
  337. err = json.Unmarshal(body, &toReturn)
  338. if err != nil {
  339. return nil, nil, fmt.Errorf("query '%s' caused unmarshal error: %s", query, err)
  340. }
  341. warnings := warningsFrom(toReturn)
  342. for _, w := range warnings {
  343. // NoStoreAPIWarning is a warning that we would consider an error. It returns partial data relating only to the
  344. // store apis which were reachable. In order to ensure integrity of data across all clusters, we'll need to identify
  345. // this warning and convert it to an error.
  346. if source.IsNoStoreAPIWarning(w) {
  347. return nil, warnings, source.CommErrorf("Error: %s, Body: %s, Query: %s", w, body, query)
  348. }
  349. log.Warnf("fetching query '%s': %s", query, w)
  350. }
  351. return toReturn, warnings, nil
  352. }
  353. // alignWindow will update the start and end times to be aligned with the step duration.
  354. // Current implementation will always floor the start/end times
  355. func (ctx *Context) alignWindow(start time.Time, end time.Time, step time.Duration) (time.Time, time.Time) {
  356. // Convert the step duration from Milliseconds to Seconds to match the Unix timestamp, which is in seconds
  357. stepInSeconds := step.Milliseconds() / 1e3
  358. alignedStart := (start.Unix() / stepInSeconds) * stepInSeconds
  359. alignedEnd := (end.Unix() / stepInSeconds) * stepInSeconds
  360. return time.Unix(alignedStart, 0).UTC(), time.Unix(alignedEnd, 0).UTC()
  361. }
  362. // Extracts the warnings from the resulting json if they exist (part of the prometheus response api).
  363. func warningsFrom(result interface{}) v1.Warnings {
  364. var warnings v1.Warnings
  365. if resultMap, ok := result.(map[string]interface{}); ok {
  366. if warningProp, ok := resultMap["warnings"]; ok {
  367. if w, ok := warningProp.([]string); ok {
  368. warnings = w
  369. }
  370. }
  371. }
  372. return warnings
  373. }