2
0

datasource.go 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902
  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/pkg/prom"
  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(prom.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) RegisterEndPoints(router *httprouter.Router) {
  433. // endpoints migrated from server
  434. router.GET("/validatePrometheus", pds.prometheusMetadata)
  435. router.GET("/prometheusRecordingRules", pds.prometheusRecordingRules)
  436. router.GET("/prometheusConfig", pds.prometheusConfig)
  437. router.GET("/prometheusTargets", pds.prometheusTargets)
  438. router.GET("/status", pds.status)
  439. // prom query proxies
  440. router.GET("/prometheusQuery", pds.prometheusQuery)
  441. router.GET("/prometheusQueryRange", pds.prometheusQueryRange)
  442. router.GET("/thanosQuery", pds.thanosQuery)
  443. router.GET("/thanosQueryRange", pds.thanosQueryRange)
  444. // diagnostics
  445. router.GET("/diagnostics/requestQueue", pds.prometheusQueueState)
  446. router.GET("/diagnostics/prometheusMetrics", pds.prometheusMetrics)
  447. }
  448. func (pds *PrometheusDataSource) RefreshInterval() time.Duration {
  449. return pds.promConfig.ScrapeInterval
  450. }
  451. func (pds *PrometheusDataSource) BatchDuration() time.Duration {
  452. return pds.promConfig.MaxQueryDuration
  453. }
  454. func (pds *PrometheusDataSource) Resolution() time.Duration {
  455. return pds.promConfig.DataResolution
  456. }
  457. func (pds *PrometheusDataSource) QueryRAMUsage(window string, offset string) source.QueryResultsChan {
  458. const ramUsageQuery = `avg(
  459. label_replace(
  460. label_replace(
  461. label_replace(
  462. sum_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
  463. ), "container_name", "$1", "container", "(.+)"
  464. ), "pod_name", "$1", "pod", "(.+)"
  465. )
  466. ) by (namespace, container_name, pod_name, node, %s)`
  467. // env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  468. if offset != "" && !strings.Contains(offset, "offset") {
  469. offset = fmt.Sprintf("offset %s", offset)
  470. }
  471. cfg := pds.promConfig
  472. queryRAMUsage := fmt.Sprintf(ramUsageQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  473. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  474. return ctx.Query(queryRAMUsage)
  475. }
  476. func (pds *PrometheusDataSource) QueryCPUUsage(window string, offset string) source.QueryResultsChan {
  477. const cpuUsageQuery = `avg(
  478. label_replace(
  479. label_replace(
  480. label_replace(
  481. rate(
  482. container_cpu_usage_seconds_total{container!="", container!="POD", instance!="", %s}[%s] %s
  483. ), "node", "$1", "instance", "(.+)"
  484. ), "container_name", "$1", "container", "(.+)"
  485. ), "pod_name", "$1", "pod", "(.+)"
  486. )
  487. ) by (namespace, container_name, pod_name, node, %s)`
  488. // env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
  489. if offset != "" && !strings.Contains(offset, "offset") {
  490. offset = fmt.Sprintf("offset %s", offset)
  491. }
  492. cfg := pds.promConfig
  493. queryCPUUsage := fmt.Sprintf(cpuUsageQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  494. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  495. return ctx.Query(queryCPUUsage)
  496. }
  497. func (pds *PrometheusDataSource) QueryNetworkInZoneRequests(window string, offset string) source.QueryResultsChan {
  498. const zoneNetworkUsageQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  499. // env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  500. if offset != "" && !strings.Contains(offset, "offset") {
  501. offset = fmt.Sprintf("offset %s", offset)
  502. }
  503. cfg := pds.promConfig
  504. queryZoneNetworkUsage := fmt.Sprintf(zoneNetworkUsageQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  505. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  506. return ctx.Query(queryZoneNetworkUsage)
  507. }
  508. func (pds *PrometheusDataSource) QueryNetworkInRegionRequests(window string, offset string) source.QueryResultsChan {
  509. const regionNetworkUsageQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  510. // env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  511. if offset != "" && !strings.Contains(offset, "offset") {
  512. offset = fmt.Sprintf("offset %s", offset)
  513. }
  514. cfg := pds.promConfig
  515. queryRegionNetworkUsage := fmt.Sprintf(regionNetworkUsageQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  516. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  517. return ctx.Query(queryRegionNetworkUsage)
  518. }
  519. func (pds *PrometheusDataSource) QueryNetworkInternetRequests(window string, offset string) source.QueryResultsChan {
  520. const internetNetworkUsageQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  521. // env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
  522. cfg := pds.promConfig
  523. queryInternetNetworkUsage := fmt.Sprintf(internetNetworkUsageQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  524. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  525. return ctx.Query(queryInternetNetworkUsage)
  526. }
  527. func (pds *PrometheusDataSource) QueryNormalization(window string, offset string) source.QueryResultsChan {
  528. const normalizationQuery = `max(count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[%s] %s))`
  529. // env.GetPromClusterFilter(), window, offset)
  530. if offset != "" && !strings.Contains(offset, "offset") {
  531. offset = fmt.Sprintf("offset %s", offset)
  532. }
  533. cfg := pds.promConfig
  534. queryNormalization := fmt.Sprintf(normalizationQuery, cfg.ClusterFilter, window, offset)
  535. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  536. return ctx.Query(queryNormalization)
  537. }
  538. func (pds *PrometheusDataSource) QueryHistoricalCPUCost(window string, offset string) source.QueryResultsChan {
  539. const historicalCPUCostQuery = `avg(avg_over_time(node_cpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`
  540. // env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  541. if offset != "" && !strings.Contains(offset, "offset") {
  542. offset = fmt.Sprintf("offset %s", offset)
  543. }
  544. cfg := pds.promConfig
  545. queryHistoricalCPUCost := fmt.Sprintf(historicalCPUCostQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  546. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  547. return ctx.Query(queryHistoricalCPUCost)
  548. }
  549. func (pds *PrometheusDataSource) QueryHistoricalRAMCost(window string, offset string) source.QueryResultsChan {
  550. const historicalRAMCostQuery = `avg(avg_over_time(node_ram_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`
  551. // env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  552. if offset != "" && !strings.Contains(offset, "offset") {
  553. offset = fmt.Sprintf("offset %s", offset)
  554. }
  555. cfg := pds.promConfig
  556. queryHistoricalRAMCost := fmt.Sprintf(historicalRAMCostQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  557. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  558. return ctx.Query(queryHistoricalRAMCost)
  559. }
  560. func (pds *PrometheusDataSource) QueryHistoricalGPUCost(window string, offset string) source.QueryResultsChan {
  561. const historicalGPUCostQuery = `avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`
  562. // env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
  563. if offset != "" && !strings.Contains(offset, "offset") {
  564. offset = fmt.Sprintf("offset %s", offset)
  565. }
  566. cfg := pds.promConfig
  567. queryHistoricalGPUCost := fmt.Sprintf(historicalGPUCostQuery, cfg.ClusterFilter, window, offset, cfg.ClusterLabel)
  568. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  569. return ctx.Query(queryHistoricalGPUCost)
  570. }
  571. func (pds *PrometheusDataSource) QueryHistoricalPodLabels(window string, offset string) source.QueryResultsChan {
  572. const historicalPodLabelsQuery = `kube_pod_labels{%s}[%s] %s`
  573. // env.GetPromClusterFilter(), window, offset
  574. if offset != "" && !strings.Contains(offset, "offset") {
  575. offset = fmt.Sprintf("offset %s", offset)
  576. }
  577. cfg := pds.promConfig
  578. queryHistoricalPodLabels := fmt.Sprintf(historicalPodLabelsQuery, cfg.ClusterFilter, window, offset)
  579. ctx := pds.promContexts.NewNamedContext(ComputeCostDataContextName)
  580. return ctx.Query(queryHistoricalPodLabels)
  581. }
  582. func (pds *PrometheusDataSource) QueryRAMRequestsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  583. const ramRequestsQuery = `avg(
  584. label_replace(
  585. label_replace(
  586. sum_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="",container!="POD", node!="", %s}[%s] %s)
  587. , "container_name","$1","container","(.+)"
  588. ), "pod_name","$1","pod","(.+)"
  589. )
  590. ) by (namespace,container_name,pod_name,node,%s)`
  591. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  592. cfg := pds.promConfig
  593. resolution = snapResolutionMinute(resolution)
  594. resMins := int64(resolution.Minutes())
  595. resStr := formatResolutionMinutes(resMins)
  596. queryRAMRequests := fmt.Sprintf(ramRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  597. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  598. return ctx.QueryRange(queryRAMRequests, start, end, resolution)
  599. }
  600. func (pds *PrometheusDataSource) QueryRAMUsageOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  601. const ramUsageQuery = `avg(
  602. label_replace(
  603. label_replace(
  604. label_replace(
  605. sum_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
  606. ), "container_name", "$1", "container", "(.+)"
  607. ), "pod_name", "$1", "pod", "(.+)"
  608. )
  609. ) by (namespace, container_name, pod_name, node, %s)`
  610. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  611. cfg := pds.promConfig
  612. resolution = snapResolutionMinute(resolution)
  613. resMins := int64(resolution.Minutes())
  614. resStr := formatResolutionMinutes(resMins)
  615. queryRAMUsage := fmt.Sprintf(ramUsageQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  616. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  617. return ctx.QueryRange(queryRAMUsage, start, end, resolution)
  618. }
  619. func (pds *PrometheusDataSource) QueryRAMAllocationOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  620. // ramAllocationByteHoursQuery yields the total byte-hour RAM allocation over the given
  621. // window, aggregated by container.
  622. // [line 3] sum_over_time(each byte) = [byte*scrape] by metric
  623. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  624. // [lines 2,4] sum(") by unique container key and multiply [byte*scrape] * [hours/scrape] for byte*hours
  625. // [lines 1,5] relabeling
  626. const ramAllocationByteHoursQuery = `
  627. label_replace(label_replace(
  628. sum(
  629. sum_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!="", %s}[%s])
  630. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  631. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  632. // env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  633. cfg := pds.promConfig
  634. resolution = snapResolutionMinute(resolution)
  635. resMins := int64(resolution.Minutes())
  636. resStr := formatResolutionMinutes(resMins)
  637. scrapeIntervalSeconds := cfg.ScrapeInterval.Seconds()
  638. queryRAMAllocationByteHours := fmt.Sprintf(ramAllocationByteHoursQuery, cfg.ClusterFilter, resStr, cfg.ClusterLabel, scrapeIntervalSeconds)
  639. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  640. return ctx.QueryRange(queryRAMAllocationByteHours, start, end, resolution)
  641. }
  642. func (pds *PrometheusDataSource) QueryCPURequestsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  643. const cpuRequestsQuery = `avg(
  644. label_replace(
  645. label_replace(
  646. sum_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="",container!="POD", node!="", %s}[%s] %s)
  647. , "container_name","$1","container","(.+)"
  648. ), "pod_name","$1","pod","(.+)"
  649. )
  650. ) by (namespace,container_name,pod_name,node,%s)`
  651. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  652. cfg := pds.promConfig
  653. resolution = snapResolutionMinute(resolution)
  654. resMins := int64(resolution.Minutes())
  655. resStr := formatResolutionMinutes(resMins)
  656. queryCPURequests := fmt.Sprintf(cpuRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  657. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  658. return ctx.QueryRange(queryCPURequests, start, end, resolution)
  659. }
  660. func (pds *PrometheusDataSource) QueryCPUUsageOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  661. const cpuUsageQuery = `avg(
  662. label_replace(
  663. label_replace(
  664. label_replace(
  665. rate(
  666. container_cpu_usage_seconds_total{container!="", container!="POD", instance!="", %s}[%s] %s
  667. ), "node", "$1", "instance", "(.+)"
  668. ), "container_name", "$1", "container", "(.+)"
  669. ), "pod_name", "$1", "pod", "(.+)"
  670. )
  671. ) by (namespace, container_name, pod_name, node, %s)`
  672. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  673. cfg := pds.promConfig
  674. resolution = snapResolutionMinute(resolution)
  675. resMins := int64(resolution.Minutes())
  676. resStr := formatResolutionMinutes(resMins)
  677. queryCPUUsage := fmt.Sprintf(cpuUsageQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  678. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  679. return ctx.QueryRange(queryCPUUsage, start, end, resolution)
  680. }
  681. func (pds *PrometheusDataSource) QueryCPUAllocationOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  682. // cpuAllocationQuery yields the total VCPU-hour CPU allocation over the given
  683. // window, aggregated by container.
  684. // [line 3] sum_over_time(each VCPU*mins in window) = [VCPU*scrape] by metric
  685. // [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
  686. // [lines 2,4] sum(") by unique container key and multiply [VCPU*scrape] * [hours/scrape] for VCPU*hours
  687. // [lines 1,5] relabeling
  688. const cpuAllocationQuery = `
  689. label_replace(label_replace(
  690. sum(
  691. sum_over_time(container_cpu_allocation{container!="",container!="POD", node!="", %s}[%s])
  692. ) by (namespace,container,pod,node,%s) * %f / 60 / 60
  693. , "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
  694. // env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  695. cfg := pds.promConfig
  696. resolution = snapResolutionMinute(resolution)
  697. resMins := int64(resolution.Minutes())
  698. resStr := formatResolutionMinutes(resMins)
  699. scrapeIntervalSeconds := cfg.ScrapeInterval.Seconds()
  700. queryCPUAllocation := fmt.Sprintf(cpuAllocationQuery, cfg.ClusterFilter, resStr, cfg.ClusterLabel, scrapeIntervalSeconds)
  701. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  702. return ctx.QueryRange(queryCPUAllocation, start, end, resolution)
  703. }
  704. func (pds *PrometheusDataSource) QueryGPURequestsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  705. const gpuRequestsQuery = `avg(
  706. label_replace(
  707. label_replace(
  708. sum_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s] %s),
  709. "container_name","$1","container","(.+)"
  710. ), "pod_name","$1","pod","(.+)"
  711. )
  712. ) by (namespace,container_name,pod_name,node,%s)`
  713. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  714. cfg := pds.promConfig
  715. resolution = snapResolutionMinute(resolution)
  716. resMins := int64(resolution.Minutes())
  717. resStr := formatResolutionMinutes(resMins)
  718. queryGPURequests := fmt.Sprintf(gpuRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  719. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  720. return ctx.QueryRange(queryGPURequests, start, end, resolution)
  721. }
  722. func (pds *PrometheusDataSource) QueryPVRequestsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  723. const pvRequestsQuery = `avg(avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, namespace, volumename, %s, kubernetes_node)
  724. *
  725. on (persistentvolumeclaim, namespace, %s, kubernetes_node) group_right(storageclass, volumename)
  726. sum(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}) by (persistentvolumeclaim, namespace, %s, kubernetes_node, kubernetes_name)) by (persistentvolumeclaim, storageclass, namespace, %s, volumename, kubernetes_node)`
  727. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel())
  728. cfg := pds.promConfig
  729. resolution = snapResolutionMinute(resolution)
  730. queryPVRequests := fmt.Sprintf(pvRequestsQuery, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterLabel, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterLabel)
  731. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  732. return ctx.QueryRange(queryPVRequests, start, end, resolution)
  733. }
  734. func (pds *PrometheusDataSource) QueryPVCAllocationOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  735. // pvcAllocationQuery yields the total byte-hour PVC allocation over the given window.
  736. // sum_over_time(each byte) = [byte*scrape] by metric *(scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by pod
  737. const pvcAllocationQuery = `sum(sum_over_time(pod_pvc_allocation{%s}[%s])) by (%s, namespace, pod, persistentvolume, persistentvolumeclaim) * %f/60/60`
  738. // env.GetPromClusterFilter(), resStr, env.GetPromClusterLabel(), scrapeIntervalSeconds)
  739. cfg := pds.promConfig
  740. resolution = snapResolutionMinute(resolution)
  741. resMins := int64(resolution.Minutes())
  742. resStr := formatResolutionMinutes(resMins)
  743. scrapeIntervalSeconds := cfg.ScrapeInterval.Seconds()
  744. queryPVCAllocation := fmt.Sprintf(pvcAllocationQuery, cfg.ClusterFilter, resStr, cfg.ClusterLabel, scrapeIntervalSeconds)
  745. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  746. return ctx.QueryRange(queryPVCAllocation, start, end, resolution)
  747. }
  748. func (pds *PrometheusDataSource) QueryPVHourlyCostOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  749. const pvHourlyCostQuery = `avg_over_time(pv_hourly_cost{%s}[%s])`
  750. // env.GetPromClusterFilter(), resStr)
  751. cfg := pds.promConfig
  752. resolution = snapResolutionMinute(resolution)
  753. resMins := int64(resolution.Minutes())
  754. resStr := formatResolutionMinutes(resMins)
  755. queryPVHourlyCost := fmt.Sprintf(pvHourlyCostQuery, cfg.ClusterFilter, resStr)
  756. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  757. return ctx.QueryRange(queryPVHourlyCost, start, end, resolution)
  758. }
  759. func (pds *PrometheusDataSource) QueryNetworkInZoneOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  760. const netZoneRequestsQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  761. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  762. cfg := pds.promConfig
  763. resolution = snapResolutionMinute(resolution)
  764. resMins := int64(resolution.Minutes())
  765. resStr := formatResolutionMinutes(resMins)
  766. queryNetZoneRequests := fmt.Sprintf(netZoneRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  767. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  768. return ctx.QueryRange(queryNetZoneRequests, start, end, resolution)
  769. }
  770. func (pds *PrometheusDataSource) QueryNetworkInRegionOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  771. const netRegionRequestsQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  772. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  773. cfg := pds.promConfig
  774. resolution = snapResolutionMinute(resolution)
  775. resMins := int64(resolution.Minutes())
  776. resStr := formatResolutionMinutes(resMins)
  777. queryNetRegionRequests := fmt.Sprintf(netRegionRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  778. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  779. return ctx.QueryRange(queryNetRegionRequests, start, end, resolution)
  780. }
  781. func (pds *PrometheusDataSource) QueryNetworkInternetOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  782. const netInternetRequestsQuery = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
  783. // env.GetPromClusterFilter(), resStr, "", env.GetPromClusterLabel())
  784. cfg := pds.promConfig
  785. resolution = snapResolutionMinute(resolution)
  786. resMins := int64(resolution.Minutes())
  787. resStr := formatResolutionMinutes(resMins)
  788. queryNetInternetRequests := fmt.Sprintf(netInternetRequestsQuery, cfg.ClusterFilter, resStr, "", cfg.ClusterLabel)
  789. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  790. return ctx.QueryRange(queryNetInternetRequests, start, end, resolution)
  791. }
  792. func (pds *PrometheusDataSource) QueryNamespaceLabelsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  793. const namespaceLabelsQuery = `avg_over_time(kube_namespace_labels{%s}[%s])`
  794. // env.GetPromClusterFilter(), resStr
  795. cfg := pds.promConfig
  796. resolution = snapResolutionMinute(resolution)
  797. resMins := int64(resolution.Minutes())
  798. resStr := formatResolutionMinutes(resMins)
  799. queryNamespaceLabels := fmt.Sprintf(namespaceLabelsQuery, cfg.ClusterFilter, resStr)
  800. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  801. return ctx.QueryRange(queryNamespaceLabels, start, end, resolution)
  802. }
  803. func (pds *PrometheusDataSource) QueryNamespaceAnnotationsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  804. const namespaceAnnotationsQuery = `avg_over_time(kube_namespace_annotations{%s}[%s])`
  805. // env.GetPromClusterFilter(), resStr
  806. cfg := pds.promConfig
  807. resolution = snapResolutionMinute(resolution)
  808. resMins := int64(resolution.Minutes())
  809. resStr := formatResolutionMinutes(resMins)
  810. queryNamespaceAnnotations := fmt.Sprintf(namespaceAnnotationsQuery, cfg.ClusterFilter, resStr)
  811. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  812. return ctx.QueryRange(queryNamespaceAnnotations, start, end, resolution)
  813. }
  814. func (pds *PrometheusDataSource) QueryPodLabelsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  815. const podLabelsQuery = `avg_over_time(kube_pod_labels{%s}[%s])`
  816. // env.GetPromClusterFilter(), resStr
  817. cfg := pds.promConfig
  818. resolution = snapResolutionMinute(resolution)
  819. resMins := int64(resolution.Minutes())
  820. resStr := formatResolutionMinutes(resMins)
  821. queryPodLabels := fmt.Sprintf(podLabelsQuery, cfg.ClusterFilter, resStr)
  822. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  823. return ctx.QueryRange(queryPodLabels, start, end, resolution)
  824. }
  825. func (pds *PrometheusDataSource) QueryPodAnnotationsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  826. const podAnnotationsQuery = `avg_over_time(kube_pod_annotations{%s}[%s])`
  827. // env.GetPromClusterFilter(), resStr
  828. cfg := pds.promConfig
  829. resolution = snapResolutionMinute(resolution)
  830. resMins := int64(resolution.Minutes())
  831. resStr := formatResolutionMinutes(resMins)
  832. queryPodAnnotations := fmt.Sprintf(podAnnotationsQuery, cfg.ClusterFilter, resStr)
  833. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  834. return ctx.QueryRange(queryPodAnnotations, start, end, resolution)
  835. }
  836. func (pds *PrometheusDataSource) QueryServiceLabelsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  837. const serviceLabelsQuery = `avg_over_time(service_selector_labels{%s}[%s])`
  838. // env.GetPromClusterFilter(), resStr
  839. cfg := pds.promConfig
  840. resolution = snapResolutionMinute(resolution)
  841. resMins := int64(resolution.Minutes())
  842. resStr := formatResolutionMinutes(resMins)
  843. queryServiceLabels := fmt.Sprintf(serviceLabelsQuery, cfg.ClusterFilter, resStr)
  844. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  845. return ctx.QueryRange(queryServiceLabels, start, end, resolution)
  846. }
  847. func (pds *PrometheusDataSource) QueryDeploymentLabelsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  848. const deploymentLabelsQuery = `avg_over_time(deployment_match_labels{%s}[%s])`
  849. // env.GetPromClusterFilter(), resStr
  850. cfg := pds.promConfig
  851. resolution = snapResolutionMinute(resolution)
  852. resMins := int64(resolution.Minutes())
  853. resStr := formatResolutionMinutes(resMins)
  854. queryDeploymentLabels := fmt.Sprintf(deploymentLabelsQuery, cfg.ClusterFilter, resStr)
  855. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  856. return ctx.QueryRange(queryDeploymentLabels, start, end, resolution)
  857. }
  858. func (pds *PrometheusDataSource) QueryStatefulsetLabelsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  859. const statefulsetLabelsQuery = `avg_over_time(statefulSet_match_labels{%s}[%s])`
  860. // env.GetPromClusterFilter(), resStr
  861. cfg := pds.promConfig
  862. resolution = snapResolutionMinute(resolution)
  863. resMins := int64(resolution.Minutes())
  864. resStr := formatResolutionMinutes(resMins)
  865. queryStatefulsetLabels := fmt.Sprintf(statefulsetLabelsQuery, cfg.ClusterFilter, resStr)
  866. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  867. return ctx.QueryRange(queryStatefulsetLabels, start, end, resolution)
  868. }
  869. func (pds *PrometheusDataSource) QueryPodJobsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  870. const podJobsQuery = `sum(kube_pod_owner{owner_kind="Job", %s}) by (namespace,pod,owner_name,%s)`
  871. // env.GetPromClusterFilter(), env.GetPromClusterLabel()
  872. cfg := pds.promConfig
  873. resolution = snapResolutionMinute(resolution)
  874. queryPodJobs := fmt.Sprintf(podJobsQuery, cfg.ClusterFilter, cfg.ClusterLabel)
  875. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  876. return ctx.QueryRange(queryPodJobs, start, end, resolution)
  877. }
  878. func (pds *PrometheusDataSource) QueryPodDaemonsetsOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  879. const podDaemonsetsQuery = `sum(kube_pod_owner{owner_kind="DaemonSet", %s}) by (namespace,pod,owner_name,%s)`
  880. // env.GetPromClusterFilter(), env.GetPromClusterLabel()
  881. cfg := pds.promConfig
  882. resolution = snapResolutionMinute(resolution)
  883. queryPodDaemonsets := fmt.Sprintf(podDaemonsetsQuery, cfg.ClusterFilter, cfg.ClusterLabel)
  884. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  885. return ctx.QueryRange(queryPodDaemonsets, start, end, resolution)
  886. }
  887. func (pds *PrometheusDataSource) QueryNormalizationOverTime(start, end time.Time, resolution time.Duration) source.QueryResultsChan {
  888. const normalizationQuery = `max(count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[%s] %s))`
  889. // env.GetPromClusterFilter(), resStr, "")
  890. cfg := pds.promConfig
  891. resolution = snapResolutionMinute(resolution)
  892. resMins := int64(resolution.Minutes())
  893. resStr := formatResolutionMinutes(resMins)
  894. queryNormalization := fmt.Sprintf(normalizationQuery, cfg.ClusterFilter, resStr, "")
  895. ctx := pds.promContexts.NewNamedContext(ComputeCostDataRangeContextName)
  896. return ctx.QueryRange(queryNormalization, start, end, resolution)
  897. }
  898. func (pds *PrometheusDataSource) QueryPVCost(start, end time.Time) source.QueryResultsChan {
  899. const pvCostQuery = `avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (%s, persistentvolume,provider_id)`
  900. durStr := timeutil.DurationString(end.Sub(start))
  901. if durStr == "" {
  902. panic("failed to parse duration string passed to QueryPVCost")
  903. }
  904. queryPVCost := fmt.Sprintf(pvCostQuery, pds.promConfig.ClusterFilter, durStr, pds.promConfig.ClusterLabel)
  905. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  906. return ctx.QueryAtTime(queryPVCost, end)
  907. }
  908. func (pds *PrometheusDataSource) QueryPVSize(start, end time.Time) source.QueryResultsChan {
  909. const pvSizeQuery = `avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (%s, persistentvolume)`
  910. cfg := pds.promConfig
  911. durStr := timeutil.DurationString(end.Sub(start))
  912. if durStr == "" {
  913. panic("failed to parse duration string passed to QueryPVCost")
  914. }
  915. queryPVSize := fmt.Sprintf(pvSizeQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  916. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  917. return ctx.QueryAtTime(queryPVSize, end)
  918. }
  919. func (pds *PrometheusDataSource) QueryPVStorageClass(start, end time.Time) source.QueryResultsChan {
  920. // `avg(avg_over_time(kubecost_pv_info{%s}[%s])) by (%s, persistentvolume, storageclass)`
  921. // , env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  922. const pvStorageSizeQuery = `avg(avg_over_time(kubecost_pv_info{%s}[%s])) by (%s, persistentvolume, storageclass)`
  923. cfg := pds.promConfig
  924. durStr := timeutil.DurationString(end.Sub(start))
  925. if durStr == "" {
  926. panic("failed to parse duration string passed to QueryPVStorageClass")
  927. }
  928. queryPVStorageClass := fmt.Sprintf(pvStorageSizeQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  929. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  930. return ctx.QueryAtTime(queryPVStorageClass, end)
  931. }
  932. func (pds *PrometheusDataSource) QueryPVUsedAverage(start, end time.Time) source.QueryResultsChan {
  933. // `avg(avg_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  934. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  935. const pvUsedAverageQuery = `avg(avg_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  936. cfg := pds.promConfig
  937. durStr := timeutil.DurationString(end.Sub(start))
  938. if durStr == "" {
  939. panic("failed to parse duration string passed to QueryPVUsedAverage")
  940. }
  941. queryPVUsedAvg := fmt.Sprintf(pvUsedAverageQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  942. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  943. return ctx.QueryAtTime(queryPVUsedAvg, end)
  944. }
  945. func (pds *PrometheusDataSource) QueryPVUsedMax(start, end time.Time) source.QueryResultsChan {
  946. // `max(max_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  947. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  948. const pvUsedMaxQuery = `max(max_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`
  949. cfg := pds.promConfig
  950. durStr := timeutil.DurationString(end.Sub(start))
  951. if durStr == "" {
  952. panic("failed to parse duration string passed to QueryPVUsedMax")
  953. }
  954. queryPVUsedMax := fmt.Sprintf(pvUsedMaxQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  955. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  956. return ctx.QueryAtTime(queryPVUsedMax, end)
  957. }
  958. func (pds *PrometheusDataSource) QueryPVCInfo(start, end time.Time) source.QueryResultsChan {
  959. // `avg(avg_over_time(kube_persistentvolumeclaim_info{%s}[%s])) by (%s, volumename, persistentvolumeclaim, namespace)`
  960. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  961. const pvcInfoQuery = `avg(avg_over_time(kube_persistentvolumeclaim_info{%s}[%s])) by (%s, volumename, persistentvolumeclaim, namespace)`
  962. cfg := pds.promConfig
  963. durStr := timeutil.DurationString(end.Sub(start))
  964. if durStr == "" {
  965. panic("failed to parse duration string passed to QueryPVCInfo")
  966. }
  967. queryPVCInfo := fmt.Sprintf(pvcInfoQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  968. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  969. return ctx.QueryAtTime(queryPVCInfo, end)
  970. }
  971. func (pds *PrometheusDataSource) QueryPVActiveMinutes(start, end time.Time) source.QueryResultsChan {
  972. // `avg(kube_persistentvolume_capacity_bytes{%s}) by (%s, persistentvolume)[%s:%dm]`
  973. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  974. const pvActiveMinsQuery = `avg(kube_persistentvolume_capacity_bytes{%s}) by (%s, persistentvolume)[%s:%dm]`
  975. cfg := pds.promConfig
  976. minsPerResolution := cfg.DataResolutionMinutes
  977. durStr := timeutil.DurationString(end.Sub(start))
  978. if durStr == "" {
  979. panic("failed to parse duration string passed to QueryPVActiveMinutes")
  980. }
  981. queryPVActiveMins := fmt.Sprintf(pvActiveMinsQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  982. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  983. return ctx.QueryAtTime(queryPVActiveMins, end)
  984. }
  985. func (pds *PrometheusDataSource) QueryLocalStorageCost(start, end time.Time) source.QueryResultsChan {
  986. // `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`
  987. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  988. 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`
  989. cfg := pds.promConfig
  990. resolution := cfg.DataResolution
  991. durStr := timeutil.DurationString(end.Sub(start))
  992. if durStr == "" {
  993. panic("failed to parse duration string passed to QueryLocalStorageCost")
  994. }
  995. //Ensuring if data resolution is less than 60s default it to 1m
  996. var minsPerResolution int
  997. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  998. minsPerResolution = 1
  999. log.DedupedWarningf(3, "QueryLocalStorageCost: Configured resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  1000. }
  1001. // hourlyToCumulative is a scaling factor that, when multiplied by an
  1002. // hourly value, converts it to a cumulative value; i.e. [$/hr] *
  1003. // [min/res]*[hr/min] = [$/res]
  1004. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1005. costPerGBHr := 0.04 / 730.0
  1006. queryLocalStorageCost := fmt.Sprintf(localStorageCostQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  1007. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1008. return ctx.QueryAtTime(queryLocalStorageCost, end)
  1009. }
  1010. func (pds *PrometheusDataSource) QueryLocalStorageUsedCost(start, end time.Time) source.QueryResultsChan {
  1011. // `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`
  1012. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  1013. 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`
  1014. cfg := pds.promConfig
  1015. minsPerResolution := cfg.DataResolutionMinutes
  1016. durStr := timeutil.DurationString(end.Sub(start))
  1017. if durStr == "" {
  1018. panic("failed to parse duration string passed to QueryLocalStorageUsedCost")
  1019. }
  1020. // hourlyToCumulative is a scaling factor that, when multiplied by an
  1021. // hourly value, converts it to a cumulative value; i.e. [$/hr] *
  1022. // [min/res]*[hr/min] = [$/res]
  1023. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1024. costPerGBHr := 0.04 / 730.0
  1025. queryLocalStorageUsedCost := fmt.Sprintf(localStorageUsedCostQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  1026. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1027. return ctx.QueryAtTime(queryLocalStorageUsedCost, end)
  1028. }
  1029. func (pds *PrometheusDataSource) QueryLocalStorageUsedAvg(start, end time.Time) source.QueryResultsChan {
  1030. // `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)`
  1031. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1032. 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)`
  1033. cfg := pds.promConfig
  1034. durStr := timeutil.DurationString(end.Sub(start))
  1035. if durStr == "" {
  1036. panic("failed to parse duration string passed to QueryLocalStorageUsedAvg")
  1037. }
  1038. queryLocalStorageUsedAvg := fmt.Sprintf(localStorageUsedAvgQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  1039. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1040. return ctx.QueryAtTime(queryLocalStorageUsedAvg, end)
  1041. }
  1042. func (pds *PrometheusDataSource) QueryLocalStorageUsedMax(start, end time.Time) source.QueryResultsChan {
  1043. // `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)`
  1044. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1045. 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)`
  1046. cfg := pds.promConfig
  1047. durStr := timeutil.DurationString(end.Sub(start))
  1048. if durStr == "" {
  1049. panic("failed to parse duration string passed to QueryLocalStorageUsedMax")
  1050. }
  1051. queryLocalStorageUsedMax := fmt.Sprintf(localStorageUsedMaxQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  1052. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1053. return ctx.QueryAtTime(queryLocalStorageUsedMax, end)
  1054. }
  1055. func (pds *PrometheusDataSource) QueryLocalStorageBytes(start, end time.Time) source.QueryResultsChan {
  1056. // `avg_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm])`
  1057. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  1058. const localStorageBytesQuery = `avg_over_time(sum(container_fs_limit_bytes{device=~"/dev/(nvme|sda).*", id="/", %s}) by (instance, device, %s)[%s:%dm])`
  1059. cfg := pds.promConfig
  1060. minsPerResolution := cfg.DataResolutionMinutes
  1061. durStr := timeutil.DurationString(end.Sub(start))
  1062. if durStr == "" {
  1063. panic("failed to parse duration string passed to QueryLocalStorageBytes")
  1064. }
  1065. queryLocalStorageBytes := fmt.Sprintf(localStorageBytesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  1066. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1067. return ctx.QueryAtTime(queryLocalStorageBytes, end)
  1068. }
  1069. func (pds *PrometheusDataSource) QueryLocalStorageActiveMinutes(start, end time.Time) source.QueryResultsChan {
  1070. // `count(node_total_hourly_cost{%s}) by (%s, node)[%s:%dm]`
  1071. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  1072. const localStorageActiveMinutesQuery = `count(node_total_hourly_cost{%s}) by (%s, node)[%s:%dm]`
  1073. cfg := pds.promConfig
  1074. minsPerResolution := cfg.DataResolutionMinutes
  1075. durStr := timeutil.DurationString(end.Sub(start))
  1076. if durStr == "" {
  1077. panic("failed to parse duration string passed to QueryLocalStorageActiveMinutes")
  1078. }
  1079. queryLocalStorageActiveMins := fmt.Sprintf(localStorageActiveMinutesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  1080. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1081. return ctx.QueryAtTime(queryLocalStorageActiveMins, end)
  1082. }
  1083. func (pds *PrometheusDataSource) QueryLocalStorageBytesByProvider(provider string, start, end time.Time) source.QueryResultsChan {
  1084. var localStorageBytesQuery string
  1085. key := strings.ToLower(provider)
  1086. if f, ok := providerStorageQueries[key]; ok {
  1087. localStorageBytesQuery = f(pds.promConfig, start, end, false, false)
  1088. } else {
  1089. localStorageBytesQuery = ""
  1090. }
  1091. if localStorageBytesQuery == "" {
  1092. return newEmptyResult()
  1093. }
  1094. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1095. return ctx.QueryAtTime(localStorageBytesQuery, end)
  1096. }
  1097. func (pds *PrometheusDataSource) QueryLocalStorageUsedByProvider(provider string, start, end time.Time) source.QueryResultsChan {
  1098. var localStorageUsedQuery string
  1099. key := strings.ToLower(provider)
  1100. if f, ok := providerStorageQueries[key]; ok {
  1101. localStorageUsedQuery = f(pds.promConfig, start, end, false, true)
  1102. } else {
  1103. localStorageUsedQuery = ""
  1104. }
  1105. if localStorageUsedQuery == "" {
  1106. return newEmptyResult()
  1107. }
  1108. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1109. return ctx.QueryAtTime(localStorageUsedQuery, end)
  1110. }
  1111. func (pds *PrometheusDataSource) QueryNodeCPUHourlyCost(start, end time.Time) source.QueryResultsChan {
  1112. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1113. const nodeCPUHourlyCostQuery = `avg(avg_over_time(node_cpu_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id)`
  1114. cfg := pds.promConfig
  1115. durStr := timeutil.DurationString(end.Sub(start))
  1116. if durStr == "" {
  1117. panic("failed to parse duration string passed to QueryNodeCPUHourlyCost")
  1118. }
  1119. queryNodeCPUHourlyCost := fmt.Sprintf(nodeCPUHourlyCostQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1120. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1121. return ctx.QueryAtTime(queryNodeCPUHourlyCost, end)
  1122. }
  1123. func (pds *PrometheusDataSource) QueryNodeCPUCoresCapacity(start, end time.Time) source.QueryResultsChan {
  1124. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1125. const nodeCPUCoresCapacityQuery = `avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s])) by (%s, node)`
  1126. cfg := pds.promConfig
  1127. durStr := timeutil.DurationString(end.Sub(start))
  1128. if durStr == "" {
  1129. panic("failed to parse duration string passed to QueryNodeCPUCoresCapacity")
  1130. }
  1131. queryNodeCPUCoresCapacity := fmt.Sprintf(nodeCPUCoresCapacityQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1132. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1133. return ctx.QueryAtTime(queryNodeCPUCoresCapacity, end)
  1134. }
  1135. func (pds *PrometheusDataSource) QueryNodeCPUCoresAllocatable(start, end time.Time) source.QueryResultsChan {
  1136. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1137. const nodeCPUCoresAllocatableQuery = `avg(avg_over_time(kube_node_status_allocatable_cpu_cores{%s}[%s])) by (%s, node)`
  1138. cfg := pds.promConfig
  1139. durStr := timeutil.DurationString(end.Sub(start))
  1140. if durStr == "" {
  1141. panic("failed to parse duration string passed to QueryNodeCPUCoresAllocatable")
  1142. }
  1143. queryNodeCPUCoresAllocatable := fmt.Sprintf(nodeCPUCoresAllocatableQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1144. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1145. return ctx.QueryAtTime(queryNodeCPUCoresAllocatable, end)
  1146. }
  1147. func (pds *PrometheusDataSource) QueryNodeRAMHourlyCost(start, end time.Time) source.QueryResultsChan {
  1148. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1149. const nodeRAMHourlyCostQuery = `avg(avg_over_time(node_ram_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id) / 1024 / 1024 / 1024`
  1150. cfg := pds.promConfig
  1151. durStr := timeutil.DurationString(end.Sub(start))
  1152. if durStr == "" {
  1153. panic("failed to parse duration string passed to QueryNodeRAMHourlyCost")
  1154. }
  1155. queryNodeRAMHourlyCost := fmt.Sprintf(nodeRAMHourlyCostQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1156. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1157. return ctx.QueryAtTime(queryNodeRAMHourlyCost, end)
  1158. }
  1159. func (pds *PrometheusDataSource) QueryNodeRAMBytesCapacity(start, end time.Time) source.QueryResultsChan {
  1160. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1161. const nodeRAMBytesCapacityQuery = `avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s])) by (%s, node)`
  1162. cfg := pds.promConfig
  1163. durStr := timeutil.DurationString(end.Sub(start))
  1164. if durStr == "" {
  1165. panic("failed to parse duration string passed to QueryNodeRAMBytesCapacity")
  1166. }
  1167. queryNodeRAMBytesCapacity := fmt.Sprintf(nodeRAMBytesCapacityQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1168. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1169. return ctx.QueryAtTime(queryNodeRAMBytesCapacity, end)
  1170. }
  1171. func (pds *PrometheusDataSource) QueryNodeRAMBytesAllocatable(start, end time.Time) source.QueryResultsChan {
  1172. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1173. const nodeRAMBytesAllocatableQuery = `avg(avg_over_time(kube_node_status_allocatable_memory_bytes{%s}[%s])) by (%s, node)`
  1174. cfg := pds.promConfig
  1175. durStr := timeutil.DurationString(end.Sub(start))
  1176. if durStr == "" {
  1177. panic("failed to parse duration string passed to QueryNodeRAMBytesAllocatable")
  1178. }
  1179. queryNodeRAMBytesAllocatable := fmt.Sprintf(nodeRAMBytesAllocatableQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1180. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1181. return ctx.QueryAtTime(queryNodeRAMBytesAllocatable, end)
  1182. }
  1183. func (pds *PrometheusDataSource) QueryNodeGPUCount(start, end time.Time) source.QueryResultsChan {
  1184. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1185. const nodeGPUCountQuery = `avg(avg_over_time(node_gpu_count{%s}[%s])) by (%s, node, provider_id)`
  1186. cfg := pds.promConfig
  1187. durStr := timeutil.DurationString(end.Sub(start))
  1188. if durStr == "" {
  1189. panic("failed to parse duration string passed to QueryNodeGPUCount")
  1190. }
  1191. queryNodeGPUCount := fmt.Sprintf(nodeGPUCountQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1192. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1193. return ctx.QueryAtTime(queryNodeGPUCount, end)
  1194. }
  1195. func (pds *PrometheusDataSource) QueryNodeGPUHourlyCost(start, end time.Time) source.QueryResultsChan {
  1196. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1197. const nodeGPUHourlyCostQuery = `avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id)`
  1198. cfg := pds.promConfig
  1199. durStr := timeutil.DurationString(end.Sub(start))
  1200. if durStr == "" {
  1201. panic("failed to parse duration string passed to QueryNodeGPUHourlyCost")
  1202. }
  1203. queryNodeGPUHourlyCost := fmt.Sprintf(nodeGPUHourlyCostQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1204. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1205. return ctx.QueryAtTime(queryNodeGPUHourlyCost, end)
  1206. }
  1207. func (pds *PrometheusDataSource) QueryNodeLabels(start, end time.Time) source.QueryResultsChan {
  1208. // env.GetPromClusterFilter(), durStr, minsPerResolution)
  1209. const labelsQuery = `count_over_time(kube_node_labels{%s}[%s:%dm])`
  1210. cfg := pds.promConfig
  1211. minsPerResolution := cfg.DataResolutionMinutes
  1212. durStr := timeutil.DurationString(end.Sub(start))
  1213. if durStr == "" {
  1214. panic("failed to parse duration string passed to QueryNodeLabels")
  1215. }
  1216. queryLabels := fmt.Sprintf(labelsQuery, cfg.ClusterFilter, durStr, minsPerResolution)
  1217. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1218. return ctx.QueryAtTime(queryLabels, end)
  1219. }
  1220. func (pds *PrometheusDataSource) QueryNodeActiveMinutes(start, end time.Time) source.QueryResultsChan {
  1221. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  1222. const activeMinsQuery = `avg(node_total_hourly_cost{%s}) by (node, %s, provider_id)[%s:%dm]`
  1223. cfg := pds.promConfig
  1224. minsPerResolution := cfg.DataResolutionMinutes
  1225. durStr := timeutil.DurationString(end.Sub(start))
  1226. if durStr == "" {
  1227. panic("failed to parse duration string passed to QueryNodeActiveMinutes")
  1228. }
  1229. queryActiveMins := fmt.Sprintf(activeMinsQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  1230. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1231. return ctx.QueryAtTime(queryActiveMins, end)
  1232. }
  1233. func (pds *PrometheusDataSource) QueryNodeIsSpot(start, end time.Time) source.QueryResultsChan {
  1234. // env.GetPromClusterFilter(), durStr, minsPerResolution)
  1235. const isSpotQuery = `avg_over_time(kubecost_node_is_spot{%s}[%s:%dm])`
  1236. cfg := pds.promConfig
  1237. minsPerResolution := cfg.DataResolutionMinutes
  1238. durStr := timeutil.DurationString(end.Sub(start))
  1239. if durStr == "" {
  1240. panic("failed to parse duration string passed to QueryNodeIsSpot")
  1241. }
  1242. queryIsSpot := fmt.Sprintf(isSpotQuery, cfg.ClusterFilter, durStr, minsPerResolution)
  1243. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1244. return ctx.QueryAtTime(queryIsSpot, end)
  1245. }
  1246. func (pds *PrometheusDataSource) QueryNodeCPUModeTotal(start, end time.Time) source.QueryResultsChan {
  1247. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel())
  1248. const nodeCPUModeTotalQuery = `sum(rate(node_cpu_seconds_total{%s}[%s:%dm])) by (kubernetes_node, %s, mode)`
  1249. cfg := pds.promConfig
  1250. minsPerResolution := cfg.DataResolutionMinutes
  1251. durStr := timeutil.DurationString(end.Sub(start))
  1252. if durStr == "" {
  1253. panic("failed to parse duration string passed to QueryNodeCPUModeTotal")
  1254. }
  1255. queryCPUModeTotal := fmt.Sprintf(nodeCPUModeTotalQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel)
  1256. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1257. return ctx.QueryAtTime(queryCPUModeTotal, end)
  1258. }
  1259. func (pds *PrometheusDataSource) QueryNodeCPUModePercent(start, end time.Time) source.QueryResultsChan {
  1260. const fmtQueryCPUModePct = `
  1261. sum(rate(node_cpu_seconds_total{%s}[%s])) by (%s, mode) / ignoring(mode)
  1262. group_left sum(rate(node_cpu_seconds_total{%s}[%s])) by (%s)
  1263. `
  1264. // env.GetPromClusterFilter(), windowStr, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel()
  1265. cfg := pds.promConfig
  1266. durStr := timeutil.DurationString(end.Sub(start))
  1267. if durStr == "" {
  1268. panic("failed to parse duration string passed to QueryNodeCPUModePercent")
  1269. }
  1270. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1271. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1272. return ctx.QueryAtTime(queryCPUModePct, end)
  1273. }
  1274. func (pds *PrometheusDataSource) QueryNodeRAMSystemPercent(start, end time.Time) source.QueryResultsChan {
  1275. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1276. 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)`
  1277. cfg := pds.promConfig
  1278. minsPerResolution := cfg.DataResolutionMinutes
  1279. durStr := timeutil.DurationString(end.Sub(start))
  1280. if durStr == "" {
  1281. panic("failed to parse duration string passed to QueryNodeRAMSystemPercent")
  1282. }
  1283. queryRAMSystemPct := fmt.Sprintf(nodeRAMSystemPctQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterLabel)
  1284. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1285. return ctx.QueryAtTime(queryRAMSystemPct, end)
  1286. }
  1287. func (pds *PrometheusDataSource) QueryNodeRAMUserPercent(start, end time.Time) source.QueryResultsChan {
  1288. // env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1289. 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)`
  1290. cfg := pds.promConfig
  1291. minsPerResolution := cfg.DataResolutionMinutes
  1292. durStr := timeutil.DurationString(end.Sub(start))
  1293. if durStr == "" {
  1294. panic("failed to parse duration string passed to QueryNodeRAMUserPercent")
  1295. }
  1296. queryRAMUserPct := fmt.Sprintf(nodeRAMUserPctQuery, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, cfg.ClusterLabel)
  1297. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1298. return ctx.QueryAtTime(queryRAMUserPct, end)
  1299. }
  1300. func (pds *PrometheusDataSource) QueryLBCost(start, end time.Time) source.QueryResultsChan {
  1301. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1302. const lbCostQuery = `avg(avg_over_time(kubecost_load_balancer_cost{%s}[%s])) by (namespace, service_name, %s, ingress_ip)`
  1303. cfg := pds.promConfig
  1304. durStr := timeutil.DurationString(end.Sub(start))
  1305. if durStr == "" {
  1306. panic("failed to parse duration string passed to QueryLBCost")
  1307. }
  1308. queryLBCost := fmt.Sprintf(lbCostQuery, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1309. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1310. return ctx.QueryAtTime(queryLBCost, end)
  1311. }
  1312. func (pds *PrometheusDataSource) QueryLBActiveMinutes(start, end time.Time) source.QueryResultsChan {
  1313. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  1314. const lbActiveMinutesQuery = `avg(kubecost_load_balancer_cost{%s}) by (namespace, service_name, %s, ingress_ip)[%s:%dm]`
  1315. cfg := pds.promConfig
  1316. minsPerResolution := cfg.DataResolutionMinutes
  1317. durStr := timeutil.DurationString(end.Sub(start))
  1318. if durStr == "" {
  1319. panic("failed to parse duration string passed to QueryLBActiveMinutes")
  1320. }
  1321. queryLBActiveMins := fmt.Sprintf(lbActiveMinutesQuery, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution)
  1322. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1323. return ctx.QueryAtTime(queryLBActiveMins, end)
  1324. }
  1325. func (pds *PrometheusDataSource) QueryDataCount(start, end time.Time) source.QueryResultsChan {
  1326. const fmtQueryDataCount = `
  1327. count_over_time(sum(kube_node_status_capacity_cpu_cores{%s}) by (%s)[%s:%dm]) * %d
  1328. `
  1329. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, minsPerResolution)
  1330. cfg := pds.promConfig
  1331. minsPerResolution := cfg.DataResolutionMinutes
  1332. durStr := timeutil.DurationString(end.Sub(start))
  1333. if durStr == "" {
  1334. panic("failed to parse duration string passed to QueryDataCount")
  1335. }
  1336. queryDataCount := fmt.Sprintf(fmtQueryDataCount, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, minsPerResolution)
  1337. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1338. return ctx.QueryAtTime(queryDataCount, end)
  1339. }
  1340. func (pds *PrometheusDataSource) QueryTotalGPU(start, end time.Time) source.QueryResultsChan {
  1341. const fmtQueryTotalGPU = `
  1342. sum(
  1343. sum_over_time(node_gpu_hourly_cost{%s}[%s:%dm]) * %f
  1344. ) by (%s)
  1345. `
  1346. // env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, hourlyToCumulative, env.GetPromClusterLabel())
  1347. cfg := pds.promConfig
  1348. minsPerResolution := cfg.DataResolutionMinutes
  1349. durStr := timeutil.DurationString(end.Sub(start))
  1350. if durStr == "" {
  1351. panic("failed to parse duration string passed to QueryTotalGPU")
  1352. }
  1353. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  1354. // value, converts it to a cumulative value; i.e.
  1355. // [$/hr] * [min/res]*[hr/min] = [$/res]
  1356. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1357. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, cfg.ClusterFilter, durStr, minsPerResolution, hourlyToCumulative, cfg.ClusterLabel)
  1358. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1359. return ctx.QueryAtTime(queryTotalGPU, end)
  1360. }
  1361. func (pds *PrometheusDataSource) QueryTotalCPU(start, end time.Time) source.QueryResultsChan {
  1362. const fmtQueryTotalCPU = `
  1363. sum(
  1364. sum_over_time(avg(kube_node_status_capacity_cpu_cores{%s}) by (node, %s)[%s:%dm]) *
  1365. avg(avg_over_time(node_cpu_hourly_cost{%s}[%s:%dm])) by (node, %s) * %f
  1366. ) by (%s)
  1367. `
  1368. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel()
  1369. cfg := pds.promConfig
  1370. minsPerResolution := cfg.DataResolutionMinutes
  1371. durStr := timeutil.DurationString(end.Sub(start))
  1372. if durStr == "" {
  1373. panic("failed to parse duration string passed to QueryTotalCPU")
  1374. }
  1375. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  1376. // value, converts it to a cumulative value; i.e.
  1377. // [$/hr] * [min/res]*[hr/min] = [$/res]
  1378. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1379. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  1380. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1381. return ctx.QueryAtTime(queryTotalCPU, end)
  1382. }
  1383. func (pds *PrometheusDataSource) QueryTotalRAM(start, end time.Time) source.QueryResultsChan {
  1384. const fmtQueryTotalRAM = `
  1385. sum(
  1386. sum_over_time(avg(kube_node_status_capacity_memory_bytes{%s}) by (node, %s)[%s:%dm]) / 1024 / 1024 / 1024 *
  1387. avg(avg_over_time(node_ram_hourly_cost{%s}[%s:%dm])) by (node, %s) * %f
  1388. ) by (%s)
  1389. `
  1390. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, env.GetPromClusterFilter(), windowStr, minsPerResolution, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  1391. cfg := pds.promConfig
  1392. minsPerResolution := cfg.DataResolutionMinutes
  1393. durStr := timeutil.DurationString(end.Sub(start))
  1394. if durStr == "" {
  1395. panic("failed to parse duration string passed to QueryTotalRAM")
  1396. }
  1397. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  1398. // value, converts it to a cumulative value; i.e.
  1399. // [$/hr] * [min/res]*[hr/min] = [$/res]
  1400. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1401. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  1402. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1403. return ctx.QueryAtTime(queryTotalRAM, end)
  1404. }
  1405. func (pds *PrometheusDataSource) QueryTotalStorage(start, end time.Time) source.QueryResultsChan {
  1406. const fmtQueryTotalStorage = `
  1407. sum(
  1408. sum_over_time(avg(kube_persistentvolume_capacity_bytes{%s}) by (persistentvolume, %s)[%s:%dm]) / 1024 / 1024 / 1024 *
  1409. avg(avg_over_time(pv_hourly_cost{%s}[%s:%dm])) by (persistentvolume, %s) * %f
  1410. ) by (%s)
  1411. `
  1412. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, env.GetPromClusterFilter(), windowStr, minsPerResolution, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  1413. cfg := pds.promConfig
  1414. minsPerResolution := cfg.DataResolutionMinutes
  1415. durStr := timeutil.DurationString(end.Sub(start))
  1416. if durStr == "" {
  1417. panic("failed to parse duration string passed to QueryTotalStorage")
  1418. }
  1419. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  1420. // value, converts it to a cumulative value; i.e.
  1421. // [$/hr] * [min/res]*[hr/min] = [$/res]
  1422. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  1423. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, cfg.ClusterFilter, cfg.ClusterLabel, durStr, minsPerResolution, cfg.ClusterFilter, durStr, minsPerResolution, cfg.ClusterLabel, hourlyToCumulative, cfg.ClusterLabel)
  1424. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1425. return ctx.QueryAtTime(queryTotalStorage, end)
  1426. }
  1427. func (pds *PrometheusDataSource) QueryClusterCores(start, end time.Time, step time.Duration) source.QueryResultsChan {
  1428. const queryClusterCores = `sum(
  1429. 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 +
  1430. avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (node, %s) * 730
  1431. ) by (%s)`
  1432. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1433. cfg := pds.promConfig
  1434. durStr := timeutil.DurationString(step)
  1435. if durStr == "" {
  1436. panic("failed to parse duration string passed to QueryClusterCores")
  1437. }
  1438. clusterCoresQuery := fmt.Sprintf(queryClusterCores, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  1439. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1440. return ctx.QueryRange(clusterCoresQuery, start, end, step)
  1441. }
  1442. func (pds *PrometheusDataSource) QueryClusterRAM(start, end time.Time, step time.Duration) source.QueryResultsChan {
  1443. const queryClusterRAM = `sum(
  1444. 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
  1445. ) by (%s)`
  1446. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1447. cfg := pds.promConfig
  1448. durStr := timeutil.DurationString(step)
  1449. if durStr == "" {
  1450. panic("failed to parse duration string passed to QueryClusterCores")
  1451. }
  1452. clusterRAMQuery := fmt.Sprintf(queryClusterRAM, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel)
  1453. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1454. return ctx.QueryRange(clusterRAMQuery, start, end, step)
  1455. }
  1456. func (pds *PrometheusDataSource) QueryClusterStorage(start, end time.Time, step time.Duration) source.QueryResultsChan {
  1457. return pds.QueryClusterStorageByProvider("", start, end, step)
  1458. }
  1459. func (pds *PrometheusDataSource) QueryClusterStorageByProvider(provider string, start, end time.Time, step time.Duration) source.QueryResultsChan {
  1460. const queryStorage = `sum(
  1461. avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (persistentvolume, %s) * 730
  1462. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  1463. ) by (%s) %s`
  1464. // env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1465. var localStorageQuery string
  1466. if provider != "" {
  1467. key := strings.ToLower(provider)
  1468. if f, ok := providerStorageQueries[key]; ok {
  1469. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1470. } else {
  1471. localStorageQuery = ""
  1472. }
  1473. }
  1474. if localStorageQuery != "" {
  1475. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1476. }
  1477. cfg := pds.promConfig
  1478. durStr := timeutil.DurationString(step)
  1479. if durStr == "" {
  1480. panic("failed to parse duration string passed to QueryClusterCores")
  1481. }
  1482. clusterStorageQuery := fmt.Sprintf(queryStorage, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterFilter, durStr, cfg.ClusterLabel, cfg.ClusterLabel, localStorageQuery)
  1483. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1484. return ctx.QueryRange(clusterStorageQuery, start, end, step)
  1485. }
  1486. func (pds *PrometheusDataSource) QueryClusterTotal(start, end time.Time, step time.Duration) source.QueryResultsChan {
  1487. return pds.QueryClusterTotalByProvider("", start, end, step)
  1488. }
  1489. func (pds *PrometheusDataSource) QueryClusterTotalByProvider(provider string, start, end time.Time, step time.Duration) source.QueryResultsChan {
  1490. const queryTotal = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 +
  1491. sum(
  1492. avg(avg_over_time(pv_hourly_cost{%s}[1h])) by (persistentvolume, %s) * 730
  1493. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[1h])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  1494. ) by (%s) %s`
  1495. var localStorageQuery string
  1496. if provider != "" {
  1497. key := strings.ToLower(provider)
  1498. if f, ok := providerStorageQueries[key]; ok {
  1499. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1500. } else {
  1501. localStorageQuery = ""
  1502. }
  1503. }
  1504. if localStorageQuery != "" {
  1505. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1506. }
  1507. cfg := pds.promConfig
  1508. durStr := timeutil.DurationString(step)
  1509. if durStr == "" {
  1510. panic("failed to parse duration string passed to QueryClusterTotalByProvider")
  1511. }
  1512. clusterTotalQuery := fmt.Sprintf(queryTotal, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterFilter, cfg.ClusterLabel, cfg.ClusterLabel, localStorageQuery)
  1513. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1514. return ctx.QueryRange(clusterTotalQuery, start, end, step)
  1515. }
  1516. func (pds *PrometheusDataSource) QueryClusterNodes(start, end time.Time, step time.Duration) source.QueryResultsChan {
  1517. return pds.QueryClusterNodesByProvider("", start, end, step)
  1518. }
  1519. func (pds *PrometheusDataSource) QueryClusterNodesByProvider(provider string, start, end time.Time, step time.Duration) source.QueryResultsChan {
  1520. const queryNodes = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 %s`
  1521. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), localStorageQuery)
  1522. var localStorageQuery string
  1523. if provider != "" {
  1524. key := strings.ToLower(provider)
  1525. if f, ok := providerStorageQueries[key]; ok {
  1526. localStorageQuery = f(pds.promConfig, start, end, true, false)
  1527. } else {
  1528. localStorageQuery = ""
  1529. }
  1530. }
  1531. if localStorageQuery != "" {
  1532. localStorageQuery = fmt.Sprintf(" + %s", localStorageQuery)
  1533. }
  1534. cfg := pds.promConfig
  1535. durStr := timeutil.DurationString(step)
  1536. if durStr == "" {
  1537. panic("failed to parse duration string passed to QueryClusterNodesByProvider")
  1538. }
  1539. clusterNodesCostQuery := fmt.Sprintf(queryNodes, cfg.ClusterFilter, cfg.ClusterLabel, localStorageQuery)
  1540. ctx := pds.promContexts.NewNamedContext(ClusterContextName)
  1541. return ctx.QueryRange(clusterNodesCostQuery, start, end, step)
  1542. }
  1543. // AllocationMetricQuerier
  1544. func (pds *PrometheusDataSource) QueryPods(start, end time.Time) source.QueryResultsChan {
  1545. const queryFmtPods = `avg(kube_pod_container_status_running{%s} != 0) by (pod, namespace, %s)[%s:%s]`
  1546. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1547. cfg := pds.promConfig
  1548. resolution := cfg.DataResolution
  1549. resStr := timeutil.DurationString(resolution)
  1550. durStr := timeutil.DurationString(end.Sub(start))
  1551. if durStr == "" {
  1552. panic("failed to parse duration string passed to QueryPods")
  1553. }
  1554. queryPods := fmt.Sprintf(queryFmtPods, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1555. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1556. return ctx.QueryAtTime(queryPods, end)
  1557. }
  1558. func (pds *PrometheusDataSource) QueryPodsUID(start, end time.Time) source.QueryResultsChan {
  1559. const queryFmtPodsUID = `avg(kube_pod_container_status_running{%s} != 0) by (pod, namespace, uid, %s)[%s:%s]`
  1560. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1561. cfg := pds.promConfig
  1562. resolution := cfg.DataResolution
  1563. resStr := timeutil.DurationString(resolution)
  1564. durStr := timeutil.DurationString(end.Sub(start))
  1565. if durStr == "" {
  1566. panic("failed to parse duration string passed to QueryPodsUID")
  1567. }
  1568. queryPodsUID := fmt.Sprintf(queryFmtPodsUID, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1569. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1570. return ctx.QueryAtTime(queryPodsUID, end)
  1571. }
  1572. func (pds *PrometheusDataSource) QueryRAMBytesAllocated(start, end time.Time) source.QueryResultsChan {
  1573. const queryFmtRAMBytesAllocated = `avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s, provider_id)`
  1574. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1575. cfg := pds.promConfig
  1576. durStr := timeutil.DurationString(end.Sub(start))
  1577. if durStr == "" {
  1578. panic("failed to parse duration string passed to QueryRAMBytesAllocated")
  1579. }
  1580. queryRAMBytesAllocated := fmt.Sprintf(queryFmtRAMBytesAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1581. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1582. return ctx.QueryAtTime(queryRAMBytesAllocated, end)
  1583. }
  1584. func (pds *PrometheusDataSource) QueryRAMRequests(start, end time.Time) source.QueryResultsChan {
  1585. 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)`
  1586. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1587. cfg := pds.promConfig
  1588. durStr := timeutil.DurationString(end.Sub(start))
  1589. if durStr == "" {
  1590. panic("failed to parse duration string passed to QueryRAMRequests")
  1591. }
  1592. queryRAMRequests := fmt.Sprintf(queryFmtRAMRequests, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1593. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1594. return ctx.QueryAtTime(queryRAMRequests, end)
  1595. }
  1596. func (pds *PrometheusDataSource) QueryRAMUsageAvg(start, end time.Time) source.QueryResultsChan {
  1597. 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)`
  1598. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1599. cfg := pds.promConfig
  1600. durStr := timeutil.DurationString(end.Sub(start))
  1601. if durStr == "" {
  1602. panic("failed to parse duration string passed to QueryRAMUsageAvg")
  1603. }
  1604. queryRAMUsageAvg := fmt.Sprintf(queryFmtRAMUsageAvg, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1605. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1606. return ctx.QueryAtTime(queryRAMUsageAvg, end)
  1607. }
  1608. func (pds *PrometheusDataSource) QueryRAMUsageMax(start, end time.Time) source.QueryResultsChan {
  1609. 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)`
  1610. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1611. cfg := pds.promConfig
  1612. durStr := timeutil.DurationString(end.Sub(start))
  1613. if durStr == "" {
  1614. panic("failed to parse duration string passed to QueryRAMUsageMax")
  1615. }
  1616. queryRAMUsageMax := fmt.Sprintf(queryFmtRAMUsageMax, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1617. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1618. return ctx.QueryAtTime(queryRAMUsageMax, end)
  1619. }
  1620. func (pds *PrometheusDataSource) QueryCPUCoresAllocated(start, end time.Time) source.QueryResultsChan {
  1621. const queryFmtCPUCoresAllocated = `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1622. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1623. cfg := pds.promConfig
  1624. durStr := timeutil.DurationString(end.Sub(start))
  1625. if durStr == "" {
  1626. panic("failed to parse duration string passed to QueryCPUCoresAllocated")
  1627. }
  1628. queryCPUCoresAllocated := fmt.Sprintf(queryFmtCPUCoresAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1629. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1630. return ctx.QueryAtTime(queryCPUCoresAllocated, end)
  1631. }
  1632. func (pds *PrometheusDataSource) QueryCPURequests(start, end time.Time) source.QueryResultsChan {
  1633. 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)`
  1634. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1635. cfg := pds.promConfig
  1636. durStr := timeutil.DurationString(end.Sub(start))
  1637. if durStr == "" {
  1638. panic("failed to parse duration string passed to QueryCPURequests")
  1639. }
  1640. queryCPURequests := fmt.Sprintf(queryFmtCPURequests, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1641. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1642. return ctx.QueryAtTime(queryCPURequests, end)
  1643. }
  1644. func (pds *PrometheusDataSource) QueryCPUUsageAvg(start, end time.Time) source.QueryResultsChan {
  1645. 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)`
  1646. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1647. cfg := pds.promConfig
  1648. durStr := timeutil.DurationString(end.Sub(start))
  1649. if durStr == "" {
  1650. panic("failed to parse duration string passed to QueryCPUUsageAvg")
  1651. }
  1652. queryCPUUsageAvg := fmt.Sprintf(queryFmtCPUUsageAvg, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1653. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1654. return ctx.QueryAtTime(queryCPUUsageAvg, end)
  1655. }
  1656. func (pds *PrometheusDataSource) QueryCPUUsageMax(start, end time.Time) source.QueryResultsChan {
  1657. // Because we use container_cpu_usage_seconds_total to calculate CPU usage
  1658. // at any given "instant" of time, we need to use an irate or rate. To then
  1659. // calculate a max (or any aggregation) we have to perform an aggregation
  1660. // query on top of an instant-by-instant maximum. Prometheus supports this
  1661. // type of query with a "subquery" [1], however it is reportedly expensive
  1662. // to make such a query. By default, Kubecost's Prometheus config includes
  1663. // a recording rule that keeps track of the instant-by-instant irate for CPU
  1664. // usage. The metric in this query is created by that recording rule.
  1665. //
  1666. // [1] https://prometheus.io/blog/2019/01/28/subquery-support/
  1667. //
  1668. // If changing the name of the recording rule, make sure to update the
  1669. // corresponding diagnostic query to avoid confusion.
  1670. const queryFmtCPUUsageMaxRecordingRule = `max(max_over_time(kubecost_container_cpu_usage_irate{%s}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  1671. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1672. // This is the subquery equivalent of the above recording rule query. It is
  1673. // more expensive, but does not require the recording rule. It should be
  1674. // used as a fallback query if the recording rule data does not exist.
  1675. //
  1676. // The parameter after the colon [:<thisone>] in the subquery affects the
  1677. // resolution of the subquery.
  1678. // The parameter after the metric ...{}[<thisone>] should be set to 2x
  1679. // the resolution, to make sure the irate always has two points to query
  1680. // in case the Prom scrape duration has been reduced to be equal to the
  1681. // ETL resolution.
  1682. 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)`
  1683. // env.GetPromClusterFilter(), doubleResStr, durStr, resStr, env.GetPromClusterLabel()
  1684. cfg := pds.promConfig
  1685. durStr := timeutil.DurationString(end.Sub(start))
  1686. if durStr == "" {
  1687. panic("failed to parse duration string passed to QueryCPUUsageMax")
  1688. }
  1689. queryCPUUsageMaxRecordingRule := fmt.Sprintf(queryFmtCPUUsageMaxRecordingRule, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1690. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1691. resCPUUsageMaxRR := ctx.QueryAtTime(queryCPUUsageMaxRecordingRule, end)
  1692. resCPUUsageMax, _ := resCPUUsageMaxRR.Await()
  1693. if len(resCPUUsageMax) > 0 {
  1694. return wrapResults(queryCPUUsageMaxRecordingRule, resCPUUsageMax)
  1695. }
  1696. resolution := cfg.DataResolution
  1697. resStr := timeutil.DurationString(resolution)
  1698. doubleResStr := timeutil.DurationString(2 * resolution)
  1699. queryCPUUsageMaxSubquery := fmt.Sprintf(queryFmtCPUUsageMaxSubquery, cfg.ClusterFilter, doubleResStr, durStr, resStr, cfg.ClusterLabel)
  1700. return ctx.QueryAtTime(queryCPUUsageMaxSubquery, end)
  1701. }
  1702. func (pds *PrometheusDataSource) QueryGPUsRequested(start, end time.Time) source.QueryResultsChan {
  1703. 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)`
  1704. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1705. cfg := pds.promConfig
  1706. durStr := timeutil.DurationString(end.Sub(start))
  1707. if durStr == "" {
  1708. panic("failed to parse duration string passed to QueryGPUsRequested")
  1709. }
  1710. queryGPUsRequested := fmt.Sprintf(queryFmtGPUsRequested, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1711. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1712. return ctx.QueryAtTime(queryGPUsRequested, end)
  1713. }
  1714. func (pds *PrometheusDataSource) QueryGPUsUsageAvg(start, end time.Time) source.QueryResultsChan {
  1715. const queryFmtGPUsUsageAvg = `avg(avg_over_time(DCGM_FI_PROF_GR_ENGINE_ACTIVE{container!=""}[%s])) by (container, pod, namespace, %s)`
  1716. // durStr, env.GetPromClusterLabel()
  1717. cfg := pds.promConfig
  1718. durStr := timeutil.DurationString(end.Sub(start))
  1719. if durStr == "" {
  1720. panic("failed to parse duration string passed to QueryGPUsUsageAvg")
  1721. }
  1722. queryGPUsUsageAvg := fmt.Sprintf(queryFmtGPUsUsageAvg, durStr, cfg.ClusterLabel)
  1723. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1724. return ctx.QueryAtTime(queryGPUsUsageAvg, end)
  1725. }
  1726. func (pds *PrometheusDataSource) QueryGPUsUsageMax(start, end time.Time) source.QueryResultsChan {
  1727. const queryFmtGPUsUsageMax = `max(max_over_time(DCGM_FI_PROF_GR_ENGINE_ACTIVE{container!=""}[%s])) by (container, pod, namespace, %s)`
  1728. // durStr, env.GetPromClusterLabel()
  1729. cfg := pds.promConfig
  1730. durStr := timeutil.DurationString(end.Sub(start))
  1731. if durStr == "" {
  1732. panic("failed to parse duration string passed to QueryGPUsUsageMax")
  1733. }
  1734. queryGPUsUsageMax := fmt.Sprintf(queryFmtGPUsUsageMax, durStr, cfg.ClusterLabel)
  1735. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1736. return ctx.QueryAtTime(queryGPUsUsageMax, end)
  1737. }
  1738. func (pds *PrometheusDataSource) QueryGPUsAllocated(start, end time.Time) source.QueryResultsChan {
  1739. const queryFmtGPUsAllocated = `avg(avg_over_time(container_gpu_allocation{container!="", container!="POD", node!="", %s}[%s])) by (container, pod, namespace, node, %s)`
  1740. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1741. cfg := pds.promConfig
  1742. durStr := timeutil.DurationString(end.Sub(start))
  1743. if durStr == "" {
  1744. panic("failed to parse duration string passed to QueryGPUsAllocated")
  1745. }
  1746. queryGPUsAllocated := fmt.Sprintf(queryFmtGPUsAllocated, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1747. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1748. return ctx.QueryAtTime(queryGPUsAllocated, end)
  1749. }
  1750. func (pds *PrometheusDataSource) QueryNodeCostPerCPUHr(start, end time.Time) source.QueryResultsChan {
  1751. const queryFmtNodeCostPerCPUHr = `avg(avg_over_time(node_cpu_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1752. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1753. cfg := pds.promConfig
  1754. durStr := timeutil.DurationString(end.Sub(start))
  1755. if durStr == "" {
  1756. panic("failed to parse duration string passed to QueryNodeCostPerCPUHr")
  1757. }
  1758. queryNodeCostPerCPUHr := fmt.Sprintf(queryFmtNodeCostPerCPUHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1759. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1760. return ctx.QueryAtTime(queryNodeCostPerCPUHr, end)
  1761. }
  1762. func (pds *PrometheusDataSource) QueryNodeCostPerRAMGiBHr(start, end time.Time) source.QueryResultsChan {
  1763. const queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1764. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1765. cfg := pds.promConfig
  1766. durStr := timeutil.DurationString(end.Sub(start))
  1767. if durStr == "" {
  1768. panic("failed to parse duration string passed to QueryNodeCostPerRAMGiBHr")
  1769. }
  1770. queryNodeCostPerRAMGiBHr := fmt.Sprintf(queryFmtNodeCostPerRAMGiBHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1771. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1772. return ctx.QueryAtTime(queryNodeCostPerRAMGiBHr, end)
  1773. }
  1774. func (pds *PrometheusDataSource) QueryNodeCostPerGPUHr(start, end time.Time) source.QueryResultsChan {
  1775. const queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (node, %s, instance_type, provider_id)`
  1776. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1777. cfg := pds.promConfig
  1778. durStr := timeutil.DurationString(end.Sub(start))
  1779. if durStr == "" {
  1780. panic("failed to parse duration string passed to QueryNodeCostPerGPUHr")
  1781. }
  1782. queryNodeCostPerGPUHr := fmt.Sprintf(queryFmtNodeCostPerGPUHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1783. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1784. return ctx.QueryAtTime(queryNodeCostPerGPUHr, end)
  1785. }
  1786. func (pds *PrometheusDataSource) QueryNodeIsSpot2(start, end time.Time) source.QueryResultsChan {
  1787. const queryFmtNodeIsSpot = `avg_over_time(kubecost_node_is_spot{%s}[%s])`
  1788. // env.GetPromClusterFilter(), durStr)
  1789. cfg := pds.promConfig
  1790. durStr := timeutil.DurationString(end.Sub(start))
  1791. if durStr == "" {
  1792. panic("failed to parse duration string passed to QueryNodeIsSpot2")
  1793. }
  1794. queryNodeIsSpot := fmt.Sprintf(queryFmtNodeIsSpot, cfg.ClusterFilter, durStr)
  1795. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1796. return ctx.QueryAtTime(queryNodeIsSpot, end)
  1797. }
  1798. func (pds *PrometheusDataSource) QueryPVCInfo2(start, end time.Time) source.QueryResultsChan {
  1799. const queryFmtPVCInfo = `avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, volumename, namespace, %s)[%s:%s]`
  1800. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1801. cfg := pds.promConfig
  1802. resolution := cfg.DataResolution
  1803. resStr := timeutil.DurationString(resolution)
  1804. durStr := timeutil.DurationString(end.Sub(start))
  1805. if durStr == "" {
  1806. panic("failed to parse duration string passed to QueryPVCInfo2")
  1807. }
  1808. queryPVCInfo := fmt.Sprintf(queryFmtPVCInfo, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1809. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1810. return ctx.QueryAtTime(queryPVCInfo, end)
  1811. }
  1812. func (pds *PrometheusDataSource) QueryPodPVCAllocation(start, end time.Time) source.QueryResultsChan {
  1813. const queryFmtPodPVCAllocation = `avg(avg_over_time(pod_pvc_allocation{%s}[%s])) by (persistentvolume, persistentvolumeclaim, pod, namespace, %s)`
  1814. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1815. cfg := pds.promConfig
  1816. durStr := timeutil.DurationString(end.Sub(start))
  1817. if durStr == "" {
  1818. panic("failed to parse duration string passed to QueryPodPVCAllocation")
  1819. }
  1820. queryPodPVCAllocation := fmt.Sprintf(queryFmtPodPVCAllocation, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1821. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1822. return ctx.QueryAtTime(queryPodPVCAllocation, end)
  1823. }
  1824. func (pds *PrometheusDataSource) QueryPVCBytesRequested(start, end time.Time) source.QueryResultsChan {
  1825. const queryFmtPVCBytesRequested = `avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}[%s])) by (persistentvolumeclaim, namespace, %s)`
  1826. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1827. cfg := pds.promConfig
  1828. durStr := timeutil.DurationString(end.Sub(start))
  1829. if durStr == "" {
  1830. panic("failed to parse duration string passed to QueryPVCBytesRequested")
  1831. }
  1832. queryPVCBytesRequested := fmt.Sprintf(queryFmtPVCBytesRequested, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1833. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1834. return ctx.QueryAtTime(queryPVCBytesRequested, end)
  1835. }
  1836. func (pds *PrometheusDataSource) QueryPVActiveMins(start, end time.Time) source.QueryResultsChan {
  1837. const queryFmtPVActiveMins = `count(kube_persistentvolume_capacity_bytes{%s}) by (persistentvolume, %s)[%s:%s]`
  1838. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  1839. cfg := pds.promConfig
  1840. resolution := cfg.DataResolution
  1841. resStr := timeutil.DurationString(resolution)
  1842. durStr := timeutil.DurationString(end.Sub(start))
  1843. if durStr == "" {
  1844. panic("failed to parse duration string passed to QueryPVActiveMins")
  1845. }
  1846. queryPVActiveMins := fmt.Sprintf(queryFmtPVActiveMins, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  1847. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1848. return ctx.QueryAtTime(queryPVActiveMins, end)
  1849. }
  1850. func (pds *PrometheusDataSource) QueryPVBytes(start, end time.Time) source.QueryResultsChan {
  1851. const queryFmtPVBytes = `avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (persistentvolume, %s)`
  1852. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1853. cfg := pds.promConfig
  1854. durStr := timeutil.DurationString(end.Sub(start))
  1855. if durStr == "" {
  1856. panic("failed to parse duration string passed to QueryPVBytes")
  1857. }
  1858. queryPVBytes := fmt.Sprintf(queryFmtPVBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1859. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1860. return ctx.QueryAtTime(queryPVBytes, end)
  1861. }
  1862. func (pds *PrometheusDataSource) QueryPVCostPerGiBHour(start, end time.Time) source.QueryResultsChan {
  1863. const queryFmtPVCostPerGiBHour = `avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (volumename, %s)`
  1864. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1865. cfg := pds.promConfig
  1866. durStr := timeutil.DurationString(end.Sub(start))
  1867. if durStr == "" {
  1868. panic("failed to parse duration string passed to QueryPVCostPerGiBHour")
  1869. }
  1870. queryPVCostPerGiBHour := fmt.Sprintf(queryFmtPVCostPerGiBHour, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1871. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1872. return ctx.QueryAtTime(queryPVCostPerGiBHour, end)
  1873. }
  1874. func (pds *PrometheusDataSource) QueryPVMeta(start, end time.Time) source.QueryResultsChan {
  1875. const queryFmtPVMeta = `avg(avg_over_time(kubecost_pv_info{%s}[%s])) by (%s, persistentvolume, provider_id)`
  1876. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1877. cfg := pds.promConfig
  1878. durStr := timeutil.DurationString(end.Sub(start))
  1879. if durStr == "" {
  1880. panic("failed to parse duration string passed to QueryPVMeta")
  1881. }
  1882. queryPVMeta := fmt.Sprintf(queryFmtPVMeta, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1883. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1884. return ctx.QueryAtTime(queryPVMeta, end)
  1885. }
  1886. func (pds *PrometheusDataSource) QueryNetZoneGiB(start, end time.Time) source.QueryResultsChan {
  1887. 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`
  1888. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1889. cfg := pds.promConfig
  1890. durStr := timeutil.DurationString(end.Sub(start))
  1891. if durStr == "" {
  1892. panic("failed to parse duration string passed to QueryNetZoneGiB")
  1893. }
  1894. queryNetZoneGiB := fmt.Sprintf(queryFmtNetZoneGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1895. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1896. return ctx.QueryAtTime(queryNetZoneGiB, end)
  1897. }
  1898. func (pds *PrometheusDataSource) QueryNetZoneCostPerGiB(start, end time.Time) source.QueryResultsChan {
  1899. const queryFmtNetZoneCostPerGiB = `avg(avg_over_time(kubecost_network_zone_egress_cost{%s}[%s])) by (%s)`
  1900. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1901. cfg := pds.promConfig
  1902. durStr := timeutil.DurationString(end.Sub(start))
  1903. if durStr == "" {
  1904. panic("failed to parse duration string passed to QueryNetZoneCostPerGiB")
  1905. }
  1906. queryNetZoneCostPerGiB := fmt.Sprintf(queryFmtNetZoneCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1907. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1908. return ctx.QueryAtTime(queryNetZoneCostPerGiB, end)
  1909. }
  1910. func (pds *PrometheusDataSource) QueryNetRegionGiB(start, end time.Time) source.QueryResultsChan {
  1911. 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`
  1912. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1913. cfg := pds.promConfig
  1914. durStr := timeutil.DurationString(end.Sub(start))
  1915. if durStr == "" {
  1916. panic("failed to parse duration string passed to QueryNetRegionGiB")
  1917. }
  1918. queryNetRegionGiB := fmt.Sprintf(queryFmtNetRegionGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1919. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1920. return ctx.QueryAtTime(queryNetRegionGiB, end)
  1921. }
  1922. func (pds *PrometheusDataSource) QueryNetRegionCostPerGiB(start, end time.Time) source.QueryResultsChan {
  1923. const queryFmtNetRegionCostPerGiB = `avg(avg_over_time(kubecost_network_region_egress_cost{%s}[%s])) by (%s)`
  1924. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1925. cfg := pds.promConfig
  1926. durStr := timeutil.DurationString(end.Sub(start))
  1927. if durStr == "" {
  1928. panic("failed to parse duration string passed to QueryNetRegionCostPerGiB")
  1929. }
  1930. queryNetRegionCostPerGiB := fmt.Sprintf(queryFmtNetRegionCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1931. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1932. return ctx.QueryAtTime(queryNetRegionCostPerGiB, end)
  1933. }
  1934. func (pds *PrometheusDataSource) QueryNetInternetGiB(start, end time.Time) source.QueryResultsChan {
  1935. const queryFmtNetInternetGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  1936. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1937. cfg := pds.promConfig
  1938. durStr := timeutil.DurationString(end.Sub(start))
  1939. if durStr == "" {
  1940. panic("failed to parse duration string passed to QueryNetInternetGiB")
  1941. }
  1942. queryNetInternetGiB := fmt.Sprintf(queryFmtNetInternetGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1943. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1944. return ctx.QueryAtTime(queryNetInternetGiB, end)
  1945. }
  1946. func (pds *PrometheusDataSource) QueryNetInternetCostPerGiB(start, end time.Time) source.QueryResultsChan {
  1947. const queryFmtNetInternetCostPerGiB = `avg(avg_over_time(kubecost_network_internet_egress_cost{%s}[%s])) by (%s)`
  1948. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel()
  1949. cfg := pds.promConfig
  1950. durStr := timeutil.DurationString(end.Sub(start))
  1951. if durStr == "" {
  1952. panic("failed to parse duration string passed to QueryNetInternetCostPerGiB")
  1953. }
  1954. queryNetInternetCostPerGiB := fmt.Sprintf(queryFmtNetInternetCostPerGiB, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1955. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1956. return ctx.QueryAtTime(queryNetInternetCostPerGiB, end)
  1957. }
  1958. func (pds *PrometheusDataSource) QueryNetReceiveBytes(start, end time.Time) source.QueryResultsChan {
  1959. const queryFmtNetReceiveBytes = `sum(increase(container_network_receive_bytes_total{pod!="", %s}[%s])) by (pod_name, pod, namespace, %s)`
  1960. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1961. cfg := pds.promConfig
  1962. durStr := timeutil.DurationString(end.Sub(start))
  1963. if durStr == "" {
  1964. panic("failed to parse duration string passed to QueryNetReceiveBytes")
  1965. }
  1966. queryNetReceiveBytes := fmt.Sprintf(queryFmtNetReceiveBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1967. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1968. return ctx.QueryAtTime(queryNetReceiveBytes, end)
  1969. }
  1970. func (pds *PrometheusDataSource) QueryNetTransferBytes(start, end time.Time) source.QueryResultsChan {
  1971. const queryFmtNetTransferBytes = `sum(increase(container_network_transmit_bytes_total{pod!="", %s}[%s])) by (pod_name, pod, namespace, %s)`
  1972. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  1973. cfg := pds.promConfig
  1974. durStr := timeutil.DurationString(end.Sub(start))
  1975. if durStr == "" {
  1976. panic("failed to parse duration string passed to QueryNetTransferBytes")
  1977. }
  1978. queryNetTransferBytes := fmt.Sprintf(queryFmtNetTransferBytes, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  1979. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1980. return ctx.QueryAtTime(queryNetTransferBytes, end)
  1981. }
  1982. func (pds *PrometheusDataSource) QueryNodeLabels2(start, end time.Time) source.QueryResultsChan {
  1983. const queryFmtNodeLabels = `avg_over_time(kube_node_labels{%s}[%s])`
  1984. // env.GetPromClusterFilter(), durStr
  1985. cfg := pds.promConfig
  1986. durStr := timeutil.DurationString(end.Sub(start))
  1987. if durStr == "" {
  1988. panic("failed to parse duration string passed to QueryNodeLabels2")
  1989. }
  1990. queryNodeLabels := fmt.Sprintf(queryFmtNodeLabels, cfg.ClusterFilter, durStr)
  1991. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  1992. return ctx.QueryAtTime(queryNodeLabels, end)
  1993. }
  1994. func (pds *PrometheusDataSource) QueryNamespaceLabels(start, end time.Time) source.QueryResultsChan {
  1995. const queryFmtNamespaceLabels = `avg_over_time(kube_namespace_labels{%s}[%s])`
  1996. // env.GetPromClusterFilter(), durStr
  1997. cfg := pds.promConfig
  1998. durStr := timeutil.DurationString(end.Sub(start))
  1999. if durStr == "" {
  2000. panic("failed to parse duration string passed to QueryNamespaceLabels")
  2001. }
  2002. queryNamespaceLabels := fmt.Sprintf(queryFmtNamespaceLabels, cfg.ClusterFilter, durStr)
  2003. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2004. return ctx.QueryAtTime(queryNamespaceLabels, end)
  2005. }
  2006. func (pds *PrometheusDataSource) QueryNamespaceAnnotations(start, end time.Time) source.QueryResultsChan {
  2007. const queryFmtNamespaceAnnotations = `avg_over_time(kube_namespace_annotations{%s}[%s])`
  2008. // env.GetPromClusterFilter(), durStr
  2009. cfg := pds.promConfig
  2010. durStr := timeutil.DurationString(end.Sub(start))
  2011. if durStr == "" {
  2012. panic("failed to parse duration string passed to QueryNamespaceAnnotations")
  2013. }
  2014. queryNamespaceAnnotations := fmt.Sprintf(queryFmtNamespaceAnnotations, cfg.ClusterFilter, durStr)
  2015. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2016. return ctx.QueryAtTime(queryNamespaceAnnotations, end)
  2017. }
  2018. func (pds *PrometheusDataSource) QueryPodLabels(start, end time.Time) source.QueryResultsChan {
  2019. const queryFmtPodLabels = `avg_over_time(kube_pod_labels{%s}[%s])`
  2020. // env.GetPromClusterFilter(), durStr
  2021. cfg := pds.promConfig
  2022. durStr := timeutil.DurationString(end.Sub(start))
  2023. if durStr == "" {
  2024. panic("failed to parse duration string passed to QueryPodLabels")
  2025. }
  2026. queryPodLabels := fmt.Sprintf(queryFmtPodLabels, cfg.ClusterFilter, durStr)
  2027. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2028. return ctx.QueryAtTime(queryPodLabels, end)
  2029. }
  2030. func (pds *PrometheusDataSource) QueryPodAnnotations(start, end time.Time) source.QueryResultsChan {
  2031. const queryFmtPodAnnotations = `avg_over_time(kube_pod_annotations{%s}[%s])`
  2032. // env.GetPromClusterFilter(), durStr
  2033. cfg := pds.promConfig
  2034. durStr := timeutil.DurationString(end.Sub(start))
  2035. if durStr == "" {
  2036. panic("failed to parse duration string passed to QueryPodAnnotations")
  2037. }
  2038. queryPodAnnotations := fmt.Sprintf(queryFmtPodAnnotations, cfg.ClusterFilter, durStr)
  2039. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2040. return ctx.QueryAtTime(queryPodAnnotations, end)
  2041. }
  2042. func (pds *PrometheusDataSource) QueryServiceLabels(start, end time.Time) source.QueryResultsChan {
  2043. const queryFmtServiceLabels = `avg_over_time(service_selector_labels{%s}[%s])`
  2044. // env.GetPromClusterFilter(), durStr
  2045. cfg := pds.promConfig
  2046. durStr := timeutil.DurationString(end.Sub(start))
  2047. if durStr == "" {
  2048. panic("failed to parse duration string passed to QueryServiceLabels")
  2049. }
  2050. queryServiceLabels := fmt.Sprintf(queryFmtServiceLabels, cfg.ClusterFilter, durStr)
  2051. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2052. return ctx.QueryAtTime(queryServiceLabels, end)
  2053. }
  2054. func (pds *PrometheusDataSource) QueryDeploymentLabels(start, end time.Time) source.QueryResultsChan {
  2055. const queryFmtDeploymentLabels = `avg_over_time(deployment_match_labels{%s}[%s])`
  2056. // env.GetPromClusterFilter(), durStr
  2057. cfg := pds.promConfig
  2058. durStr := timeutil.DurationString(end.Sub(start))
  2059. if durStr == "" {
  2060. panic("failed to parse duration string passed to QueryNamespaceAnnotations")
  2061. }
  2062. queryDeploymentLabels := fmt.Sprintf(queryFmtDeploymentLabels, cfg.ClusterFilter, durStr)
  2063. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2064. return ctx.QueryAtTime(queryDeploymentLabels, end)
  2065. }
  2066. func (pds *PrometheusDataSource) QueryStatefulSetLabels(start, end time.Time) source.QueryResultsChan {
  2067. const queryFmtStatefulSetLabels = `avg_over_time(statefulSet_match_labels{%s}[%s])`
  2068. // env.GetPromClusterFilter(), durStr
  2069. cfg := pds.promConfig
  2070. durStr := timeutil.DurationString(end.Sub(start))
  2071. if durStr == "" {
  2072. panic("failed to parse duration string passed to QueryStatefulSetLabels")
  2073. }
  2074. queryStatefulSetLabels := fmt.Sprintf(queryFmtStatefulSetLabels, cfg.ClusterFilter, durStr)
  2075. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2076. return ctx.QueryAtTime(queryStatefulSetLabels, end)
  2077. }
  2078. func (pds *PrometheusDataSource) QueryDaemonSetLabels(start, end time.Time) source.QueryResultsChan {
  2079. const queryFmtDaemonSetLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet", %s}[%s])) by (pod, owner_name, namespace, %s)`
  2080. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2081. cfg := pds.promConfig
  2082. durStr := timeutil.DurationString(end.Sub(start))
  2083. if durStr == "" {
  2084. panic("failed to parse duration string passed to QueryDaemonSetLabels")
  2085. }
  2086. queryDaemonSetLabels := fmt.Sprintf(queryFmtDaemonSetLabels, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2087. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2088. return ctx.QueryAtTime(queryDaemonSetLabels, end)
  2089. }
  2090. func (pds *PrometheusDataSource) QueryJobLabels(start, end time.Time) source.QueryResultsChan {
  2091. const queryFmtJobLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="Job", %s}[%s])) by (pod, owner_name, namespace ,%s)`
  2092. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2093. cfg := pds.promConfig
  2094. durStr := timeutil.DurationString(end.Sub(start))
  2095. if durStr == "" {
  2096. panic("failed to parse duration string passed to QueryJobLabels")
  2097. }
  2098. queryJobLabels := fmt.Sprintf(queryFmtJobLabels, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2099. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2100. return ctx.QueryAtTime(queryJobLabels, end)
  2101. }
  2102. func (pds *PrometheusDataSource) QueryPodsWithReplicaSetOwner(start, end time.Time) source.QueryResultsChan {
  2103. const queryFmtPodsWithReplicaSetOwner = `sum(avg_over_time(kube_pod_owner{owner_kind="ReplicaSet", %s}[%s])) by (pod, owner_name, namespace ,%s)`
  2104. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2105. cfg := pds.promConfig
  2106. durStr := timeutil.DurationString(end.Sub(start))
  2107. if durStr == "" {
  2108. panic("failed to parse duration string passed to QueryPodsWithReplicaSetOwner")
  2109. }
  2110. queryPodsWithReplicaSetOwner := fmt.Sprintf(queryFmtPodsWithReplicaSetOwner, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2111. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2112. return ctx.QueryAtTime(queryPodsWithReplicaSetOwner, end)
  2113. }
  2114. func (pds *PrometheusDataSource) QueryReplicaSetsWithoutOwners(start, end time.Time) source.QueryResultsChan {
  2115. const queryFmtReplicaSetsWithoutOwners = `avg(avg_over_time(kube_replicaset_owner{owner_kind="<none>", owner_name="<none>", %s}[%s])) by (replicaset, namespace, %s)`
  2116. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2117. cfg := pds.promConfig
  2118. durStr := timeutil.DurationString(end.Sub(start))
  2119. if durStr == "" {
  2120. panic("failed to parse duration string passed to QueryReplicaSetsWithoutOwners")
  2121. }
  2122. queryReplicaSetsWithoutOwners := fmt.Sprintf(queryFmtReplicaSetsWithoutOwners, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2123. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2124. return ctx.QueryAtTime(queryReplicaSetsWithoutOwners, end)
  2125. }
  2126. func (pds *PrometheusDataSource) QueryReplicaSetsWithRollout(start, end time.Time) source.QueryResultsChan {
  2127. const queryFmtReplicaSetsWithRolloutOwner = `avg(avg_over_time(kube_replicaset_owner{owner_kind="Rollout", %s}[%s])) by (replicaset, namespace, owner_kind, owner_name, %s)`
  2128. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2129. cfg := pds.promConfig
  2130. durStr := timeutil.DurationString(end.Sub(start))
  2131. if durStr == "" {
  2132. panic("failed to parse duration string passed to QueryReplicaSetsWithRollout")
  2133. }
  2134. queryReplicaSetsWithRolloutOwner := fmt.Sprintf(queryFmtReplicaSetsWithRolloutOwner, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2135. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2136. return ctx.QueryAtTime(queryReplicaSetsWithRolloutOwner, end)
  2137. }
  2138. func (pds *PrometheusDataSource) QueryLBCostPerHr(start, end time.Time) source.QueryResultsChan {
  2139. const queryFmtLBCostPerHr = `avg(avg_over_time(kubecost_load_balancer_cost{%s}[%s])) by (namespace, service_name, ingress_ip, %s)`
  2140. // env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  2141. cfg := pds.promConfig
  2142. durStr := timeutil.DurationString(end.Sub(start))
  2143. if durStr == "" {
  2144. panic("failed to parse duration string passed to QueryLBCostPerHr")
  2145. }
  2146. queryLBCostPerHr := fmt.Sprintf(queryFmtLBCostPerHr, cfg.ClusterFilter, durStr, cfg.ClusterLabel)
  2147. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2148. return ctx.QueryAtTime(queryLBCostPerHr, end)
  2149. }
  2150. func (pds *PrometheusDataSource) QueryLBActiveMins(start, end time.Time) source.QueryResultsChan {
  2151. const queryFmtLBActiveMins = `count(kubecost_load_balancer_cost{%s}) by (namespace, service_name, %s)[%s:%s]`
  2152. // env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, resStr)
  2153. cfg := pds.promConfig
  2154. resolution := cfg.DataResolution
  2155. resStr := timeutil.DurationString(resolution)
  2156. durStr := timeutil.DurationString(end.Sub(start))
  2157. if durStr == "" {
  2158. panic("failed to parse duration string passed to QueryLBActiveMins")
  2159. }
  2160. queryLBActiveMins := fmt.Sprintf(queryFmtLBActiveMins, cfg.ClusterFilter, cfg.ClusterLabel, durStr, resStr)
  2161. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2162. return ctx.QueryAtTime(queryLBActiveMins, end)
  2163. }
  2164. func (pds *PrometheusDataSource) QueryDataCoverage(limitDays int) (time.Time, time.Time, error) {
  2165. const (
  2166. queryFmtOldestSample = `min_over_time(timestamp(group(node_cpu_hourly_cost{%s}))[%s:%s])`
  2167. queryFmtNewestSample = `max_over_time(timestamp(group(node_cpu_hourly_cost{%s}))[%s:%s])`
  2168. )
  2169. cfg := pds.promConfig
  2170. now := time.Now()
  2171. durStr := fmt.Sprintf("%dd", limitDays)
  2172. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2173. queryOldest := fmt.Sprintf(queryFmtOldestSample, cfg.ClusterFilter, durStr, "1h")
  2174. resOldestFut := ctx.QueryAtTime(queryOldest, now)
  2175. resOldest, err := resOldestFut.Await()
  2176. if err != nil {
  2177. return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
  2178. }
  2179. if len(resOldest) == 0 || len(resOldest[0].Values) == 0 {
  2180. return time.Time{}, time.Time{}, fmt.Errorf("querying oldest sample: %w", err)
  2181. }
  2182. oldest := time.Unix(int64(resOldest[0].Values[0].Value), 0)
  2183. queryNewest := fmt.Sprintf(queryFmtNewestSample, cfg.ClusterFilter, durStr, "1h")
  2184. resNewestFut := ctx.QueryAtTime(queryNewest, now)
  2185. resNewest, err := resNewestFut.Await()
  2186. if err != nil {
  2187. return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: %w", err)
  2188. }
  2189. if len(resNewest) == 0 || len(resNewest[0].Values) == 0 {
  2190. return time.Time{}, time.Time{}, fmt.Errorf("querying newest sample: %w", err)
  2191. }
  2192. newest := time.Unix(int64(resNewest[0].Values[0].Value), 0)
  2193. return oldest, newest, nil
  2194. }
  2195. func (pds *PrometheusDataSource) QueryIsGPUShared(start, end time.Time) source.QueryResultsChan {
  2196. 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)`
  2197. // env.GetPromClusterFilter(), durStr
  2198. cfg := pds.promConfig
  2199. durStr := timeutil.DurationString(end.Sub(start))
  2200. if durStr == "" {
  2201. panic("failed to parse duration string passed to QueryIsGPUShared")
  2202. }
  2203. queryIsGPUShared := fmt.Sprintf(queryFmtIsGPUShared, cfg.ClusterFilter, durStr)
  2204. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2205. return ctx.QueryAtTime(queryIsGPUShared, end)
  2206. }
  2207. func (pds *PrometheusDataSource) QueryGetGPUInfo(start, end time.Time) source.QueryResultsChan {
  2208. const queryFmtGetGPUInfo = `avg(avg_over_time(DCGM_FI_DEV_DEC_UTIL{container!="",%s}[%s])) by (container, pod, namespace, device, modelName, UUID)`
  2209. // env.GetPromClusterFilter(), durStr
  2210. cfg := pds.promConfig
  2211. durStr := timeutil.DurationString(end.Sub(start))
  2212. if durStr == "" {
  2213. panic("failed to parse duration string passed to QueryGetGPUInfo")
  2214. }
  2215. queryGetGPUInfo := fmt.Sprintf(queryFmtGetGPUInfo, cfg.ClusterFilter, durStr)
  2216. ctx := pds.promContexts.NewNamedContext(AllocationContextName)
  2217. return ctx.QueryAtTime(queryGetGPUInfo, end)
  2218. }
  2219. func newEmptyResult() source.QueryResultsChan {
  2220. ch := make(source.QueryResultsChan)
  2221. go func() {
  2222. results := source.NewQueryResults("")
  2223. ch <- results
  2224. }()
  2225. return ch
  2226. }
  2227. func wrapResults(query string, results []*source.QueryResult) source.QueryResultsChan {
  2228. ch := make(source.QueryResultsChan)
  2229. go func() {
  2230. r := source.NewQueryResults(query)
  2231. r.Results = results
  2232. ch <- r
  2233. }()
  2234. return ch
  2235. }
  2236. func snapResolutionMinute(res time.Duration) time.Duration {
  2237. resMins := int64(math.Trunc(res.Minutes()))
  2238. if resMins <= 0 {
  2239. resMins = 1
  2240. }
  2241. return time.Duration(resMins) * time.Minute
  2242. }
  2243. func formatResolutionMinutes(resMins int64) string {
  2244. if resMins%60 == 0 {
  2245. return fmt.Sprintf("%dh", resMins/60)
  2246. }
  2247. return fmt.Sprintf("%dm", resMins)
  2248. }