datasource.go 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "math"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/julienschmidt/httprouter"
  11. "github.com/opencost/opencost/modules/prometheus-source/pkg/env"
  12. "github.com/opencost/opencost/core/pkg/clusters"
  13. "github.com/opencost/opencost/core/pkg/log"
  14. "github.com/opencost/opencost/core/pkg/protocol"
  15. "github.com/opencost/opencost/core/pkg/source"
  16. "github.com/opencost/opencost/core/pkg/util/httputil"
  17. "github.com/opencost/opencost/core/pkg/util/json"
  18. "github.com/opencost/opencost/core/pkg/util/timeutil"
  19. prometheus "github.com/prometheus/client_golang/api"
  20. prometheusAPI "github.com/prometheus/client_golang/api/prometheus/v1"
  21. )
  22. const (
  23. apiPrefix = "/api/v1"
  24. epAlertManagers = apiPrefix + "/alertmanagers"
  25. epLabelValues = apiPrefix + "/label/:name/values"
  26. epSeries = apiPrefix + "/series"
  27. epTargets = apiPrefix + "/targets"
  28. epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
  29. epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
  30. epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
  31. epConfig = apiPrefix + "/status/config"
  32. epFlags = apiPrefix + "/status/flags"
  33. epRules = apiPrefix + "/rules"
  34. )
  35. // helper for query range proxy requests
  36. func toStartEndStep(qp httputil.QueryParams) (start, end time.Time, step time.Duration, err error) {
  37. var e error
  38. ss := qp.Get("start", "")
  39. es := qp.Get("end", "")
  40. ds := qp.Get("duration", "")
  41. layout := "2006-01-02T15:04:05.000Z"
  42. start, e = time.Parse(layout, ss)
  43. if e != nil {
  44. err = fmt.Errorf("Error parsing time %s. Error: %s", ss, err)
  45. return
  46. }
  47. end, e = time.Parse(layout, es)
  48. if e != nil {
  49. err = fmt.Errorf("Error parsing time %s. Error: %s", es, err)
  50. return
  51. }
  52. step, e = time.ParseDuration(ds)
  53. if e != nil {
  54. err = fmt.Errorf("Error parsing duration %s. Error: %s", ds, err)
  55. return
  56. }
  57. err = nil
  58. return
  59. }
  60. // FIXME: Before merge, implement a more robust design. This is brittle and bug-prone,
  61. // FIXME: but decouples the prom requirements from the Provider implementations.
  62. var providerStorageQueries = map[string]func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string{
  63. "aws": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  64. return ""
  65. },
  66. "gcp": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  67. // TODO Set to the price for the appropriate storage class. It's not trivial to determine the local storage disk type
  68. // See https://cloud.google.com/compute/disks-image-pricing#persistentdisk
  69. localStorageCost := 0.04
  70. baseMetric := "container_fs_limit_bytes"
  71. if used {
  72. baseMetric = "container_fs_usage_bytes"
  73. }
  74. fmtCumulativeQuery := `sum(
  75. sum_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m])
  76. ) by (%s) / 60 / 730 / 1024 / 1024 / 1024 * %f`
  77. fmtMonthlyQuery := `sum(
  78. avg_over_time(%s{device!="tmpfs", id="/", %s}[%s:1m])
  79. ) by (%s) / 1024 / 1024 / 1024 * %f`
  80. fmtQuery := fmtCumulativeQuery
  81. if rate {
  82. fmtQuery = fmtMonthlyQuery
  83. }
  84. fmtWindow := timeutil.DurationString(end.Sub(start))
  85. return fmt.Sprintf(fmtQuery, baseMetric, config.ClusterFilter, fmtWindow, config.ClusterLabel, localStorageCost)
  86. },
  87. "azure": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  88. return ""
  89. },
  90. "alibaba": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  91. return ""
  92. },
  93. "scaleway": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  94. return ""
  95. },
  96. "otc": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  97. return ""
  98. },
  99. "oracle": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  100. return ""
  101. },
  102. "csv": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  103. return ""
  104. },
  105. "custom": func(config *OpenCostPrometheusConfig, start, end time.Time, rate bool, used bool) string {
  106. return ""
  107. },
  108. }
  109. // creates a new help error which indicates the caller can retry and is non-fatal.
  110. func newHelpRetryError(format string, args ...any) error {
  111. formatWithHelp := format + "\nTroubleshooting help available at: %s"
  112. args = append(args, PrometheusTroubleshootingURL)
  113. cause := fmt.Errorf(formatWithHelp, args...)
  114. return source.NewHelpRetryError(cause)
  115. }
  116. // PrometheusDataSource is the OpenCost data source implementation leveraging Prometheus. Prometheus provides longer retention periods and
  117. // more detailed metrics than the OpenCost Collector, which is useful for historical analysis and cost forecasting.
  118. type PrometheusDataSource struct {
  119. promConfig *OpenCostPrometheusConfig
  120. promClient prometheus.Client
  121. promContexts *ContextFactory
  122. thanosConfig *OpenCostThanosConfig
  123. thanosClient prometheus.Client
  124. thanosContexts *ContextFactory
  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() (*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(config, thanosConfig)
  143. }
  144. // NewPrometheusDataSource initializes clients for Prometheus and Thanos, and returns a new PrometheusDataSource.
  145. func NewPrometheusDataSource(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. return &PrometheusDataSource{
  202. promConfig: promConfig,
  203. promClient: promClient,
  204. promContexts: promContexts,
  205. thanosConfig: thanosConfig,
  206. thanosClient: thanosClient,
  207. thanosContexts: thanosContexts,
  208. }, nil
  209. }
  210. var proto = protocol.HTTP()
  211. // prometheusMetadata returns the metadata for the prometheus server
  212. func (pds *PrometheusDataSource) prometheusMetadata(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  213. w.Header().Set("Content-Type", "application/json")
  214. w.Header().Set("Access-Control-Allow-Origin", "*")
  215. resp := proto.ToResponse(Validate(pds.promClient, pds.promConfig))
  216. proto.WriteResponse(w, resp)
  217. }
  218. // prometheusRecordingRules is a proxy for /rules against prometheus
  219. func (pds *PrometheusDataSource) prometheusRecordingRules(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  220. w.Header().Set("Content-Type", "application/json")
  221. w.Header().Set("Access-Control-Allow-Origin", "*")
  222. u := pds.promClient.URL(epRules, nil)
  223. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  224. if err != nil {
  225. fmt.Fprintf(w, "error creating Prometheus rule request: %s", err)
  226. return
  227. }
  228. _, body, err := pds.promClient.Do(r.Context(), req)
  229. if err != nil {
  230. fmt.Fprintf(w, "error making Prometheus rule request: %s", err)
  231. return
  232. }
  233. w.Write(body)
  234. }
  235. // prometheusConfig returns the current configuration of the prometheus server
  236. func (pds *PrometheusDataSource) prometheusConfig(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  237. w.Header().Set("Content-Type", "application/json")
  238. w.Header().Set("Access-Control-Allow-Origin", "*")
  239. pConfig := map[string]string{
  240. "address": pds.promConfig.ServerEndpoint,
  241. }
  242. body, err := json.Marshal(pConfig)
  243. if err != nil {
  244. fmt.Fprintf(w, "Error marshalling prometheus config")
  245. } else {
  246. w.Write(body)
  247. }
  248. }
  249. // prometheusTargets is a proxy for /targets against prometheus
  250. func (pds *PrometheusDataSource) prometheusTargets(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  251. w.Header().Set("Content-Type", "application/json")
  252. w.Header().Set("Access-Control-Allow-Origin", "*")
  253. u := pds.promClient.URL(epTargets, nil)
  254. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  255. if err != nil {
  256. fmt.Fprintf(w, "error creating Prometheus rule request: %s", err)
  257. return
  258. }
  259. _, body, err := pds.promClient.Do(r.Context(), req)
  260. if err != nil {
  261. fmt.Fprintf(w, "error making Prometheus rule request: %s", err)
  262. return
  263. }
  264. w.Write(body)
  265. }
  266. // status returns the status of the prometheus client
  267. func (pds *PrometheusDataSource) status(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  268. w.Header().Set("Content-Type", "application/json")
  269. w.Header().Set("Access-Control-Allow-Origin", "*")
  270. promServer := pds.promConfig.ServerEndpoint
  271. api := prometheusAPI.NewAPI(pds.promClient)
  272. result, err := api.Buildinfo(r.Context())
  273. if err != nil {
  274. fmt.Fprintf(w, "Using Prometheus at %s, Error: %s", promServer, err)
  275. } else {
  276. fmt.Fprintf(w, "Using Prometheus at %s, version: %s", promServer, result.Version)
  277. }
  278. }
  279. // prometheusQuery is a proxy for /query against prometheus
  280. func (pds *PrometheusDataSource) prometheusQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  281. w.Header().Set("Content-Type", "application/json")
  282. w.Header().Set("Access-Control-Allow-Origin", "*")
  283. qp := httputil.NewQueryParams(r.URL.Query())
  284. query := qp.Get("query", "")
  285. if query == "" {
  286. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  287. return
  288. }
  289. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  290. var timeVal time.Time
  291. timeStr := qp.Get("time", "")
  292. if len(timeStr) > 0 {
  293. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  294. timeVal = time.Unix(t, 0)
  295. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  296. timeVal = t
  297. }
  298. // If time is given, but not parse-able, return an error
  299. if timeVal.IsZero() {
  300. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  301. }
  302. }
  303. ctx := pds.promContexts.NewNamedContext(FrontendContextName)
  304. body, err := ctx.RawQuery(query, timeVal)
  305. if err != nil {
  306. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  307. return
  308. }
  309. w.Write(body) // prometheusQueryRange is a proxy for /query_range against prometheus
  310. }
  311. func (pds *PrometheusDataSource) prometheusQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  312. w.Header().Set("Content-Type", "application/json")
  313. w.Header().Set("Access-Control-Allow-Origin", "*")
  314. qp := httputil.NewQueryParams(r.URL.Query())
  315. query := qp.Get("query", "")
  316. if query == "" {
  317. fmt.Fprintf(w, "Error parsing query from request parameters.")
  318. return
  319. }
  320. start, end, duration, err := toStartEndStep(qp)
  321. if err != nil {
  322. fmt.Fprintf(w, "error: %s", err)
  323. return
  324. }
  325. ctx := pds.promContexts.NewNamedContext(FrontendContextName)
  326. body, err := ctx.RawQueryRange(query, start, end, duration)
  327. if err != nil {
  328. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  329. return
  330. }
  331. w.Write(body)
  332. }
  333. // thanosQuery is a proxy for /query against thanos
  334. func (pds *PrometheusDataSource) thanosQuery(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  335. w.Header().Set("Content-Type", "application/json")
  336. w.Header().Set("Access-Control-Allow-Origin", "*")
  337. if pds.thanosClient == nil {
  338. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("ThanosDisabled")))
  339. return
  340. }
  341. qp := httputil.NewQueryParams(r.URL.Query())
  342. query := qp.Get("query", "")
  343. if query == "" {
  344. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Query Parameter 'query' is unset'")))
  345. return
  346. }
  347. // Attempt to parse time as either a unix timestamp or as an RFC3339 value
  348. var timeVal time.Time
  349. timeStr := qp.Get("time", "")
  350. if len(timeStr) > 0 {
  351. if t, err := strconv.ParseInt(timeStr, 10, 64); err == nil {
  352. timeVal = time.Unix(t, 0)
  353. } else if t, err := time.Parse(time.RFC3339, timeStr); err == nil {
  354. timeVal = t
  355. }
  356. // If time is given, but not parse-able, return an error
  357. if timeVal.IsZero() {
  358. http.Error(w, fmt.Sprintf("time must be a unix timestamp or RFC3339 value; illegal value given: %s", timeStr), http.StatusBadRequest)
  359. }
  360. }
  361. ctx := pds.thanosContexts.NewNamedContext(FrontendContextName)
  362. body, err := ctx.RawQuery(query, timeVal)
  363. if err != nil {
  364. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("Error running query %s. Error: %s", query, err)))
  365. return
  366. }
  367. w.Write(body)
  368. }
  369. // thanosQueryRange is a proxy for /query_range against thanos
  370. func (pds *PrometheusDataSource) thanosQueryRange(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  371. w.Header().Set("Content-Type", "application/json")
  372. w.Header().Set("Access-Control-Allow-Origin", "*")
  373. if pds.thanosClient == nil {
  374. proto.WriteResponse(w, proto.ToResponse(nil, fmt.Errorf("ThanosDisabled")))
  375. return
  376. }
  377. qp := httputil.NewQueryParams(r.URL.Query())
  378. query := qp.Get("query", "")
  379. if query == "" {
  380. fmt.Fprintf(w, "Error parsing query from request parameters.")
  381. return
  382. }
  383. start, end, duration, err := toStartEndStep(qp)
  384. if err != nil {
  385. fmt.Fprintf(w, "error: %s", err)
  386. return
  387. }
  388. ctx := pds.thanosContexts.NewNamedContext(FrontendContextName)
  389. body, err := ctx.RawQueryRange(query, start, end, duration)
  390. if err != nil {
  391. fmt.Fprintf(w, "Error running query %s. Error: %s", query, err)
  392. return
  393. }
  394. w.Write(body)
  395. }
  396. // promtheusQueueState returns the current state of the prometheus and thanos request queues
  397. func (pds *PrometheusDataSource) prometheusQueueState(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  398. w.Header().Set("Content-Type", "application/json")
  399. w.Header().Set("Access-Control-Allow-Origin", "*")
  400. promQueueState, err := GetPrometheusQueueState(pds.promClient, pds.promConfig)
  401. if err != nil {
  402. proto.WriteResponse(w, proto.ToResponse(nil, err))
  403. return
  404. }
  405. result := map[string]*PrometheusQueueState{
  406. "prometheus": promQueueState,
  407. }
  408. if pds.thanosClient != nil {
  409. thanosQueueState, err := GetPrometheusQueueState(pds.thanosClient, pds.thanosConfig.OpenCostPrometheusConfig)
  410. if err != nil {
  411. log.Warnf("Error getting Thanos queue state: %s", err)
  412. } else {
  413. result["thanos"] = thanosQueueState
  414. }
  415. }
  416. proto.WriteResponse(w, proto.ToResponse(result, nil))
  417. }
  418. // prometheusMetrics retrieves availability of Prometheus and Thanos metrics
  419. func (pds *PrometheusDataSource) prometheusMetrics(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  420. w.Header().Set("Content-Type", "application/json")
  421. w.Header().Set("Access-Control-Allow-Origin", "*")
  422. promMetrics := GetPrometheusMetrics(pds.promClient, pds.promConfig, "")
  423. result := map[string][]*PrometheusDiagnostic{
  424. "prometheus": promMetrics,
  425. }
  426. if pds.thanosClient != nil {
  427. thanosMetrics := GetPrometheusMetrics(pds.thanosClient, pds.thanosConfig.OpenCostPrometheusConfig, pds.thanosConfig.Offset)
  428. result["thanos"] = thanosMetrics
  429. }
  430. proto.WriteResponse(w, proto.ToResponse(result, nil))
  431. }
  432. func (pds *PrometheusDataSource) PrometheusClient() prometheus.Client {
  433. return pds.promClient
  434. }
  435. func (pds *PrometheusDataSource) PrometheusConfig() *OpenCostPrometheusConfig {
  436. return pds.promConfig
  437. }
  438. func (pds *PrometheusDataSource) PrometheusContexts() *ContextFactory {
  439. return pds.promContexts
  440. }
  441. func (pds *PrometheusDataSource) ThanosClient() prometheus.Client {
  442. return pds.thanosClient
  443. }
  444. func (pds *PrometheusDataSource) ThanosConfig() *OpenCostThanosConfig {
  445. return pds.thanosConfig
  446. }
  447. func (pds *PrometheusDataSource) ThanosContexts() *ContextFactory {
  448. return pds.thanosContexts
  449. }
  450. func (pds *PrometheusDataSource) NewClusterMap(clusterInfoProvider clusters.ClusterInfoProvider) clusters.ClusterMap {
  451. if pds.thanosClient != nil {
  452. return newPrometheusClusterMap(pds.thanosContexts, clusterInfoProvider, 10*time.Minute)
  453. }
  454. return newPrometheusClusterMap(pds.promContexts, clusterInfoProvider, 5*time.Minute)
  455. }
  456. func (pds *PrometheusDataSource) RegisterEndPoints(router *httprouter.Router) {
  457. // endpoints migrated from server
  458. router.GET("/validatePrometheus", pds.prometheusMetadata)
  459. router.GET("/prometheusRecordingRules", pds.prometheusRecordingRules)
  460. router.GET("/prometheusConfig", pds.prometheusConfig)
  461. router.GET("/prometheusTargets", pds.prometheusTargets)
  462. router.GET("/status", pds.status)
  463. // prom query proxies
  464. router.GET("/prometheusQuery", pds.prometheusQuery)
  465. router.GET("/prometheusQueryRange", pds.prometheusQueryRange)
  466. router.GET("/thanosQuery", pds.thanosQuery)
  467. router.GET("/thanosQueryRange", pds.thanosQueryRange)
  468. // diagnostics
  469. router.GET("/diagnostics/requestQueue", pds.prometheusQueueState)
  470. router.GET("/diagnostics/prometheusMetrics", pds.prometheusMetrics)
  471. }
  472. func (pds *PrometheusDataSource) RefreshInterval() time.Duration {
  473. return pds.promConfig.ScrapeInterval
  474. }
  475. func (pds *PrometheusDataSource) BatchDuration() time.Duration {
  476. return pds.promConfig.MaxQueryDuration
  477. }
  478. func (pds *PrometheusDataSource) Resolution() time.Duration {
  479. return pds.promConfig.DataResolution
  480. }
  481. func (pds *PrometheusDataSource) MetaData() map[string]string {
  482. thanosEnabled := pds.thanosClient != nil
  483. metadata := map[string]string{
  484. clusters.ClusterInfoThanosEnabledKey: fmt.Sprintf("%t", thanosEnabled),
  485. }
  486. if thanosEnabled {
  487. metadata[clusters.ClusterInfoThanosOffsetKey] = pds.thanosConfig.Offset
  488. }
  489. return metadata
  490. }
  491. //--------------------------------------------------------------------------
  492. // InstantMetricsQuerier
  493. //--------------------------------------------------------------------------
  494. func (pds *PrometheusDataSource) QueryPVPricePerGiBHour(start, end time.Time) *source.Future[source.PVPricePerGiBHourResult] {
  495. const pvCostQuery = `avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (%s, persistentvolume, volumename, provider_id)`
  496. durStr := timeutil.DurationString(end.Sub(start))
  497. if durStr == "" {
  498. panic("failed to parse duration string passed to QueryPVCost")
  499. }
  500. queryPVCost := fmt.Sprintf(pvCostQuery, pds.promConfig.ClusterFilter, durStr, pds.promConfig.ClusterLabel)
  501. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  502. return source.NewFuture(source.DecodePVPricePerGiBHourResult, ctx.QueryAtTime(queryPVCost, end))
  503. }
  504. func (pds *PrometheusDataSource) QueryPVUsedAverage(start, end time.Time) *source.Future[source.PVUsedAvgResult] {
  505. // `avg(avg_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  506. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  507. const pvUsedAverageQuery = `avg(avg_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  508. cfg := pds.promConfig
  509. durStr := timeutil.DurationString(end.Sub(start))
  510. if durStr == "" {
  511. panic("failed to parse duration string passed to QueryPVUsedAverage")
  512. }
  513. queryPVUsedAvg := fmt.Sprintf(pvUsedAverageQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  514. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  515. return source.NewFuture(source.DecodePVUsedAvgResult, ctx.QueryAtTime(queryPVUsedAvg, end))
  516. }
  517. func (pds *PrometheusDataSource) QueryPVUsedMax(start, end time.Time) *source.Future[source.PVUsedMaxResult] {
  518. // `max(max_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  519. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  520. const pvUsedMaxQuery = `max(max_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  521. cfg := pds.promConfig
  522. durStr := timeutil.DurationString(end.Sub(start))
  523. if durStr == "" {
  524. panic("failed to parse duration string passed to QueryPVUsedMax")
  525. }
  526. queryPVUsedMax := fmt.Sprintf(pvUsedMaxQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  527. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  528. return source.NewFuture(source.DecodePVUsedMaxResult, ctx.QueryAtTime(queryPVUsedMax, end))
  529. }
  530. func (pds *PrometheusDataSource) QueryPVCInfo(start, end time.Time) *source.Future[source.PVCInfoResult] {
  531. const queryFmtPVCInfo = `avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, volumename, namespace, %s)[%s:%s]`
  532. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  533. cfg := pds.promConfig
  534. resolution := cfg.DataResolution
  535. resStr := timeutil.DurationString(resolution)
  536. durStr := timeutil.DurationString(end.Sub(start))
  537. if durStr == "" {
  538. panic("failed to parse duration string passed to QueryPVCInfo")
  539. }
  540. queryPVCInfo := fmt.Sprintf(queryFmtPVCInfo, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  541. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  542. return source.NewFuture(source.DecodePVCInfoResult, ctx.QueryAtTime(queryPVCInfo, end))
  543. }
  544. func (pds *PrometheusDataSource) QueryPVActiveMinutes(start, end time.Time) *source.Future[source.PVActiveMinutesResult] {
  545. const pvActiveMinsQuery = `avg(kube_persistentvolume_capacity_bytes{%s}) by (%s, persistentvolume)[%s:%dm]`
  546. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  547. cfg := pds.promConfig
  548. minsPerResolution := cfg.DataResolutionMinutes
  549. durStr := timeutil.DurationString(end.Sub(start))
  550. if durStr == "" {
  551. panic("failed to parse duration string passed to QueryPVActiveMinutes")
  552. }
  553. queryPVActiveMins := fmt.Sprintf(pvActiveMinsQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  554. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  555. return source.NewFuture(source.DecodePVActiveMinutesResult, ctx.QueryAtTime(queryPVActiveMins, end))
  556. }
  557. func (pds *PrometheusDataSource) QueryLocalStorageCost(start, end time.Time) *source.Future[source.LocalStorageCostResult] {
  558. // `sum_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`
  559. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  560. const localStorageCostQuery = `sum_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`
  561. cfg := pds.promConfig
  562. resolution := cfg.DataResolution
  563. durStr := timeutil.DurationString(end.Sub(start))
  564. if durStr == "" {
  565. panic("failed to parse duration string passed to QueryLocalStorageCost")
  566. }
  567. //Ensuring if data resolution is less than 60s default it to 1m
  568. var minsPerResolution int
  569. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  570. minsPerResolution = 1
  571. log.DedupedWarningf(3, "QueryLocalStorageCost: Configured resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  572. }
  573. // hourlyToCumulative is a scaling factor that, when multiplied by an
  574. // hourly value, converts it to a cumulative value; i.e. [$/hr] *
  575. // [min/res]*[hr/min] = [$/res]
  576. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  577. costPerGBHr := 0.04 / 730.0
  578. queryLocalStorageCost := fmt.Sprintf(localStorageCostQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  579. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  580. return source.NewFuture(source.DecodeLocalStorageCostResult, ctx.QueryAtTime(queryLocalStorageCost, end))
  581. }
  582. func (pds *PrometheusDataSource) QueryLocalStorageUsedCost(start, end time.Time) *source.Future[source.LocalStorageUsedCostResult] {
  583. // `sum_over_time(sum(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`
  584. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  585. const localStorageUsedCostQuery = `sum_over_time(sum(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`
  586. cfg := pds.promConfig
  587. minsPerResolution := cfg.DataResolutionMinutes
  588. durStr := timeutil.DurationString(end.Sub(start))
  589. if durStr == "" {
  590. panic("failed to parse duration string passed to QueryLocalStorageUsedCost")
  591. }
  592. // hourlyToCumulative is a scaling factor that, when multiplied by an
  593. // hourly value, converts it to a cumulative value; i.e. [$/hr] *
  594. // [min/res]*[hr/min] = [$/res]
  595. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  596. costPerGBHr := 0.04 / 730.0
  597. queryLocalStorageUsedCost := fmt.Sprintf(localStorageUsedCostQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  598. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  599. return source.NewFuture(source.DecodeLocalStorageUsedCostResult, ctx.QueryAtTime(queryLocalStorageUsedCost, end))
  600. }
  601. func (pds *PrometheusDataSource) QueryLocalStorageUsedAvg(start, end time.Time) *source.Future[source.LocalStorageUsedAvgResult] {
  602. // `avg(sum(avg_over_time(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}[%s])) by (instance, device, %s, job)) by (instance, device, %s)`
  603. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  604. const localStorageUsedAvgQuery = `avg(sum(avg_over_time(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}[%s])) by (instance, device, %s, job)) by (instance, device, %s)`
  605. cfg := pds.promConfig
  606. durStr := timeutil.DurationString(end.Sub(start))
  607. if durStr == "" {
  608. panic("failed to parse duration string passed to QueryLocalStorageUsedAvg")
  609. }
  610. queryLocalStorageUsedAvg := fmt.Sprintf(localStorageUsedAvgQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  611. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  612. return source.NewFuture(source.DecodeLocalStorageUsedAvgResult, ctx.QueryAtTime(queryLocalStorageUsedAvg, end))
  613. }
  614. func (pds *PrometheusDataSource) QueryLocalStorageUsedMax(start, end time.Time) *source.Future[source.LocalStorageUsedMaxResult] {
  615. // `max(sum(max_over_time(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}[%s])) by (instance, device, %s, job)) by (instance, device, %s)`
  616. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  617. const localStorageUsedMaxQuery = `max(sum(max_over_time(container_fs_usage_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}[%s])) by (instance, device, %s, job)) by (instance, device, %s)`
  618. cfg := pds.promConfig
  619. durStr := timeutil.DurationString(end.Sub(start))
  620. if durStr == "" {
  621. panic("failed to parse duration string passed to QueryLocalStorageUsedMax")
  622. }
  623. queryLocalStorageUsedMax := fmt.Sprintf(localStorageUsedMaxQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  624. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  625. return source.NewFuture(source.DecodeLocalStorageUsedMaxResult, ctx.QueryAtTime(queryLocalStorageUsedMax, end))
  626. }
  627. func (pds *PrometheusDataSource) QueryLocalStorageBytes(start, end time.Time) *source.Future[source.LocalStorageBytesResult] {
  628. // `avg_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm])`
  629. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  630. const localStorageBytesQuery = `avg_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm])`
  631. cfg := pds.promConfig
  632. minsPerResolution := cfg.DataResolutionMinutes
  633. durStr := timeutil.DurationString(end.Sub(start))
  634. if durStr == "" {
  635. panic("failed to parse duration string passed to QueryLocalStorageBytes")
  636. }
  637. queryLocalStorageBytes := fmt.Sprintf(localStorageBytesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  638. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  639. return source.NewFuture(source.DecodeLocalStorageBytesResult, ctx.QueryAtTime(queryLocalStorageBytes, end))
  640. }
  641. func (pds *PrometheusDataSource) QueryLocalStorageActiveMinutes(start, end time.Time) *source.Future[source.LocalStorageActiveMinutesResult] {
  642. // `count(node_total_hourly_cost{%s}) by (%s, node)[%s:%dm]`
  643. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  644. const localStorageActiveMinutesQuery = `count(node_total_hourly_cost{%s}) by (%s, node)[%s:%dm]`
  645. cfg := pds.promConfig
  646. minsPerResolution := cfg.DataResolutionMinutes
  647. durStr := timeutil.DurationString(end.Sub(start))
  648. if durStr == "" {
  649. panic("failed to parse duration string passed to QueryLocalStorageActiveMinutes")
  650. }
  651. queryLocalStorageActiveMins := fmt.Sprintf(localStorageActiveMinutesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  652. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  653. return source.NewFuture(source.DecodeLocalStorageActiveMinutesResult, ctx.QueryAtTime(queryLocalStorageActiveMins, end))
  654. }
  655. func (pds *PrometheusDataSource) QueryLocalStorageBytesByProvider(provider string, start, end time.Time) *source.Future[source.LocalStorageBytesByProviderResult] {
  656. var localStorageBytesQuery string
  657. key := strings.ToLower(provider)
  658. if f, ok := providerStorageQueries[key]; ok {
  659. localStorageBytesQuery = f(pds.promConfig, start, end, false, false)
  660. } else {
  661. localStorageBytesQuery = ""
  662. }
  663. if localStorageBytesQuery == "" {
  664. return newEmptyResult(source.DecodeLocalStorageBytesByProviderResult)
  665. }
  666. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  667. return source.NewFuture(source.DecodeLocalStorageBytesByProviderResult, ctx.QueryAtTime(localStorageBytesQuery, end))
  668. }
  669. func (pds *PrometheusDataSource) QueryLocalStorageUsedByProvider(provider string, start, end time.Time) *source.Future[source.LocalStorageUsedByProviderResult] {
  670. var localStorageUsedQuery string
  671. key := strings.ToLower(provider)
  672. if f, ok := providerStorageQueries[key]; ok {
  673. localStorageUsedQuery = f(pds.promConfig, start, end, false, true)
  674. } else {
  675. localStorageUsedQuery = ""
  676. }
  677. if localStorageUsedQuery == "" {
  678. return newEmptyResult(source.DecodeLocalStorageUsedByProviderResult)
  679. }
  680. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  681. return source.NewFuture(source.DecodeLocalStorageUsedByProviderResult, ctx.QueryAtTime(localStorageUsedQuery, end))
  682. }
  683. func (pds *PrometheusDataSource) QueryNodeCPUCoresCapacity(start, end time.Time) *source.Future[source.NodeCPUCoresCapacityResult] {
  684. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  685. const nodeCPUCoresCapacityQuery = `avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s])) by (%s, node)`
  686. cfg := pds.promConfig
  687. durStr := timeutil.DurationString(end.Sub(start))
  688. if durStr == "" {
  689. panic("failed to parse duration string passed to QueryNodeCPUCoresCapacity")
  690. }
  691. queryNodeCPUCoresCapacity := fmt.Sprintf(nodeCPUCoresCapacityQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  692. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  693. return source.NewFuture(source.DecodeNodeCPUCoresCapacityResult, ctx.QueryAtTime(queryNodeCPUCoresCapacity, end))
  694. }
  695. func (pds *PrometheusDataSource) QueryNodeCPUCoresAllocatable(start, end time.Time) *source.Future[source.NodeCPUCoresAllocatableResult] {
  696. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  697. const nodeCPUCoresAllocatableQuery = `avg(avg_over_time(kube_node_status_allocatable_cpu_cores{%s}[%s])) by (%s, node)`
  698. // `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  699. cfg := pds.promConfig
  700. durStr := timeutil.DurationString(end.Sub(start))
  701. if durStr == "" {
  702. panic("failed to parse duration string passed to QueryNodeCPUCoresAllocatable")
  703. }
  704. queryNodeCPUCoresAllocatable := fmt.Sprintf(nodeCPUCoresAllocatableQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  705. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  706. return source.NewFuture(source.DecodeNodeCPUCoresAllocatableResult, ctx.QueryAtTime(queryNodeCPUCoresAllocatable, end))
  707. }
  708. func (pds *PrometheusDataSource) QueryNodeRAMBytesCapacity(start, end time.Time) *source.Future[source.NodeRAMBytesCapacityResult] {
  709. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  710. const nodeRAMBytesCapacityQuery = `avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s])) by (%s, node)`
  711. cfg := pds.promConfig
  712. durStr := timeutil.DurationString(end.Sub(start))
  713. if durStr == "" {
  714. panic("failed to parse duration string passed to QueryNodeRAMBytesCapacity")
  715. }
  716. queryNodeRAMBytesCapacity := fmt.Sprintf(nodeRAMBytesCapacityQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  717. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  718. return source.NewFuture(source.DecodeNodeRAMBytesCapacityResult, ctx.QueryAtTime(queryNodeRAMBytesCapacity, end))
  719. }
  720. func (pds *PrometheusDataSource) QueryNodeRAMBytesAllocatable(start, end time.Time) *source.Future[source.NodeRAMBytesAllocatableResult] {
  721. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  722. const nodeRAMBytesAllocatableQuery = `avg(avg_over_time(kube_node_status_allocatable_memory_bytes{%s}[%s])) by (%s, node)`
  723. cfg := pds.promConfig
  724. durStr := timeutil.DurationString(end.Sub(start))
  725. if durStr == "" {
  726. panic("failed to parse duration string passed to QueryNodeRAMBytesAllocatable")
  727. }
  728. queryNodeRAMBytesAllocatable := fmt.Sprintf(nodeRAMBytesAllocatableQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  729. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  730. return source.NewFuture(source.DecodeNodeRAMBytesAllocatableResult, ctx.QueryAtTime(queryNodeRAMBytesAllocatable, end))
  731. }
  732. func (pds *PrometheusDataSource) QueryNodeGPUCount(start, end time.Time) *source.Future[source.NodeGPUCountResult] {
  733. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  734. const nodeGPUCountQuery = `avg(avg_over_time(node_gpu_count{%s}[%s])) by (%s, node, provider_id)`
  735. cfg := pds.promConfig
  736. durStr := timeutil.DurationString(end.Sub(start))
  737. if durStr == "" {
  738. panic("failed to parse duration string passed to QueryNodeGPUCount")
  739. }
  740. queryNodeGPUCount := fmt.Sprintf(nodeGPUCountQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  741. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  742. return source.NewFuture(source.DecodeNodeGPUCountResult, ctx.QueryAtTime(queryNodeGPUCount, end))
  743. }
  744. func (pds *PrometheusDataSource) QueryNodeLabels(start, end time.Time) *source.Future[source.NodeLabelsResult] {
  745. const labelsQuery = `avg_over_time(kube_node_labels{%s}[%s])`
  746. // env.GetPromClusterFilter(), durStr
  747. cfg := pds.promConfig
  748. durStr := timeutil.DurationString(end.Sub(start))
  749. if durStr == "" {
  750. panic("failed to parse duration string passed to QueryNodeLabels")
  751. }
  752. queryLabels := fmt.Sprintf(labelsQuery, cfg.ClusterFilter, durStr)
  753. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  754. return source.NewFuture(source.DecodeNodeLabelsResult, ctx.QueryAtTime(queryLabels, end))
  755. }
  756. func (pds *PrometheusDataSource) QueryNodeActiveMinutes(start, end time.Time) *source.Future[source.NodeActiveMinutesResult] {
  757. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  758. const activeMinsQuery = `avg(node_total_hourly_cost{%s}) by (node, %s, provider_id)[%s:%dm]`
  759. cfg := pds.promConfig
  760. minsPerResolution := cfg.DataResolutionMinutes
  761. durStr := timeutil.DurationString(end.Sub(start))
  762. if durStr == "" {
  763. panic("failed to parse duration string passed to QueryNodeActiveMinutes")
  764. }
  765. queryActiveMins := fmt.Sprintf(activeMinsQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  766. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  767. return source.NewFuture(source.DecodeNodeActiveMinutesResult, ctx.QueryAtTime(queryActiveMins, end))
  768. }
  769. func (pds *PrometheusDataSource) QueryNodeCPUModeTotal(start, end time.Time) *source.Future[source.NodeCPUModeTotalResult] {
  770. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel())
  771. const nodeCPUModeTotalQuery = `sum(rate(node_cpu_seconds_total{%s}[%s:%dm])) by (kubernetes_node, %s, mode)`
  772. cfg := pds.promConfig
  773. minsPerResolution := cfg.DataResolutionMinutes
  774. durStr := timeutil.DurationString(end.Sub(start))
  775. if durStr == "" {
  776. panic("failed to parse duration string passed to QueryNodeCPUModeTotal")
  777. }
  778. queryCPUModeTotal := fmt.Sprintf(nodeCPUModeTotalQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel)
  779. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  780. return source.NewFuture(source.DecodeNodeCPUModeTotalResult, ctx.QueryAtTime(queryCPUModeTotal, end))
  781. }
  782. func (pds *PrometheusDataSource) QueryNodeCPUModePercent(start, end time.Time) *source.Future[source.NodeCPUModePercentResult] {
  783. const fmtQueryCPUModePct = `
  784. sum(rate(node_cpu_seconds_total{%s}[%s])) by (%s, mode) / ignoring(mode)
  785. group_left sum(rate(node_cpu_seconds_total{%s}[%s])) by (%s)
  786. `
  787. // env.GetPromClusterFilter(), windowStr, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel()
  788. cfg := pds.promConfig
  789. durStr := timeutil.DurationString(end.Sub(start))
  790. if durStr == "" {
  791. panic("failed to parse duration string passed to QueryNodeCPUModePercent")
  792. }
  793. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  794. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  795. return source.NewFuture(source.DecodeNodeCPUModePercentResult, ctx.QueryAtTime(queryCPUModePct, end))
  796. }
  797. func (pds *PrometheusDataSource) QueryNodeRAMSystemPercent(start, end time.Time) *source.Future[source.NodeRAMSystemPercentResult] {
  798. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  799. const nodeRAMSystemPctQuery = `sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace="kube-system", %s}[%s:%dm])) by (instance, %s) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm])) by (node, %s), "instance", "$1", "node", "(.*)")) by (instance, %s)`
  800. cfg := pds.promConfig
  801. minsPerResolution := cfg.DataResolutionMinutes
  802. durStr := timeutil.DurationString(end.Sub(start))
  803. if durStr == "" {
  804. panic("failed to parse duration string passed to QueryNodeRAMSystemPercent")
  805. }
  806. queryRAMSystemPct := fmt.Sprintf(nodeRAMSystemPctQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterLabel)
  807. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  808. return source.NewFuture(source.DecodeNodeRAMSystemPercentResult, ctx.QueryAtTime(queryRAMSystemPct, end))
  809. }
  810. func (pds *PrometheusDataSource) QueryNodeRAMUserPercent(start, end time.Time) *source.Future[source.NodeRAMUserPercentResult] {
  811. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  812. const nodeRAMUserPctQuery = `sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace!="kube-system", %s}[%s:%dm])) by (instance, %s) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm])) by (node, %s), "instance", "$1", "node", "(.*)")) by (instance, %s)`
  813. cfg := pds.promConfig
  814. minsPerResolution := cfg.DataResolutionMinutes
  815. durStr := timeutil.DurationString(end.Sub(start))
  816. if durStr == "" {
  817. panic("failed to parse duration string passed to QueryNodeRAMUserPercent")
  818. }
  819. queryRAMUserPct := fmt.Sprintf(nodeRAMUserPctQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterLabel)
  820. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  821. return source.NewFuture(source.DecodeNodeRAMUserPercentResult, ctx.QueryAtTime(queryRAMUserPct, end))
  822. }
  823. func (pds *PrometheusDataSource) QueryLBPricePerHr(start, end time.Time) *source.Future[source.LBPricePerHrResult] {
  824. const queryFmtLBCostPerHr = `avg(avg_over_time(kubecost_load_balancer_cost{%s}[%s])) by (namespace, service_name, ingress_ip, %s)`
  825. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  826. cfg := pds.promConfig
  827. durStr := timeutil.DurationString(end.Sub(start))
  828. if durStr == "" {
  829. panic("failed to parse duration string passed to QueryLBPricePerHr")
  830. }
  831. queryLBCostPerHr := fmt.Sprintf(queryFmtLBCostPerHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  832. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  833. return source.NewFuture(source.DecodeLBPricePerHrResult, ctx.QueryAtTime(queryLBCostPerHr, end))
  834. }
  835. func (pds *PrometheusDataSource) QueryLBActiveMinutes(start, end time.Time) *source.Future[source.LBActiveMinutesResult] {
  836. const lbActiveMinutesQuery = `avg(kubecost_load_balancer_cost{%s}) by (namespace, service_name, %s, ingress_ip)[%s:%dm]`
  837. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  838. cfg := pds.promConfig
  839. minsPerResolution := cfg.DataResolutionMinutes
  840. durStr := timeutil.DurationString(end.Sub(start))
  841. if durStr == "" {
  842. panic("failed to parse duration string passed to QueryLBActiveMinutes")
  843. }
  844. queryLBActiveMins := fmt.Sprintf(lbActiveMinutesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  845. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  846. return source.NewFuture(source.DecodeLBActiveMinutesResult, ctx.QueryAtTime(queryLBActiveMins, end))
  847. }
  848. func (pds *PrometheusDataSource) QueryClusterManagementDuration(start, end time.Time) *source.Future[source.ClusterManagementDurationResult] {
  849. const clusterManagementDurationQuery = `avg(kubecost_cluster_management_cost{%s}) by (%s, provisioner_name)[%s:%dm]`
  850. cfg := pds.promConfig
  851. minsPerResolution := cfg.DataResolutionMinutes
  852. durStr := timeutil.DurationString(end.Sub(start))
  853. if durStr == "" {
  854. panic("failed to parse duration string passed to QueryClusterManagementDuration")
  855. }
  856. queryClusterManagementDuration := fmt.Sprintf(clusterManagementDurationQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  857. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  858. return source.NewFuture(source.DecodeClusterManagementDurationResult, ctx.QueryAtTime(queryClusterManagementDuration, end))
  859. }
  860. func (pds *PrometheusDataSource) QueryClusterManagementPricePerHr(start, end time.Time) *source.Future[source.ClusterManagementPricePerHrResult] {
  861. const clusterManagementCostQuery = `avg(avg_over_time(kubecost_cluster_management_cost{%s}[%s])) by (%s, provisioner_name)`
  862. // env.GetPromClusterFilter(), durationStr, env.GetPromClusterLabel()
  863. cfg := pds.promConfig
  864. durStr := timeutil.DurationString(end.Sub(start))
  865. if durStr == "" {
  866. panic("failed to parse duration string passed to QueryClusterManagementCost")
  867. }
  868. queryClusterManagementCost := fmt.Sprintf(clusterManagementCostQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  869. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  870. return source.NewFuture(source.DecodeClusterManagementPricePerHrResult, ctx.QueryAtTime(queryClusterManagementCost, end))
  871. }
  872. func (pds *PrometheusDataSource) QueryDataCount(start, end time.Time) *source.Future[source.DataCountResult] {
  873. const fmtQueryDataCount = `
  874. count_over_time(sum(kube_node_status_capacity_cpu_cores{%s}) by (%s)[%s:%dm]) * %d
  875. `
  876. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, minsPerResolution)
  877. cfg := pds.promConfig
  878. minsPerResolution := cfg.DataResolutionMinutes
  879. durStr := timeutil.DurationString(end.Sub(start))
  880. if durStr == "" {
  881. panic("failed to parse duration string passed to QueryDataCount")
  882. }
  883. queryDataCount := fmt.Sprintf(fmtQueryDataCount, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, minsPerResolution)
  884. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  885. return source.NewFuture(source.DecodeDataCountResult, ctx.QueryAtTime(queryDataCount, end))
  886. }
  887. func (pds *PrometheusDataSource) QueryTotalGPU(start, end time.Time) *source.Future[source.TotalGPUResult] {
  888. const fmtQueryTotalGPU = `
  889. sum(
  890. sum_over_time(node_gpu_hourly_cost{%s}[%s:%dm]) * %f
  891. ) by (%s)
  892. `
  893. // env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, hourlyToCumulative, env.GetPromClusterLabel())
  894. cfg := pds.promConfig
  895. minsPerResolution := cfg.DataResolutionMinutes
  896. durStr := timeutil.DurationString(end.Sub(start))
  897. if durStr == "" {
  898. panic("failed to parse duration string passed to QueryTotalGPU")
  899. }
  900. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  901. // value, converts it to a cumulative value; i.e.
  902. // [$/hr] * [min/res]*[hr/min] = [$/res]
  903. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  904. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, cfg.ClusterFilter, durStr, minsPerResolution, hourlyToCumulative, cfg.ClusterLabel)
  905. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  906. return source.NewFuture(source.DecodeTotalGPUResult, ctx.QueryAtTime(queryTotalGPU, end))
  907. }
  908. func (pds *PrometheusDataSource) QueryTotalCPU(start, end time.Time) *source.Future[source.TotalCPUResult] {
  909. const fmtQueryTotalCPU = `
  910. sum(
  911. sum_over_time(avg(kube_node_status_capacity_cpu_cores{%s}) by (node, %s)[%s:%dm]) *
  912. avg(avg_over_time(node_cpu_hourly_cost{%s}[%s:%dm])) by (node, %s) * %f
  913. ) by (%s)
  914. `
  915. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel()
  916. cfg := pds.promConfig
  917. minsPerResolution := cfg.DataResolutionMinutes
  918. durStr := timeutil.DurationString(end.Sub(start))
  919. if durStr == "" {
  920. panic("failed to parse duration string passed to QueryTotalCPU")
  921. }
  922. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  923. // value, converts it to a cumulative value; i.e.
  924. // [$/hr] * [min/res]*[hr/min] = [$/res]
  925. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  926. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  927. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  928. return source.NewFuture(source.DecodeTotalCPUResult, ctx.QueryAtTime(queryTotalCPU, end))
  929. }
  930. func (pds *PrometheusDataSource) QueryTotalRAM(start, end time.Time) *source.Future[source.TotalRAMResult] {
  931. const fmtQueryTotalRAM = `
  932. sum(
  933. sum_over_time(avg(kube_node_status_capacity_memory_bytes{%s}) by (node, %s)[%s:%dm]) / 1024 / 1024 / 1024 *
  934. avg(avg_over_time(node_ram_hourly_cost{%s}[%s:%dm])) by (node, %s) * %f
  935. ) by (%s)
  936. `
  937. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, env.GetPromClusterFilter(), windowStr, minsPerResolution, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  938. cfg := pds.promConfig
  939. minsPerResolution := cfg.DataResolutionMinutes
  940. durStr := timeutil.DurationString(end.Sub(start))
  941. if durStr == "" {
  942. panic("failed to parse duration string passed to QueryTotalRAM")
  943. }
  944. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  945. // value, converts it to a cumulative value; i.e.
  946. // [$/hr] * [min/res]*[hr/min] = [$/res]
  947. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  948. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  949. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  950. return source.NewFuture(source.DecodeTotalRAMResult, ctx.QueryAtTime(queryTotalRAM, end))
  951. }
  952. func (pds *PrometheusDataSource) QueryTotalStorage(start, end time.Time) *source.Future[source.TotalStorageResult] {
  953. const fmtQueryTotalStorage = `
  954. sum(
  955. sum_over_time(avg(kube_persistentvolume_capacity_bytes{%s}) by (persistentvolume, %s)[%s:%dm]) / 1024 / 1024 / 1024 *
  956. avg(avg_over_time(pv_hourly_cost{%s}[%s:%dm])) by (persistentvolume, %s) * %f
  957. ) by (%s)
  958. `
  959. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, env.GetPromClusterFilter(), windowStr, minsPerResolution, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  960. cfg := pds.promConfig
  961. minsPerResolution := cfg.DataResolutionMinutes
  962. durStr := timeutil.DurationString(end.Sub(start))
  963. if durStr == "" {
  964. panic("failed to parse duration string passed to QueryTotalStorage")
  965. }
  966. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  967. // value, converts it to a cumulative value; i.e.
  968. // [$/hr] * [min/res]*[hr/min] = [$/res]
  969. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  970. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  971. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  972. return source.NewFuture(source.DecodeTotalStorageResult, ctx.QueryAtTime(queryTotalStorage, end))
  973. }
  974. func (pds *PrometheusDataSource) QueryClusterCores(start, end time.Time, step time.Duration) *source.Future[source.ClusterCoresResult] {
  975. const queryClusterCores = `sum(
  976. avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s])) by (node, %s) * avg(avg_over_time(node_cpu_hourly_cost{%s}[%s])) by (node, %s) * 730 +
  977. avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (node, %s) * 730
  978. ) by (%s)`
  979. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  980. cfg := pds.promConfig
  981. durStr := timeutil.DurationString(step)
  982. if durStr == "" {
  983. panic("failed to parse duration string passed to QueryClusterCores")
  984. }
  985. clusterCoresQuery := fmt.Sprintf(queryClusterCores, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  986. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  987. return source.NewFuture(source.DecodeClusterCoresResult, ctx.QueryRange(clusterCoresQuery, start, end, step))
  988. }
  989. func (pds *PrometheusDataSource) QueryClusterRAM(start, end time.Time, step time.Duration) *source.Future[source.ClusterRAMResult] {
  990. const queryClusterRAM = `sum(
  991. avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s])) by (node, %s) / 1024 / 1024 / 1024 * avg(avg_over_time(node_ram_hourly_cost{%s}[%s])) by (node, %s) * 730
  992. ) by (%s)`
  993. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  994. cfg := pds.promConfig
  995. durStr := timeutil.DurationString(step)
  996. if durStr == "" {
  997. panic("failed to parse duration string passed to QueryClusterRAM")
  998. }
  999. clusterRAMQuery := fmt.Sprintf(queryClusterRAM, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  1000. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1001. return source.NewFuture(source.DecodeClusterRAMResult, ctx.QueryRange(clusterRAMQuery, start, end, step))
  1002. }
  1003. func (pds *PrometheusDataSource) QueryClusterStorage(start, end time.Time, step time.Duration) *source.Future[source.ClusterStorageResult] {
  1004. return pds.QueryClusterStorageByProvider("", start, end, step)
  1005. }
  1006. func (pds *PrometheusDataSource) QueryClusterStorageByProvider(provider string, start, end time.Time, step time.Duration) *source.Future[source.ClusterStorageResult] {
  1007. const queryStorage = `sum(
  1008. avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (persistentvolume, %s) * 730
  1009. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  1010. ) by (%s) %s`
  1011. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1012. var localStorageQuery string
  1013. if provider != "" {
  1014. key := strings.ToLower(provider)
  1015. if f, ok := providerStorageQueries[key]; ok {
  1016. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1017. } else {
  1018. localStorageQuery = ""
  1019. }
  1020. }
  1021. if localStorageQuery != "" {
  1022. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1023. }
  1024. cfg := pds.promConfig
  1025. durStr := timeutil.DurationString(step)
  1026. if durStr == "" {
  1027. panic("failed to parse duration string passed to QueryClusterCores")
  1028. }
  1029. clusterStorageQuery := fmt.Sprintf(queryStorage, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel, localStorageQuery)
  1030. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1031. return source.NewFuture(source.DecodeClusterStorageResult, ctx.QueryRange(clusterStorageQuery, start, end, step))
  1032. }
  1033. func (pds *PrometheusDataSource) QueryClusterTotal(start, end time.Time, step time.Duration) *source.Future[source.ClusterTotalResult] {
  1034. return pds.QueryClusterTotalByProvider("", start, end, step)
  1035. }
  1036. func (pds *PrometheusDataSource) QueryClusterTotalByProvider(provider string, start, end time.Time, step time.Duration) *source.Future[source.ClusterTotalResult] {
  1037. const queryTotal = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 +
  1038. sum(
  1039. avg(avg_over_time(pv_hourly_cost{%s}[1h])) by (persistentvolume, %s) * 730
  1040. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[1h])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  1041. ) by (%s) %s`
  1042. var localStorageQuery string
  1043. if provider != "" {
  1044. key := strings.ToLower(provider)
  1045. if f, ok := providerStorageQueries[key]; ok {
  1046. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1047. } else {
  1048. localStorageQuery = ""
  1049. }
  1050. }
  1051. if localStorageQuery != "" {
  1052. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1053. }
  1054. cfg := pds.promConfig
  1055. durStr := timeutil.DurationString(step)
  1056. if durStr == "" {
  1057. panic("failed to parse duration string passed to QueryClusterTotalByProvider")
  1058. }
  1059. clusterTotalQuery := fmt.Sprintf(queryTotal, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterLabel, localStorageQuery)
  1060. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1061. return source.NewFuture(source.DecodeClusterTotalResult, ctx.QueryRange(clusterTotalQuery, start, end, step))
  1062. }
  1063. func (pds *PrometheusDataSource) QueryClusterNodes(start, end time.Time, step time.Duration) *source.Future[source.ClusterNodesResult] {
  1064. return pds.QueryClusterNodesByProvider("", start, end, step)
  1065. }
  1066. func (pds *PrometheusDataSource) QueryClusterNodesByProvider(provider string, start, end time.Time, step time.Duration) *source.Future[source.ClusterNodesResult] {
  1067. const queryNodes = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 %s`
  1068. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), localStorageQuery)
  1069. var localStorageQuery string
  1070. if provider != "" {
  1071. key := strings.ToLower(provider)
  1072. if f, ok := providerStorageQueries[key]; ok {
  1073. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1074. } else {
  1075. localStorageQuery = ""
  1076. }
  1077. }
  1078. if localStorageQuery != "" {
  1079. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1080. }
  1081. cfg := pds.promConfig
  1082. durStr := timeutil.DurationString(step)
  1083. if durStr == "" {
  1084. panic("failed to parse duration string passed to QueryClusterNodesByProvider")
  1085. }
  1086. clusterNodesCostQuery := fmt.Sprintf(queryNodes, cfg.ClusterFilter, cfg.ClusterLabel, localStorageQuery)
  1087. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1088. return source.NewFuture(source.DecodeClusterNodesResult, ctx.QueryRange(clusterNodesCostQuery, start, end, step))
  1089. }
  1090. // AllocationMetricQuerier
  1091. func (pds *PrometheusDataSource) QueryPods(start, end time.Time) *source.Future[source.PodsResult] {
  1092. const queryFmtPods = `avg(kube_pod_container_status_running{%s} != 0) by (pod, namespace, %s)[%s:%s]`
  1093. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1094. cfg := pds.promConfig
  1095. resolution := cfg.DataResolution
  1096. resStr := timeutil.DurationString(resolution)
  1097. durStr := timeutil.DurationString(end.Sub(start))
  1098. if durStr == "" {
  1099. panic("failed to parse duration string passed to QueryPods")
  1100. }
  1101. queryPods := fmt.Sprintf(queryFmtPods, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1102. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1103. return source.NewFuture(source.DecodePodsResult, ctx.QueryAtTime(queryPods, end))
  1104. }
  1105. func (pds *PrometheusDataSource) QueryPodsUID(start, end time.Time) *source.Future[source.PodsResult] {
  1106. const queryFmtPodsUID = `avg(kube_pod_container_status_running{%s} != 0) by (pod, namespace, uid, %s)[%s:%s]`
  1107. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1108. cfg := pds.promConfig
  1109. resolution := cfg.DataResolution
  1110. resStr := timeutil.DurationString(resolution)
  1111. durStr := timeutil.DurationString(end.Sub(start))
  1112. if durStr == "" {
  1113. panic("failed to parse duration string passed to QueryPodsUID")
  1114. }
  1115. queryPodsUID := fmt.Sprintf(queryFmtPodsUID, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1116. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1117. return source.NewFuture(source.DecodePodsResult, ctx.QueryAtTime(queryPodsUID, end))
  1118. }
  1119. func (pds *PrometheusDataSource) QueryRAMBytesAllocated(start, end time.Time) *source.Future[source.RAMBytesAllocatedResult] {
  1120. const queryFmtRAMBytesAllocated = `avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s, provider_id)`
  1121. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1122. cfg := pds.promConfig
  1123. durStr := timeutil.DurationString(end.Sub(start))
  1124. if durStr == "" {
  1125. panic("failed to parse duration string passed to QueryRAMBytesAllocated")
  1126. }
  1127. queryRAMBytesAllocated := fmt.Sprintf(queryFmtRAMBytesAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1128. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1129. return source.NewFuture(source.DecodeRAMBytesAllocatedResult, ctx.QueryAtTime(queryRAMBytesAllocated, end))
  1130. }
  1131. func (pds *PrometheusDataSource) QueryRAMRequests(start, end time.Time) *source.Future[source.RAMRequestsResult] {
  1132. const queryFmtRAMRequests = `avg(avg_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1133. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1134. cfg := pds.promConfig
  1135. durStr := timeutil.DurationString(end.Sub(start))
  1136. if durStr == "" {
  1137. panic("failed to parse duration string passed to QueryRAMRequests")
  1138. }
  1139. queryRAMRequests := fmt.Sprintf(queryFmtRAMRequests, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1140. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1141. return source.NewFuture(source.DecodeRAMRequestsResult, ctx.QueryAtTime(queryRAMRequests, end))
  1142. }
  1143. func (pds *PrometheusDataSource) QueryRAMUsageAvg(start, end time.Time) *source.Future[source.RAMUsageAvgResult] {
  1144. const queryFmtRAMUsageAvg = `avg(avg_over_time(container_memory_working_set_bytes{container!="", container_name!="POD", container!="POD", %s}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  1145. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1146. cfg := pds.promConfig
  1147. durStr := timeutil.DurationString(end.Sub(start))
  1148. if durStr == "" {
  1149. panic("failed to parse duration string passed to QueryRAMUsageAvg")
  1150. }
  1151. queryRAMUsageAvg := fmt.Sprintf(queryFmtRAMUsageAvg, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1152. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1153. return source.NewFuture(source.DecodeRAMUsageAvgResult, ctx.QueryAtTime(queryRAMUsageAvg, end))
  1154. }
  1155. func (pds *PrometheusDataSource) QueryRAMUsageMax(start, end time.Time) *source.Future[source.RAMUsageMaxResult] {
  1156. const queryFmtRAMUsageMax = `max(max_over_time(container_memory_working_set_bytes{container!="", container_name!="POD", container!="POD", %s}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  1157. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1158. cfg := pds.promConfig
  1159. durStr := timeutil.DurationString(end.Sub(start))
  1160. if durStr == "" {
  1161. panic("failed to parse duration string passed to QueryRAMUsageMax")
  1162. }
  1163. queryRAMUsageMax := fmt.Sprintf(queryFmtRAMUsageMax, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1164. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1165. return source.NewFuture(source.DecodeRAMUsageMaxResult, ctx.QueryAtTime(queryRAMUsageMax, end))
  1166. }
  1167. func (pds *PrometheusDataSource) QueryCPUCoresAllocated(start, end time.Time) *source.Future[source.CPUCoresAllocatedResult] {
  1168. const queryFmtCPUCoresAllocated = `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1169. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1170. cfg := pds.promConfig
  1171. durStr := timeutil.DurationString(end.Sub(start))
  1172. if durStr == "" {
  1173. panic("failed to parse duration string passed to QueryCPUCoresAllocated")
  1174. }
  1175. queryCPUCoresAllocated := fmt.Sprintf(queryFmtCPUCoresAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1176. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1177. return source.NewFuture(source.DecodeCPUCoresAllocatedResult, ctx.QueryAtTime(queryCPUCoresAllocated, end))
  1178. }
  1179. func (pds *PrometheusDataSource) QueryCPURequests(start, end time.Time) *source.Future[source.CPURequestsResult] {
  1180. const queryFmtCPURequests = `avg(avg_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1181. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1182. cfg := pds.promConfig
  1183. durStr := timeutil.DurationString(end.Sub(start))
  1184. if durStr == "" {
  1185. panic("failed to parse duration string passed to QueryCPURequests")
  1186. }
  1187. queryCPURequests := fmt.Sprintf(queryFmtCPURequests, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1188. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1189. return source.NewFuture(source.DecodeCPURequestsResult, ctx.QueryAtTime(queryCPURequests, end))
  1190. }
  1191. func (pds *PrometheusDataSource) QueryCPUUsageAvg(start, end time.Time) *source.Future[source.CPUUsageAvgResult] {
  1192. const queryFmtCPUUsageAvg = `avg(rate(container_cpu_usage_seconds_total{container!="", container_name!="POD", container!="POD", %s}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  1193. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1194. cfg := pds.promConfig
  1195. durStr := timeutil.DurationString(end.Sub(start))
  1196. if durStr == "" {
  1197. panic("failed to parse duration string passed to QueryCPUUsageAvg")
  1198. }
  1199. queryCPUUsageAvg := fmt.Sprintf(queryFmtCPUUsageAvg, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1200. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1201. return source.NewFuture(source.DecodeCPUUsageAvgResult, ctx.QueryAtTime(queryCPUUsageAvg, end))
  1202. }
  1203. func (pds *PrometheusDataSource) QueryCPUUsageMax(start, end time.Time) *source.Future[source.CPUUsageMaxResult] {
  1204. // Because we use container_cpu_usage_seconds_total to calculate CPU usage
  1205. // at any given "instant" of time, we need to use an irate or rate. To then
  1206. // calculate a max (or any aggregation) we have to perform an aggregation
  1207. // query on top of an instant-by-instant maximum. Prometheus supports this
  1208. // type of query with a "subquery" [1], however it is reportedly expensive
  1209. // to make such a query. By default, Kubecost's Prometheus config includes
  1210. // a recording rule that keeps track of the instant-by-instant irate for CPU
  1211. // usage. The metric in this query is created by that recording rule.
  1212. //
  1213. // [1] https://prometheus.io/blog/2019/01/28/subquery-support/
  1214. //
  1215. // If changing the name of the recording rule, make sure to update the
  1216. // corresponding diagnostic query to avoid confusion.
  1217. const queryFmtCPUUsageMaxRecordingRule = `max(max_over_time(kubecost_container_cpu_usage_irate{%s}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  1218. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1219. // This is the subquery equivalent of the above recording rule query. It is
  1220. // more expensive, but does not require the recording rule. It should be
  1221. // used as a fallback query if the recording rule data does not exist.
  1222. //
  1223. // The parameter after the colon [:<thisone>] in the subquery affects the
  1224. // resolution of the subquery.
  1225. // The parameter after the metric ...{}[<thisone>] should be set to 2x
  1226. // the resolution, to make sure the irate always has two points to query
  1227. // in case the Prom scrape duration has been reduced to be equal to the
  1228. // ETL resolution.
  1229. const queryFmtCPUUsageMaxSubquery = `max(max_over_time(irate(container_cpu_usage_seconds_total{container!="POD", container!="", %s}[%s])[%s:%s])) by (container, pod_name, pod, namespace, instance, %s)`
  1230. // env.GetPromClusterFilter(), doubleResStr, durStr, resStr, env.GetPromClusterLabel()
  1231. cfg := pds.promConfig
  1232. durStr := timeutil.DurationString(end.Sub(start))
  1233. if durStr == "" {
  1234. panic("failed to parse duration string passed to QueryCPUUsageMax")
  1235. }
  1236. queryCPUUsageMaxRecordingRule := fmt.Sprintf(queryFmtCPUUsageMaxRecordingRule, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1237. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1238. resCPUUsageMaxRR := ctx.QueryAtTime(queryCPUUsageMaxRecordingRule, end)
  1239. resCPUUsageMax, _ := resCPUUsageMaxRR.Await()
  1240. if len(resCPUUsageMax) > 0 {
  1241. return wrapResults(queryCPUUsageMaxRecordingRule, source.DecodeCPUUsageMaxResult, resCPUUsageMax)
  1242. }
  1243. resolution := cfg.DataResolution
  1244. resStr := timeutil.DurationString(resolution)
  1245. doubleResStr := timeutil.DurationString(2 * resolution)
  1246. queryCPUUsageMaxSubquery := fmt.Sprintf(queryFmtCPUUsageMaxSubquery, cfg.ClusterFilter, doubleResStr, durStr, resStr, cfg.ClusterLabel)
  1247. return source.NewFuture(source.DecodeCPUUsageMaxResult, ctx.QueryAtTime(queryCPUUsageMaxSubquery, end))
  1248. }
  1249. func (pds *PrometheusDataSource) QueryGPUsRequested(start, end time.Time) *source.Future[source.GPUsRequestedResult] {
  1250. const queryFmtGPUsRequested = `avg(avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1251. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1252. cfg := pds.promConfig
  1253. durStr := timeutil.DurationString(end.Sub(start))
  1254. if durStr == "" {
  1255. panic("failed to parse duration string passed to QueryGPUsRequested")
  1256. }
  1257. queryGPUsRequested := fmt.Sprintf(queryFmtGPUsRequested, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1258. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1259. return source.NewFuture(source.DecodeGPUsRequestedResult, ctx.QueryAtTime(queryGPUsRequested, end))
  1260. }
  1261. func (pds *PrometheusDataSource) QueryGPUsUsageAvg(start, end time.Time) *source.Future[source.GPUsUsageAvgResult] {
  1262. const queryFmtGPUsUsageAvg = `avg(avg_over_time(DCGM_FI_PROF_GR_ENGINE_ACTIVE{container!=""}[%s])) by (container, pod, namespace, %s)`
  1263. // durStr, env.GetPromClusterLabel()
  1264. cfg := pds.promConfig
  1265. durStr := timeutil.DurationString(end.Sub(start))
  1266. if durStr == "" {
  1267. panic("failed to parse duration string passed to QueryGPUsUsageAvg")
  1268. }
  1269. queryGPUsUsageAvg := fmt.Sprintf(queryFmtGPUsUsageAvg, durStr, cfg.ClusterLabel)
  1270. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1271. return source.NewFuture(source.DecodeGPUsUsageAvgResult, ctx.QueryAtTime(queryGPUsUsageAvg, end))
  1272. }
  1273. func (pds *PrometheusDataSource) QueryGPUsUsageMax(start, end time.Time) *source.Future[source.GPUsUsageMaxResult] {
  1274. const queryFmtGPUsUsageMax = `max(max_over_time(DCGM_FI_PROF_GR_ENGINE_ACTIVE{container!=""}[%s])) by (container, pod, namespace, %s)`
  1275. // durStr, env.GetPromClusterLabel()
  1276. cfg := pds.promConfig
  1277. durStr := timeutil.DurationString(end.Sub(start))
  1278. if durStr == "" {
  1279. panic("failed to parse duration string passed to QueryGPUsUsageMax")
  1280. }
  1281. queryGPUsUsageMax := fmt.Sprintf(queryFmtGPUsUsageMax, durStr, cfg.ClusterLabel)
  1282. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1283. return source.NewFuture(source.DecodeGPUsUsageMaxResult, ctx.QueryAtTime(queryGPUsUsageMax, end))
  1284. }
  1285. func (pds *PrometheusDataSource) QueryGPUsAllocated(start, end time.Time) *source.Future[source.GPUsAllocatedResult] {
  1286. const queryFmtGPUsAllocated = `avg(avg_over_time(container_gpu_allocation{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1287. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1288. cfg := pds.promConfig
  1289. durStr := timeutil.DurationString(end.Sub(start))
  1290. if durStr == "" {
  1291. panic("failed to parse duration string passed to QueryGPUsAllocated")
  1292. }
  1293. queryGPUsAllocated := fmt.Sprintf(queryFmtGPUsAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1294. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1295. return source.NewFuture(source.DecodeGPUsAllocatedResult, ctx.QueryAtTime(queryGPUsAllocated, end))
  1296. }
  1297. func (pds *PrometheusDataSource) QueryIsGPUShared(start, end time.Time) *source.Future[source.IsGPUSharedResult] {
  1298. const queryFmtIsGPUShared = `avg(avg_over_time(kube_pod_container_resource_requests{container!="", node != "", pod != "", container!= "", unit = "integer", %s}[%s])) by (container, pod, namespace, node, resource)`
  1299. // env.GetPromClusterFilter(), durStr
  1300. cfg := pds.promConfig
  1301. durStr := timeutil.DurationString(end.Sub(start))
  1302. if durStr == "" {
  1303. panic("failed to parse duration string passed to QueryIsGPUShared")
  1304. }
  1305. queryIsGPUShared := fmt.Sprintf(queryFmtIsGPUShared, cfg.ClusterFilter, durStr)
  1306. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1307. return source.NewFuture(source.DecodeIsGPUSharedResult, ctx.QueryAtTime(queryIsGPUShared, end))
  1308. }
  1309. func (pds *PrometheusDataSource) QueryGPUInfo(start, end time.Time) *source.Future[source.GPUInfoResult] {
  1310. const queryFmtGetGPUInfo = `avg(avg_over_time(DCGM_FI_DEV_DEC_UTIL{container!="",%s}[%s])) by (container, pod, namespace, device, modelName, UUID)`
  1311. // env.GetPromClusterFilter(), durStr
  1312. cfg := pds.promConfig
  1313. durStr := timeutil.DurationString(end.Sub(start))
  1314. if durStr == "" {
  1315. panic("failed to parse duration string passed to QueryGPUInfo")
  1316. }
  1317. queryGetGPUInfo := fmt.Sprintf(queryFmtGetGPUInfo, cfg.ClusterFilter, durStr)
  1318. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1319. return source.NewFuture(source.DecodeGPUInfoResult, ctx.QueryAtTime(queryGetGPUInfo, end))
  1320. }
  1321. func (pds *PrometheusDataSource) QueryNodeCPUPricePerHr(start, end time.Time) *source.Future[source.NodeCPUPricePerHrResult] {
  1322. const queryFmtNodeCostPerCPUHr = `avg(avg_over_time(node_cpu_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1323. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1324. cfg := pds.promConfig
  1325. durStr := timeutil.DurationString(end.Sub(start))
  1326. if durStr == "" {
  1327. panic("failed to parse duration string passed to QueryNodeCPUPricePerHr")
  1328. }
  1329. queryNodeCostPerCPUHr := fmt.Sprintf(queryFmtNodeCostPerCPUHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1330. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1331. return source.NewFuture(source.DecodeNodeCPUPricePerHrResult, ctx.QueryAtTime(queryNodeCostPerCPUHr, end))
  1332. }
  1333. func (pds *PrometheusDataSource) QueryNodeRAMPricePerGiBHr(start, end time.Time) *source.Future[source.NodeRAMPricePerGiBHrResult] {
  1334. const queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1335. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1336. cfg := pds.promConfig
  1337. durStr := timeutil.DurationString(end.Sub(start))
  1338. if durStr == "" {
  1339. panic("failed to parse duration string passed to QueryNodeRAMPricePerGiBHr")
  1340. }
  1341. queryNodeCostPerRAMGiBHr := fmt.Sprintf(queryFmtNodeCostPerRAMGiBHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1342. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1343. return source.NewFuture(source.DecodeNodeRAMPricePerGiBHrResult, ctx.QueryAtTime(queryNodeCostPerRAMGiBHr, end))
  1344. }
  1345. func (pds *PrometheusDataSource) QueryNodeGPUPricePerHr(start, end time.Time) *source.Future[source.NodeGPUPricePerHrResult] {
  1346. const queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1347. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1348. cfg := pds.promConfig
  1349. durStr := timeutil.DurationString(end.Sub(start))
  1350. if durStr == "" {
  1351. panic("failed to parse duration string passed to QueryNodeGPUPricePerHr")
  1352. }
  1353. queryNodeCostPerGPUHr := fmt.Sprintf(queryFmtNodeCostPerGPUHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1354. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1355. return source.NewFuture(source.DecodeNodeGPUPricePerHrResult, ctx.QueryAtTime(queryNodeCostPerGPUHr, end))
  1356. }
  1357. func (pds *PrometheusDataSource) QueryNodeIsSpot(start, end time.Time) *source.Future[source.NodeIsSpotResult] {
  1358. const queryFmtNodeIsSpot = `avg_over_time(kubecost_node_is_spot{%s}[%s])`
  1359. //`avg_over_time(kubecost_node_is_spot{%s}[%s:%dm])`
  1360. // env.GetPromClusterFilter(), durStr)
  1361. cfg := pds.promConfig
  1362. durStr := timeutil.DurationString(end.Sub(start))
  1363. if durStr == "" {
  1364. panic("failed to parse duration string passed to QueryNodeIsSpot2")
  1365. }
  1366. queryNodeIsSpot := fmt.Sprintf(queryFmtNodeIsSpot, cfg.ClusterFilter, durStr)
  1367. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1368. return source.NewFuture(source.DecodeNodeIsSpotResult, ctx.QueryAtTime(queryNodeIsSpot, end))
  1369. }
  1370. func (pds *PrometheusDataSource) QueryPodPVCAllocation(start, end time.Time) *source.Future[source.PodPVCAllocationResult] {
  1371. const queryFmtPodPVCAllocation = `avg(avg_over_time(pod_pvc_allocation{%s}[%s])) by (persistentvolume, persistentvolumeclaim, pod, namespace, %s)`
  1372. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1373. cfg := pds.promConfig
  1374. durStr := timeutil.DurationString(end.Sub(start))
  1375. if durStr == "" {
  1376. panic("failed to parse duration string passed to QueryPodPVCAllocation")
  1377. }
  1378. queryPodPVCAllocation := fmt.Sprintf(queryFmtPodPVCAllocation, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1379. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1380. return source.NewFuture(source.DecodePodPVCAllocationResult, ctx.QueryAtTime(queryPodPVCAllocation, end))
  1381. }
  1382. func (pds *PrometheusDataSource) QueryPVCBytesRequested(start, end time.Time) *source.Future[source.PVCBytesRequestedResult] {
  1383. const queryFmtPVCBytesRequested = `avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}[%s])) by (persistentvolumeclaim, namespace, %s)`
  1384. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1385. cfg := pds.promConfig
  1386. durStr := timeutil.DurationString(end.Sub(start))
  1387. if durStr == "" {
  1388. panic("failed to parse duration string passed to QueryPVCBytesRequested")
  1389. }
  1390. queryPVCBytesRequested := fmt.Sprintf(queryFmtPVCBytesRequested, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1391. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1392. return source.NewFuture(source.DecodePVCBytesRequestedResult, ctx.QueryAtTime(queryPVCBytesRequested, end))
  1393. }
  1394. func (pds *PrometheusDataSource) QueryPVBytes(start, end time.Time) *source.Future[source.PVBytesResult] {
  1395. const queryFmtPVBytes = `avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (persistentvolume, %s)`
  1396. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1397. cfg := pds.promConfig
  1398. durStr := timeutil.DurationString(end.Sub(start))
  1399. if durStr == "" {
  1400. panic("failed to parse duration string passed to QueryPVBytes")
  1401. }
  1402. queryPVBytes := fmt.Sprintf(queryFmtPVBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1403. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1404. return source.NewFuture(source.DecodePVBytesResult, ctx.QueryAtTime(queryPVBytes, end))
  1405. }
  1406. func (pds *PrometheusDataSource) QueryPVCostPerGiBHour(start, end time.Time) *source.Future[source.PVPricePerGiBHourResult] {
  1407. const queryFmtPVCostPerGiBHour = `avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (volumename, %s)`
  1408. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1409. cfg := pds.promConfig
  1410. durStr := timeutil.DurationString(end.Sub(start))
  1411. if durStr == "" {
  1412. panic("failed to parse duration string passed to QueryPVCostPerGiBHour")
  1413. }
  1414. queryPVCostPerGiBHour := fmt.Sprintf(queryFmtPVCostPerGiBHour, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1415. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1416. return source.NewFuture(source.DecodePVPricePerGiBHourResult, ctx.QueryAtTime(queryPVCostPerGiBHour, end))
  1417. }
  1418. func (pds *PrometheusDataSource) QueryPVInfo(start, end time.Time) *source.Future[source.PVInfoResult] {
  1419. const queryFmtPVMeta = `avg(avg_over_time(kubecost_pv_info{%s}[%s])) by (%s, storageclass, persistentvolume, provider_id)`
  1420. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1421. cfg := pds.promConfig
  1422. durStr := timeutil.DurationString(end.Sub(start))
  1423. if durStr == "" {
  1424. panic("failed to parse duration string passed to QueryPVMeta")
  1425. }
  1426. queryPVMeta := fmt.Sprintf(queryFmtPVMeta, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1427. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1428. return source.NewFuture(source.DecodePVInfoResult, ctx.QueryAtTime(queryPVMeta, end))
  1429. }
  1430. func (pds *PrometheusDataSource) QueryNetZoneGiB(start, end time.Time) *source.Future[source.NetZoneGiBResult] {
  1431. const queryFmtNetZoneGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", same_zone="false", same_region="true", %s}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  1432. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1433. cfg := pds.promConfig
  1434. durStr := timeutil.DurationString(end.Sub(start))
  1435. if durStr == "" {
  1436. panic("failed to parse duration string passed to QueryNetZoneGiB")
  1437. }
  1438. queryNetZoneGiB := fmt.Sprintf(queryFmtNetZoneGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1439. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1440. return source.NewFuture(source.DecodeNetZoneGiBResult, ctx.QueryAtTime(queryNetZoneGiB, end))
  1441. }
  1442. func (pds *PrometheusDataSource) QueryNetZonePricePerGiB(start, end time.Time) *source.Future[source.NetZonePricePerGiBResult] {
  1443. const queryFmtNetZoneCostPerGiB = `avg(avg_over_time(kubecost_network_zone_egress_cost{%s}[%s])) by (%s)`
  1444. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1445. cfg := pds.promConfig
  1446. durStr := timeutil.DurationString(end.Sub(start))
  1447. if durStr == "" {
  1448. panic("failed to parse duration string passed to QueryNetZonePricePerGiB")
  1449. }
  1450. queryNetZoneCostPerGiB := fmt.Sprintf(queryFmtNetZoneCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1451. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1452. return source.NewFuture(source.DecodeNetZonePricePerGiBResult, ctx.QueryAtTime(queryNetZoneCostPerGiB, end))
  1453. }
  1454. func (pds *PrometheusDataSource) QueryNetRegionGiB(start, end time.Time) *source.Future[source.NetRegionGiBResult] {
  1455. const queryFmtNetRegionGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", same_zone="false", same_region="false", %s}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  1456. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1457. cfg := pds.promConfig
  1458. durStr := timeutil.DurationString(end.Sub(start))
  1459. if durStr == "" {
  1460. panic("failed to parse duration string passed to QueryNetRegionGiB")
  1461. }
  1462. queryNetRegionGiB := fmt.Sprintf(queryFmtNetRegionGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1463. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1464. return source.NewFuture(source.DecodeNetRegionGiBResult, ctx.QueryAtTime(queryNetRegionGiB, end))
  1465. }
  1466. func (pds *PrometheusDataSource) QueryNetRegionPricePerGiB(start, end time.Time) *source.Future[source.NetRegionPricePerGiBResult] {
  1467. const queryFmtNetRegionCostPerGiB = `avg(avg_over_time(kubecost_network_region_egress_cost{%s}[%s])) by (%s)`
  1468. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1469. cfg := pds.promConfig
  1470. durStr := timeutil.DurationString(end.Sub(start))
  1471. if durStr == "" {
  1472. panic("failed to parse duration string passed to QueryNetRegionPricePerGiB")
  1473. }
  1474. queryNetRegionCostPerGiB := fmt.Sprintf(queryFmtNetRegionCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1475. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1476. return source.NewFuture(source.DecodeNetRegionPricePerGiBResult, ctx.QueryAtTime(queryNetRegionCostPerGiB, end))
  1477. }
  1478. func (pds *PrometheusDataSource) QueryNetInternetGiB(start, end time.Time) *source.Future[source.NetInternetGiBResult] {
  1479. const queryFmtNetInternetGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  1480. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1481. cfg := pds.promConfig
  1482. durStr := timeutil.DurationString(end.Sub(start))
  1483. if durStr == "" {
  1484. panic("failed to parse duration string passed to QueryNetInternetGiB")
  1485. }
  1486. queryNetInternetGiB := fmt.Sprintf(queryFmtNetInternetGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1487. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1488. return source.NewFuture(source.DecodeNetInternetGiBResult, ctx.QueryAtTime(queryNetInternetGiB, end))
  1489. }
  1490. func (pds *PrometheusDataSource) QueryNetInternetPricePerGiB(start, end time.Time) *source.Future[source.NetInternetPricePerGiBResult] {
  1491. const queryFmtNetInternetCostPerGiB = `avg(avg_over_time(kubecost_network_internet_egress_cost{%s}[%s])) by (%s)`
  1492. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1493. cfg := pds.promConfig
  1494. durStr := timeutil.DurationString(end.Sub(start))
  1495. if durStr == "" {
  1496. panic("failed to parse duration string passed to QueryNetInternetPricePerGiB")
  1497. }
  1498. queryNetInternetCostPerGiB := fmt.Sprintf(queryFmtNetInternetCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1499. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1500. return source.NewFuture(source.DecodeNetInternetPricePerGiBResult, ctx.QueryAtTime(queryNetInternetCostPerGiB, end))
  1501. }
  1502. func (pds *PrometheusDataSource) QueryNetReceiveBytes(start, end time.Time) *source.Future[source.NetReceiveBytesResult] {
  1503. const queryFmtNetReceiveBytes = `sum(increase(container_network_receive_bytes_total{pod!="", %s}[%s])) by (pod_name, pod, namespace, %s)`
  1504. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1505. cfg := pds.promConfig
  1506. durStr := timeutil.DurationString(end.Sub(start))
  1507. if durStr == "" {
  1508. panic("failed to parse duration string passed to QueryNetReceiveBytes")
  1509. }
  1510. queryNetReceiveBytes := fmt.Sprintf(queryFmtNetReceiveBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1511. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1512. return source.NewFuture(source.DecodeNetReceiveBytesResult, ctx.QueryAtTime(queryNetReceiveBytes, end))
  1513. }
  1514. func (pds *PrometheusDataSource) QueryNetTransferBytes(start, end time.Time) *source.Future[source.NetTransferBytesResult] {
  1515. const queryFmtNetTransferBytes = `sum(increase(container_network_transmit_bytes_total{pod!="", %s}[%s])) by (pod_name, pod, namespace, %s)`
  1516. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1517. cfg := pds.promConfig
  1518. durStr := timeutil.DurationString(end.Sub(start))
  1519. if durStr == "" {
  1520. panic("failed to parse duration string passed to QueryNetTransferBytes")
  1521. }
  1522. queryNetTransferBytes := fmt.Sprintf(queryFmtNetTransferBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1523. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1524. return source.NewFuture(source.DecodeNetTransferBytesResult, ctx.QueryAtTime(queryNetTransferBytes, end))
  1525. }
  1526. func (pds *PrometheusDataSource) QueryNamespaceLabels(start, end time.Time) *source.Future[source.NamespaceLabelsResult] {
  1527. const queryFmtNamespaceLabels = `avg_over_time(kube_namespace_labels{%s}[%s])`
  1528. // env.GetPromClusterFilter(), durStr
  1529. cfg := pds.promConfig
  1530. durStr := timeutil.DurationString(end.Sub(start))
  1531. if durStr == "" {
  1532. panic("failed to parse duration string passed to QueryNamespaceLabels")
  1533. }
  1534. queryNamespaceLabels := fmt.Sprintf(queryFmtNamespaceLabels, cfg.ClusterFilter, durStr)
  1535. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1536. return source.NewFuture(source.DecodeNamespaceLabelsResult, ctx.QueryAtTime(queryNamespaceLabels, end))
  1537. }
  1538. func (pds *PrometheusDataSource) QueryNamespaceAnnotations(start, end time.Time) *source.Future[source.NamespaceAnnotationsResult] {
  1539. const queryFmtNamespaceAnnotations = `avg_over_time(kube_namespace_annotations{%s}[%s])`
  1540. // env.GetPromClusterFilter(), durStr
  1541. cfg := pds.promConfig
  1542. durStr := timeutil.DurationString(end.Sub(start))
  1543. if durStr == "" {
  1544. panic("failed to parse duration string passed to QueryNamespaceAnnotations")
  1545. }
  1546. queryNamespaceAnnotations := fmt.Sprintf(queryFmtNamespaceAnnotations, cfg.ClusterFilter, durStr)
  1547. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1548. return source.NewFuture(source.DecodeNamespaceAnnotationsResult, ctx.QueryAtTime(queryNamespaceAnnotations, end))
  1549. }
  1550. func (pds *PrometheusDataSource) QueryPodLabels(start, end time.Time) *source.Future[source.PodLabelsResult] {
  1551. const queryFmtPodLabels = `avg_over_time(kube_pod_labels{%s}[%s])`
  1552. // env.GetPromClusterFilter(), durStr
  1553. cfg := pds.promConfig
  1554. durStr := timeutil.DurationString(end.Sub(start))
  1555. if durStr == "" {
  1556. panic("failed to parse duration string passed to QueryPodLabels")
  1557. }
  1558. queryPodLabels := fmt.Sprintf(queryFmtPodLabels, cfg.ClusterFilter, durStr)
  1559. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1560. return source.NewFuture(source.DecodePodLabelsResult, ctx.QueryAtTime(queryPodLabels, end))
  1561. }
  1562. func (pds *PrometheusDataSource) QueryPodAnnotations(start, end time.Time) *source.Future[source.PodAnnotationsResult] {
  1563. const queryFmtPodAnnotations = `avg_over_time(kube_pod_annotations{%s}[%s])`
  1564. // env.GetPromClusterFilter(), durStr
  1565. cfg := pds.promConfig
  1566. durStr := timeutil.DurationString(end.Sub(start))
  1567. if durStr == "" {
  1568. panic("failed to parse duration string passed to QueryPodAnnotations")
  1569. }
  1570. queryPodAnnotations := fmt.Sprintf(queryFmtPodAnnotations, cfg.ClusterFilter, durStr)
  1571. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1572. return source.NewFuture(source.DecodePodAnnotationsResult, ctx.QueryAtTime(queryPodAnnotations, end))
  1573. }
  1574. func (pds *PrometheusDataSource) QueryServiceLabels(start, end time.Time) *source.Future[source.ServiceLabelsResult] {
  1575. const queryFmtServiceLabels = `avg_over_time(service_selector_labels{%s}[%s])`
  1576. // env.GetPromClusterFilter(), durStr
  1577. cfg := pds.promConfig
  1578. durStr := timeutil.DurationString(end.Sub(start))
  1579. if durStr == "" {
  1580. panic("failed to parse duration string passed to QueryServiceLabels")
  1581. }
  1582. queryServiceLabels := fmt.Sprintf(queryFmtServiceLabels, cfg.ClusterFilter, durStr)
  1583. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1584. return source.NewFuture(source.DecodeServiceLabelsResult, ctx.QueryAtTime(queryServiceLabels, end))
  1585. }
  1586. func (pds *PrometheusDataSource) QueryDeploymentLabels(start, end time.Time) *source.Future[source.DeploymentLabelsResult] {
  1587. const queryFmtDeploymentLabels = `avg_over_time(deployment_match_labels{%s}[%s])`
  1588. // env.GetPromClusterFilter(), durStr
  1589. cfg := pds.promConfig
  1590. durStr := timeutil.DurationString(end.Sub(start))
  1591. if durStr == "" {
  1592. panic("failed to parse duration string passed to QueryNamespaceAnnotations")
  1593. }
  1594. queryDeploymentLabels := fmt.Sprintf(queryFmtDeploymentLabels, cfg.ClusterFilter, durStr)
  1595. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1596. return source.NewFuture(source.DecodeDeploymentLabelsResult, ctx.QueryAtTime(queryDeploymentLabels, end))
  1597. }
  1598. func (pds *PrometheusDataSource) QueryStatefulSetLabels(start, end time.Time) *source.Future[source.StatefulSetLabelsResult] {
  1599. const queryFmtStatefulSetLabels = `avg_over_time(statefulSet_match_labels{%s}[%s])`
  1600. // env.GetPromClusterFilter(), durStr
  1601. cfg := pds.promConfig
  1602. durStr := timeutil.DurationString(end.Sub(start))
  1603. if durStr == "" {
  1604. panic("failed to parse duration string passed to QueryStatefulSetLabels")
  1605. }
  1606. queryStatefulSetLabels := fmt.Sprintf(queryFmtStatefulSetLabels, cfg.ClusterFilter, durStr)
  1607. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1608. return source.NewFuture(source.DecodeStatefulSetLabelsResult, ctx.QueryAtTime(queryStatefulSetLabels, end))
  1609. }
  1610. func (pds *PrometheusDataSource) QueryDaemonSetLabels(start, end time.Time) *source.Future[source.DaemonSetLabelsResult] {
  1611. const queryFmtDaemonSetLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet", %s}[%s])) by (pod, owner_name, namespace, %s)`
  1612. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1613. cfg := pds.promConfig
  1614. durStr := timeutil.DurationString(end.Sub(start))
  1615. if durStr == "" {
  1616. panic("failed to parse duration string passed to QueryDaemonSetLabels")
  1617. }
  1618. queryDaemonSetLabels := fmt.Sprintf(queryFmtDaemonSetLabels, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1619. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1620. return source.NewFuture(source.DecodeDaemonSetLabelsResult, ctx.QueryAtTime(queryDaemonSetLabels, end))
  1621. }
  1622. func (pds *PrometheusDataSource) QueryJobLabels(start, end time.Time) *source.Future[source.JobLabelsResult] {
  1623. const queryFmtJobLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="Job", %s}[%s])) by (pod, owner_name, namespace ,%s)`
  1624. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1625. cfg := pds.promConfig
  1626. durStr := timeutil.DurationString(end.Sub(start))
  1627. if durStr == "" {
  1628. panic("failed to parse duration string passed to QueryJobLabels")
  1629. }
  1630. queryJobLabels := fmt.Sprintf(queryFmtJobLabels, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1631. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1632. return source.NewFuture(source.DecodeJobLabelsResult, ctx.QueryAtTime(queryJobLabels, end))
  1633. }
  1634. func (pds *PrometheusDataSource) QueryPodsWithReplicaSetOwner(start, end time.Time) *source.Future[source.PodsWithReplicaSetOwnerResult] {
  1635. const queryFmtPodsWithReplicaSetOwner = `sum(avg_over_time(kube_pod_owner{owner_kind="ReplicaSet", %s}[%s])) by (pod, owner_name, namespace ,%s)`
  1636. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1637. cfg := pds.promConfig
  1638. durStr := timeutil.DurationString(end.Sub(start))
  1639. if durStr == "" {
  1640. panic("failed to parse duration string passed to QueryPodsWithReplicaSetOwner")
  1641. }
  1642. queryPodsWithReplicaSetOwner := fmt.Sprintf(queryFmtPodsWithReplicaSetOwner, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1643. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1644. return source.NewFuture(source.DecodePodsWithReplicaSetOwnerResult, ctx.QueryAtTime(queryPodsWithReplicaSetOwner, end))
  1645. }
  1646. func (pds *PrometheusDataSource) QueryReplicaSetsWithoutOwners(start, end time.Time) *source.Future[source.ReplicaSetsWithoutOwnersResult] {
  1647. const queryFmtReplicaSetsWithoutOwners = `avg(avg_over_time(kube_replicaset_owner{owner_kind="<none>", owner_name="<none>", %s}[%s])) by (replicaset, namespace, %s)`
  1648. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1649. cfg := pds.promConfig
  1650. durStr := timeutil.DurationString(end.Sub(start))
  1651. if durStr == "" {
  1652. panic("failed to parse duration string passed to QueryReplicaSetsWithoutOwners")
  1653. }
  1654. queryReplicaSetsWithoutOwners := fmt.Sprintf(queryFmtReplicaSetsWithoutOwners, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1655. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1656. return source.NewFuture(source.DecodeReplicaSetsWithoutOwnersResult, ctx.QueryAtTime(queryReplicaSetsWithoutOwners, end))
  1657. }
  1658. func (pds *PrometheusDataSource) QueryReplicaSetsWithRollout(start, end time.Time) *source.Future[source.ReplicaSetsWithRolloutResult] {
  1659. const queryFmtReplicaSetsWithRolloutOwner = `avg(avg_over_time(kube_replicaset_owner{owner_kind="Rollout", %s}[%s])) by (replicaset, namespace, owner_kind, owner_name, %s)`
  1660. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1661. cfg := pds.promConfig
  1662. durStr := timeutil.DurationString(end.Sub(start))
  1663. if durStr == "" {
  1664. panic("failed to parse duration string passed to QueryReplicaSetsWithRollout")
  1665. }
  1666. queryReplicaSetsWithRolloutOwner := fmt.Sprintf(queryFmtReplicaSetsWithRolloutOwner, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1667. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1668. return source.NewFuture(source.DecodeReplicaSetsWithRolloutResult, ctx.QueryAtTime(queryReplicaSetsWithRolloutOwner, end))
  1669. }
  1670. func (pds *PrometheusDataSource) QueryDataCoverage(limitDays int) (time.Time, time.Time, error) {
  1671. const (
  1672. queryFmtOldestSample = `min_over_time(timestamp(group(node_cpu_hourly_cost{%s}))[%s:%s])`
  1673. queryFmtNewestSample = `max_over_time(timestamp(group(node_cpu_hourly_cost{%s}))[%s:%s])`
  1674. )
  1675. cfg := pds.promConfig
  1676. now := time.Now()
  1677. durStr := fmt.Sprintf("%dd", limitDays)
  1678. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1679. queryOldest := fmt.Sprintf(queryFmtOldestSample, cfg.ClusterFilter, durStr, "1h")
  1680. resOldestFut := ctx.QueryAtTime(queryOldest, now)
  1681. resOldest, err := resOldestFut.Await()
  1682. if err != nil {
  1683. return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
  1684. }
  1685. if len(resOldest) == 0 || len(resOldest[0].Values) == 0 {
  1686. return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
  1687. }
  1688. oldest := time.Unix(int64(resOldest[0].Values[0].Value), 0)
  1689. queryNewest := fmt.Sprintf(queryFmtNewestSample, cfg.ClusterFilter, durStr, "1h")
  1690. resNewestFut := ctx.QueryAtTime(queryNewest, now)
  1691. resNewest, err := resNewestFut.Await()
  1692. if err != nil {
  1693. return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: %w", err)
  1694. }
  1695. if len(resNewest) == 0 || len(resNewest[0].Values) == 0 {
  1696. return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: %w", err)
  1697. }
  1698. newest := time.Unix(int64(resNewest[0].Values[0].Value), 0)
  1699. return oldest, newest, nil
  1700. }
  1701. func newEmptyResult[T any](decoder source.ResultDecoder[T]) *source.Future[T] {
  1702. ch := make(source.QueryResultsChan)
  1703. go func() {
  1704. results := source.NewQueryResults("")
  1705. ch <- results
  1706. }()
  1707. return source.NewFuture(decoder, ch)
  1708. }
  1709. func wrapResults[T any](query string, decoder source.ResultDecoder[T], results []*source.QueryResult) *source.Future[T] {
  1710. ch := make(source.QueryResultsChan)
  1711. go func() {
  1712. r := source.NewQueryResults(query)
  1713. r.Results = results
  1714. ch <- r
  1715. }()
  1716. return source.NewFuture(decoder, ch)
  1717. }
  1718. func snapResolutionMinute(res time.Duration) time.Duration {
  1719. resMins := int64(math.Trunc(res.Minutes()))
  1720. if resMins <= 0 {
  1721. resMins = 1
  1722. }
  1723. return time.Duration(resMins) * time.Minute
  1724. }
  1725. func formatResolutionMinutes(resMins int64) string {
  1726. if resMins%60 == 0 {
  1727. return fmt.Sprintf("%dh", resMins/60)
  1728. }
  1729. return fmt.Sprintf("%dm", resMins)
  1730. }