datasource.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/julienschmidt/httprouter"
  9. "github.com/opencost/opencost/modules/prometheus-source/pkg/env"
  10. "github.com/opencost/opencost/core/pkg/clusters"
  11. "github.com/opencost/opencost/core/pkg/log"
  12. "github.com/opencost/opencost/core/pkg/protocol"
  13. "github.com/opencost/opencost/core/pkg/source"
  14. "github.com/opencost/opencost/core/pkg/util/httputil"
  15. "github.com/opencost/opencost/core/pkg/util/json"
  16. "github.com/opencost/opencost/core/pkg/util/timeutil"
  17. prometheus "github.com/prometheus/client_golang/api"
  18. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  19. )
  20. const (
  21. apiPrefix = "/api/v1"
  22. epAlertManagers = apiPrefix + "/alertmanagers"
  23. epLabelValues = apiPrefix + "/label/:name/values"
  24. epSeries = apiPrefix + "/series"
  25. epTargets = apiPrefix + "/targets"
  26. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  27. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  28. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  29. epConfig = apiPrefix + "/status/config"
  30. epFlags = apiPrefix + "/status/flags"
  31. epRules = apiPrefix + "/rules"
  32. )
  33. // helper for query range proxy requests
  34. func toStartEndStep(qp httputil.QueryParams) (start, end time.Time, step time.Duration, err error) {
  35. var e error
  36. ss := qp.Get("start", "")
  37. es := qp.Get("end", "")
  38. ds := qp.Get("duration", "")
  39. layout := "2006-01-02T15:04:05.000Z"
  40. start, e = time.Parse(layout, ss)
  41. if e != nil {
  42. err = fmt.Errorf("Error parsing time %s. Error: %s", ss, err)
  43. return
  44. }
  45. end, e = time.Parse(layout, es)
  46. if e != nil {
  47. err = fmt.Errorf("Error parsing time %s. Error: %s", es, err)
  48. return
  49. }
  50. step, e = time.ParseDuration(ds)
  51. if e != nil {
  52. err = fmt.Errorf("Error parsing duration %s. Error: %s", ds, err)
  53. return
  54. }
  55. err = nil
  56. return
  57. }
  58. // FIXME: Before merge, implement a more robust design. This is brittle and bug-prone,
  59. // FIXME: but decouples the prom requirements from the Provider implementations.
  60. var providerStorageQueries = map[string]func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string{
  61. "aws": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  62. return ""
  63. },
  64. "gcp": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  65. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  66. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  67. localStorageCost := 0.04
  68. baseMetric := "container_fs_limit_bytes"
  69. if used {
  70. baseMetric = "container_fs_usage_bytes"
  71. }
  72. fmtCumulativeQuery := `sum(
  73. sum_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m])
  74. ) by (%s) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  75. fmtMonthlyQuery := `sum(
  76. avg_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m])
  77. ) by (%s) / 1024 / 1024 / 1024 * %f`
  78. fmtQuery := fmtCumulativeQuery
  79. if rate {
  80. fmtQuery = fmtMonthlyQuery
  81. }
  82. fmtWindow := timeutil.DurationString(end.Sub(start))
  83. return fmt.Sprintf(fmtQuery, baseMetric, config.ClusterFilter, fmtWindow, config.ClusterLabel, localStorageCost)
  84. },
  85. "azure": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  86. return ""
  87. },
  88. "alibaba": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  89. return ""
  90. },
  91. "scaleway": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  92. return ""
  93. },
  94. "otc": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  95. return ""
  96. },
  97. "oracle": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  98. return ""
  99. },
  100. "csv": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  101. return ""
  102. },
  103. "custom": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  104. return ""
  105. },
  106. }
  107. // creates a new help error which indicates the caller can retry and is non-fatal.
  108. func newHelpRetryError(format string, args ...any) error {
  109. formatWithHelp := format + "\nTroubleshooting help available at: %s"
  110. args = append(args, PrometheusTroubleshootingURL)
  111. cause := fmt.Errorf(formatWithHelp, args...)
  112. return source.NewHelpRetryError(cause)
  113. }
  114. // PrometheusDataSource is the OpenCost data source implementation leveraging Prometheus. Prometheus provides longer retention periods and
  115. // more detailed metrics than the OpenCost Collector, which is useful for historical analysis and cost forecasting.
  116. type PrometheusDataSource struct {
  117. promConfig *OpenCostPrometheusConfig
  118. promClient prometheus.Client
  119. promContexts *ContextFactory
  120. thanosConfig *OpenCostThanosConfig
  121. thanosClient prometheus.Client
  122. thanosContexts *ContextFactory
  123. metricsQuerier *PrometheusMetricsQuerier
  124. clusterMap clusters.ClusterMap
  125. }
  126. // NewDefaultPrometheusDataSource creates and initializes a new `PrometheusDataSource` with configuration
  127. // parsed from environment variables. This function will block until a connection to prometheus is established,
  128. // or fails. It is recommended to run this function in a goroutine on a retry cycle.
  129. func NewDefaultPrometheusDataSource(clusterInfoProvider clusters.ClusterInfoProvider) (*PrometheusDataSource, error) {
  130. config, err := NewOpenCostPrometheusConfigFromEnv()
  131. if err != nil {
  132. return nil, fmt.Errorf("failed to create prometheus config from env: %w", err)
  133. }
  134. var thanosConfig *OpenCostThanosConfig
  135. if env.IsThanosEnabled() {
  136. // thanos initialization is not fatal, so we log the error and continue
  137. thanosConfig, err = NewOpenCostThanosConfigFromEnv()
  138. if err != nil {
  139. log.Warnf("Thanos was enabled, but failed to create thanos config from env: %s. Continuing...", err.Error())
  140. }
  141. }
  142. return NewPrometheusDataSource(clusterInfoProvider, config, thanosConfig)
  143. }
  144. // NewPrometheusDataSource initializes clients for Prometheus and Thanos, and returns a new PrometheusDataSource.
  145. func NewPrometheusDataSource(infoProvider clusters.ClusterInfoProvider, promConfig *OpenCostPrometheusConfig, thanosConfig *OpenCostThanosConfig) (*PrometheusDataSource, error) {
  146. promClient, err := NewPrometheusClient(promConfig.ServerEndpoint, promConfig.ClientConfig)
  147. if err != nil {
  148. return nil, fmt.Errorf("failed to build prometheus client: %w", err)
  149. }
  150. // validation of the prometheus client
  151. m, err := Validate(promClient, promConfig)
  152. if err != nil || !m.Running {
  153. if err != nil {
  154. return nil, newHelpRetryError("failed to query prometheus at %s: %w", promConfig.ServerEndpoint, err)
  155. } else if !m.Running {
  156. return nil, newHelpRetryError("prometheus at %s is not running", promConfig.ServerEndpoint)
  157. }
  158. } else {
  159. log.Infof("Success: retrieved the 'up' query against prometheus at: %s", promConfig.ServerEndpoint)
  160. }
  161. // we don't consider this a fatal error, but we log for visibility
  162. api := prometheusAPI.NewAPI(promClient)
  163. _, err = api.Buildinfo(context.Background())
  164. if err != nil {
  165. log.Infof("No valid prometheus config file at %s. Error: %s.\nTroubleshooting help available at: %s.\n**Ignore if using cortex/mimir/thanos here**", promConfig.ServerEndpoint, err.Error(), PrometheusTroubleshootingURL)
  166. } else {
  167. log.Infof("Retrieved a prometheus config file from: %s", promConfig.ServerEndpoint)
  168. }
  169. // Fix scrape interval if zero by attempting to lookup the interval for the configured job
  170. if promConfig.ScrapeInterval == 0 {
  171. promConfig.ScrapeInterval = time.Minute
  172. // Lookup scrape interval for kubecost job, update if found
  173. si, err := ScrapeIntervalFor(promClient, promConfig.JobName)
  174. if err == nil {
  175. promConfig.ScrapeInterval = si
  176. }
  177. }
  178. log.Infof("Using scrape interval of %f", promConfig.ScrapeInterval.Seconds())
  179. promContexts := NewContextFactory(promClient, promConfig)
  180. var thanosClient prometheus.Client
  181. var thanosContexts *ContextFactory
  182. // if the thanos configuration is non-nil, we assume intent to use thanos. However, failure to
  183. // initialize the thanos client is not fatal, and we will log the error and continue.
  184. if thanosConfig != nil {
  185. thanosHost := thanosConfig.ServerEndpoint
  186. if thanosHost != "" {
  187. thanosCli, _ := NewThanosClient(thanosHost, thanosConfig)
  188. _, err = Validate(thanosCli, thanosConfig.OpenCostPrometheusConfig)
  189. if err != nil {
  190. log.Warnf("Failed to query Thanos at %s. Error: %s.", thanosHost, err.Error())
  191. thanosClient = thanosCli
  192. } else {
  193. log.Infof("Success: retrieved the 'up' query against Thanos at: %s", thanosHost)
  194. thanosClient = thanosCli
  195. }
  196. thanosContexts = NewContextFactory(thanosClient, thanosConfig.OpenCostPrometheusConfig)
  197. } else {
  198. log.Infof("Error resolving environment variable: $%s", env.ThanosQueryUrlEnvVar)
  199. }
  200. }
  201. // metadata creation for cluster info
  202. thanosEnabled := thanosClient != nil
  203. metadata := map[string]string{
  204. clusters.ClusterInfoThanosEnabledKey: fmt.Sprintf("%t", thanosEnabled),
  205. }
  206. if thanosEnabled {
  207. metadata[clusters.ClusterInfoThanosOffsetKey] = thanosConfig.Offset
  208. }
  209. // cluster info provider
  210. clusterInfoProvider := clusters.NewClusterInfoDecorator(infoProvider, metadata)
  211. var clusterMap clusters.ClusterMap
  212. if thanosEnabled {
  213. clusterMap = newPrometheusClusterMap(thanosContexts, clusterInfoProvider, 10*time.Minute)
  214. } else {
  215. clusterMap = newPrometheusClusterMap(promContexts, clusterInfoProvider, 5*time.Minute)
  216. }
  217. // create metrics querier implementation for prometheus and thanos
  218. metricsQuerier := newPrometheusMetricsQuerier(
  219. promConfig,
  220. promClient,
  221. promContexts,
  222. thanosConfig,
  223. thanosClient,
  224. thanosContexts,
  225. )
  226. return &PrometheusDataSource{
  227. promConfig: promConfig,
  228. promClient: promClient,
  229. promContexts: promContexts,
  230. thanosConfig: thanosConfig,
  231. thanosClient: thanosClient,
  232. thanosContexts: thanosContexts,
  233. metricsQuerier: metricsQuerier,
  234. clusterMap: clusterMap,
  235. }, nil
  236. }
  237. var proto = protocol.HTTP()
  238. // prometheusMetadata returns the metadata for the prometheus server
  239. func (pds *PrometheusDataSource) prometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  240. w.Header().Set("Content-Type", "application/json")
  241. w.Header().Set("Access-Control-Allow-Origin", "*")
  242. resp := proto.ToResponse(Validate(pds.promClient, pds.promConfig))
  243. proto.WriteResponse(w, resp)
  244. }
  245. // prometheusRecordingRules is a proxy for /rules against prometheus
  246. func (pds *PrometheusDataSource) prometheusRecordingRules(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  247. w.Header().Set("Content-Type", "application/json")
  248. w.Header().Set("Access-Control-Allow-Origin", "*")
  249. u := pds.promClient.URL(epRules, nil)
  250. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  251. if err != nil {
  252. fmt.Fprintf(w, "error creating Prometheus rule request: %s", err)
  253. return
  254. }
  255. _, body, err := pds.promClient.Do(r.Context(), req)
  256. if err != nil {
  257. fmt.Fprintf(w, "error making Prometheus rule request: %s", err)
  258. return
  259. }
  260. w.Write(body)
  261. }
  262. // prometheusConfig returns the current configuration of the prometheus server
  263. func (pds *PrometheusDataSource) prometheusConfig(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  264. w.Header().Set("Content-Type", "application/json")
  265. w.Header().Set("Access-Control-Allow-Origin", "*")
  266. pConfig := map[string]string{
  267. "address": pds.promConfig.ServerEndpoint,
  268. }
  269. body, err := json.Marshal(pConfig)
  270. if err != nil {
  271. fmt.Fprintf(w, "Error marshalling prometheus config")
  272. } else {
  273. w.Write(body)
  274. }
  275. }
  276. // prometheusTargets is a proxy for /targets against prometheus
  277. func (pds *PrometheusDataSource) prometheusTargets(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  278. w.Header().Set("Content-Type", "application/json")
  279. w.Header().Set("Access-Control-Allow-Origin", "*")
  280. u := pds.promClient.URL(epTargets, nil)
  281. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  282. if err != nil {
  283. fmt.Fprintf(w, "error creating Prometheus rule request: %s", err)
  284. return
  285. }
  286. _, body, err := pds.promClient.Do(r.Context(), req)
  287. if err != nil {
  288. fmt.Fprintf(w, "error making Prometheus rule request: %s", err)
  289. return
  290. }
  291. w.Write(body)
  292. }
  293. // status returns the status of the prometheus client
  294. func (pds *PrometheusDataSource) status(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  295. w.Header().Set("Content-Type", "application/json")
  296. w.Header().Set("Access-Control-Allow-Origin", "*")
  297. promServer := pds.promConfig.ServerEndpoint
  298. api := prometheusAPI.NewAPI(pds.promClient)
  299. result, err := api.Buildinfo(r.Context())
  300. if err != nil {
  301. fmt.Fprintf(w, "Using Prometheus at %s, Error: %s", promServer, err)
  302. } else {
  303. fmt.Fprintf(w, "Using Prometheus at %s, version: %s", promServer, result.Version)
  304. }
  305. }
  306. // prometheusQuery is a proxy for /query against prometheus
  307. func (pds *PrometheusDataSource) prometheusQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  308. w.Header().Set("Content-Type", "application/json")
  309. w.Header().Set("Access-Control-Allow-Origin", "*")
  310. qp := httputil.NewQueryParams(r.URL.Query())
  311. query := qp.Get("query", "")
  312. if query == "" {
  313. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  314. return
  315. }
  316. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  317. var timeVal time.Time
  318. timeStr := qp.Get("time", "")
  319. if len(timeStr) > 0 {
  320. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  321. timeVal = time.Unix(t, 0)
  322. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  323. timeVal = t
  324. }
  325. // If time is given, but not parse-able, return an error
  326. if timeVal.IsZero() {
  327. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  328. }
  329. }
  330. ctx := pds.promContexts.NewNamedContext(FrontendContextName)
  331. body, err := ctx.RawQuery(query, timeVal)
  332. if err != nil {
  333. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  334. return
  335. }
  336. w.Write(body) // prometheusQueryRange is a proxy for /query_range against prometheus
  337. }
  338. func (pds *PrometheusDataSource) prometheusQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  339. w.Header().Set("Content-Type", "application/json")
  340. w.Header().Set("Access-Control-Allow-Origin", "*")
  341. qp := httputil.NewQueryParams(r.URL.Query())
  342. query := qp.Get("query", "")
  343. if query == "" {
  344. fmt.Fprintf(w, "Error parsing query from request parameters.")
  345. return
  346. }
  347. start, end, duration, err := toStartEndStep(qp)
  348. if err != nil {
  349. fmt.Fprintf(w, "error: %s", err)
  350. return
  351. }
  352. ctx := pds.promContexts.NewNamedContext(FrontendContextName)
  353. body, err := ctx.RawQueryRange(query, start, end, duration)
  354. if err != nil {
  355. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  356. return
  357. }
  358. w.Write(body)
  359. }
  360. // thanosQuery is a proxy for /query against thanos
  361. func (pds *PrometheusDataSource) thanosQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  362. w.Header().Set("Content-Type", "application/json")
  363. w.Header().Set("Access-Control-Allow-Origin", "*")
  364. if pds.thanosClient == nil {
  365. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("ThanosDisabled")))
  366. return
  367. }
  368. qp := httputil.NewQueryParams(r.URL.Query())
  369. query := qp.Get("query", "")
  370. if query == "" {
  371. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  372. return
  373. }
  374. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  375. var timeVal time.Time
  376. timeStr := qp.Get("time", "")
  377. if len(timeStr) > 0 {
  378. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  379. timeVal = time.Unix(t, 0)
  380. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  381. timeVal = t
  382. }
  383. // If time is given, but not parse-able, return an error
  384. if timeVal.IsZero() {
  385. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  386. }
  387. }
  388. ctx := pds.thanosContexts.NewNamedContext(FrontendContextName)
  389. body, err := ctx.RawQuery(query, timeVal)
  390. if err != nil {
  391. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  392. return
  393. }
  394. w.Write(body)
  395. }
  396. // thanosQueryRange is a proxy for /query_range against thanos
  397. func (pds *PrometheusDataSource) thanosQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  398. w.Header().Set("Content-Type", "application/json")
  399. w.Header().Set("Access-Control-Allow-Origin", "*")
  400. if pds.thanosClient == nil {
  401. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("ThanosDisabled")))
  402. return
  403. }
  404. qp := httputil.NewQueryParams(r.URL.Query())
  405. query := qp.Get("query", "")
  406. if query == "" {
  407. fmt.Fprintf(w, "Error parsing query from request parameters.")
  408. return
  409. }
  410. start, end, duration, err := toStartEndStep(qp)
  411. if err != nil {
  412. fmt.Fprintf(w, "error: %s", err)
  413. return
  414. }
  415. ctx := pds.thanosContexts.NewNamedContext(FrontendContextName)
  416. body, err := ctx.RawQueryRange(query, start, end, duration)
  417. if err != nil {
  418. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  419. return
  420. }
  421. w.Write(body)
  422. }
  423. // promtheusQueueState returns the current state of the prometheus and thanos request queues
  424. func (pds *PrometheusDataSource) prometheusQueueState(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  425. w.Header().Set("Content-Type", "application/json")
  426. w.Header().Set("Access-Control-Allow-Origin", "*")
  427. promQueueState, err := GetPrometheusQueueState(pds.promClient, pds.promConfig)
  428. if err != nil {
  429. proto.WriteResponse(w, proto.ToResponse(nil, err))
  430. return
  431. }
  432. result := map[string]*PrometheusQueueState{
  433. "prometheus": promQueueState,
  434. }
  435. if pds.thanosClient != nil {
  436. thanosQueueState, err := GetPrometheusQueueState(pds.thanosClient, pds.thanosConfig.OpenCostPrometheusConfig)
  437. if err != nil {
  438. log.Warnf("Error getting Thanos queue state: %s", err)
  439. } else {
  440. result["thanos"] = thanosQueueState
  441. }
  442. }
  443. proto.WriteResponse(w, proto.ToResponse(result, nil))
  444. }
  445. // prometheusMetrics retrieves availability of Prometheus and Thanos metrics
  446. func (pds *PrometheusDataSource) prometheusMetrics(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  447. w.Header().Set("Content-Type", "application/json")
  448. w.Header().Set("Access-Control-Allow-Origin", "*")
  449. promMetrics := GetPrometheusMetrics(pds.promClient, pds.promConfig, "")
  450. result := map[string][]*PrometheusDiagnostic{
  451. "prometheus": promMetrics,
  452. }
  453. if pds.thanosClient != nil {
  454. thanosMetrics := GetPrometheusMetrics(pds.thanosClient, pds.thanosConfig.OpenCostPrometheusConfig, pds.thanosConfig.Offset)
  455. result["thanos"] = thanosMetrics
  456. }
  457. proto.WriteResponse(w, proto.ToResponse(result, nil))
  458. }
  459. func (pds *PrometheusDataSource) PrometheusClient() prometheus.Client {
  460. return pds.promClient
  461. }
  462. func (pds *PrometheusDataSource) PrometheusConfig() *OpenCostPrometheusConfig {
  463. return pds.promConfig
  464. }
  465. func (pds *PrometheusDataSource) PrometheusContexts() *ContextFactory {
  466. return pds.promContexts
  467. }
  468. func (pds *PrometheusDataSource) ThanosClient() prometheus.Client {
  469. return pds.thanosClient
  470. }
  471. func (pds *PrometheusDataSource) ThanosConfig() *OpenCostThanosConfig {
  472. return pds.thanosConfig
  473. }
  474. func (pds *PrometheusDataSource) ThanosContexts() *ContextFactory {
  475. return pds.thanosContexts
  476. }
  477. func (pds *PrometheusDataSource) RegisterEndPoints(router *httprouter.Router) {
  478. // endpoints migrated from server
  479. router.GET("/validatePrometheus", pds.prometheusMetadata)
  480. router.GET("/prometheusRecordingRules", pds.prometheusRecordingRules)
  481. router.GET("/prometheusConfig", pds.prometheusConfig)
  482. router.GET("/prometheusTargets", pds.prometheusTargets)
  483. router.GET("/status", pds.status)
  484. // prom query proxies
  485. router.GET("/prometheusQuery", pds.prometheusQuery)
  486. router.GET("/prometheusQueryRange", pds.prometheusQueryRange)
  487. router.GET("/thanosQuery", pds.thanosQuery)
  488. router.GET("/thanosQueryRange", pds.thanosQueryRange)
  489. // diagnostics
  490. router.GET("/diagnostics/requestQueue", pds.prometheusQueueState)
  491. router.GET("/diagnostics/prometheusMetrics", pds.prometheusMetrics)
  492. }
  493. func (pds *PrometheusDataSource) RefreshInterval() time.Duration {
  494. return pds.promConfig.ScrapeInterval
  495. }
  496. func (pds *PrometheusDataSource) Metrics() source.MetricsQuerier {
  497. return pds.metricsQuerier
  498. }
  499. func (pds *PrometheusDataSource) ClusterMap() clusters.ClusterMap {
  500. return pds.clusterMap
  501. }
  502. func (pds *PrometheusDataSource) BatchDuration() time.Duration {
  503. return pds.promConfig.MaxQueryDuration
  504. }
  505. func (pds *PrometheusDataSource) Resolution() time.Duration {
  506. return pds.promConfig.DataResolution
  507. }