datasource.go 95 KB

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