datasource.go 121 KB

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