cluster.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/kubecost/cost-model/pkg/cloud"
  6. "github.com/kubecost/cost-model/pkg/env"
  7. "github.com/kubecost/cost-model/pkg/log"
  8. "github.com/kubecost/cost-model/pkg/prom"
  9. "github.com/kubecost/cost-model/pkg/util"
  10. prometheus "github.com/prometheus/client_golang/api"
  11. "k8s.io/klog"
  12. )
  13. const (
  14. queryClusterCores = `sum(
  15. avg(avg_over_time(kube_node_status_capacity_cpu_cores[%s] %s)) by (node, cluster_id) * avg(avg_over_time(node_cpu_hourly_cost[%s] %s)) by (node, cluster_id) * 730 +
  16. avg(avg_over_time(node_gpu_hourly_cost[%s] %s)) by (node, cluster_id) * 730
  17. ) by (cluster_id)`
  18. queryClusterRAM = `sum(
  19. avg(avg_over_time(kube_node_status_capacity_memory_bytes[%s] %s)) by (node, cluster_id) / 1024 / 1024 / 1024 * avg(avg_over_time(node_ram_hourly_cost[%s] %s)) by (node, cluster_id) * 730
  20. ) by (cluster_id)`
  21. queryStorage = `sum(
  22. avg(avg_over_time(pv_hourly_cost[%s] %s)) by (persistentvolume, cluster_id) * 730
  23. * avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s] %s)) by (persistentvolume, cluster_id) / 1024 / 1024 / 1024
  24. ) by (cluster_id) %s`
  25. queryTotal = `sum(avg(node_total_hourly_cost) by (node, cluster_id)) * 730 +
  26. sum(
  27. avg(avg_over_time(pv_hourly_cost[1h])) by (persistentvolume, cluster_id) * 730
  28. * avg(avg_over_time(kube_persistentvolume_capacity_bytes[1h])) by (persistentvolume, cluster_id) / 1024 / 1024 / 1024
  29. ) by (cluster_id) %s`
  30. queryNodes = `sum(avg(node_total_hourly_cost) by (node, cluster_id)) * 730 %s`
  31. )
  32. // Costs represents cumulative and monthly cluster costs over a given duration. Costs
  33. // are broken down by cores, memory, and storage.
  34. type ClusterCosts struct {
  35. Start *time.Time `json:"startTime"`
  36. End *time.Time `json:"endTime"`
  37. CPUCumulative float64 `json:"cpuCumulativeCost"`
  38. CPUMonthly float64 `json:"cpuMonthlyCost"`
  39. CPUBreakdown *ClusterCostsBreakdown `json:"cpuBreakdown"`
  40. GPUCumulative float64 `json:"gpuCumulativeCost"`
  41. GPUMonthly float64 `json:"gpuMonthlyCost"`
  42. RAMCumulative float64 `json:"ramCumulativeCost"`
  43. RAMMonthly float64 `json:"ramMonthlyCost"`
  44. RAMBreakdown *ClusterCostsBreakdown `json:"ramBreakdown"`
  45. StorageCumulative float64 `json:"storageCumulativeCost"`
  46. StorageMonthly float64 `json:"storageMonthlyCost"`
  47. StorageBreakdown *ClusterCostsBreakdown `json:"storageBreakdown"`
  48. TotalCumulative float64 `json:"totalCumulativeCost"`
  49. TotalMonthly float64 `json:"totalMonthlyCost"`
  50. DataMinutes float64
  51. }
  52. // ClusterCostsBreakdown provides percentage-based breakdown of a resource by
  53. // categories: user for user-space (i.e. non-system) usage, system, and idle.
  54. type ClusterCostsBreakdown struct {
  55. Idle float64 `json:"idle"`
  56. Other float64 `json:"other"`
  57. System float64 `json:"system"`
  58. User float64 `json:"user"`
  59. }
  60. // NewClusterCostsFromCumulative takes cumulative cost data over a given time range, computes
  61. // the associated monthly rate data, and returns the Costs.
  62. func NewClusterCostsFromCumulative(cpu, gpu, ram, storage float64, window, offset string, dataHours float64) (*ClusterCosts, error) {
  63. start, end, err := util.ParseTimeRange(window, offset)
  64. if err != nil {
  65. return nil, err
  66. }
  67. // If the number of hours is not given (i.e. is zero) compute one from the window and offset
  68. if dataHours == 0 {
  69. dataHours = end.Sub(*start).Hours()
  70. }
  71. // Do not allow zero-length windows to prevent divide-by-zero issues
  72. if dataHours == 0 {
  73. return nil, fmt.Errorf("illegal time range: window %s, offset %s", window, offset)
  74. }
  75. cc := &ClusterCosts{
  76. Start: start,
  77. End: end,
  78. CPUCumulative: cpu,
  79. GPUCumulative: gpu,
  80. RAMCumulative: ram,
  81. StorageCumulative: storage,
  82. TotalCumulative: cpu + gpu + ram + storage,
  83. CPUMonthly: cpu / dataHours * (util.HoursPerMonth),
  84. GPUMonthly: gpu / dataHours * (util.HoursPerMonth),
  85. RAMMonthly: ram / dataHours * (util.HoursPerMonth),
  86. StorageMonthly: storage / dataHours * (util.HoursPerMonth),
  87. }
  88. cc.TotalMonthly = cc.CPUMonthly + cc.GPUMonthly + cc.RAMMonthly + cc.StorageMonthly
  89. return cc, nil
  90. }
  91. type Disk struct {
  92. Cluster string
  93. Name string
  94. ProviderID string
  95. Cost float64
  96. Bytes float64
  97. Local bool
  98. Start time.Time
  99. End time.Time
  100. Minutes float64
  101. Breakdown *ClusterCostsBreakdown
  102. }
  103. func ClusterDisks(client prometheus.Client, provider cloud.Provider, duration, offset time.Duration) (map[string]*Disk, error) {
  104. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  105. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  106. if offset < time.Minute {
  107. offsetStr = ""
  108. }
  109. // minsPerResolution determines accuracy and resource use for the following
  110. // queries. Smaller values (higher resolution) result in better accuracy,
  111. // but more expensive queries, and vice-a-versa.
  112. minsPerResolution := 1
  113. resolution := time.Duration(minsPerResolution) * time.Minute
  114. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  115. // value, converts it to a cumulative value; i.e.
  116. // [$/hr] * [min/res]*[hr/min] = [$/res]
  117. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  118. // TODO niko/assets how do we not hard-code this price?
  119. costPerGBHr := 0.04 / 730.0
  120. ctx := prom.NewContext(client)
  121. queryPVCost := fmt.Sprintf(`sum_over_time((avg(kube_persistentvolume_capacity_bytes) by (cluster_id, persistentvolume) * on(cluster_id, persistentvolume) group_right avg(pv_hourly_cost) by (cluster_id, persistentvolume,provider_id))[%s:%dm]%s)/1024/1024/1024 * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  122. queryPVSize := fmt.Sprintf(`avg_over_time(kube_persistentvolume_capacity_bytes[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  123. queryActiveMins := fmt.Sprintf(`count(pv_hourly_cost) by (cluster_id, persistentvolume)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  124. queryLocalStorageCost := fmt.Sprintf(`sum_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 * %f * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative, costPerGBHr)
  125. queryLocalStorageUsedCost := fmt.Sprintf(`sum_over_time(sum(container_fs_usage_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 * %f * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative, costPerGBHr)
  126. queryLocalStorageBytes := fmt.Sprintf(`avg_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  127. queryLocalActiveMins := fmt.Sprintf(`count(node_total_hourly_cost) by (cluster_id, node)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  128. resChPVCost := ctx.Query(queryPVCost)
  129. resChPVSize := ctx.Query(queryPVSize)
  130. resChActiveMins := ctx.Query(queryActiveMins)
  131. resChLocalStorageCost := ctx.Query(queryLocalStorageCost)
  132. resChLocalStorageUsedCost := ctx.Query(queryLocalStorageUsedCost)
  133. resChLocalStorageBytes := ctx.Query(queryLocalStorageBytes)
  134. resChLocalActiveMins := ctx.Query(queryLocalActiveMins)
  135. resPVCost, _ := resChPVCost.Await()
  136. resPVSize, _ := resChPVSize.Await()
  137. resActiveMins, _ := resChActiveMins.Await()
  138. resLocalStorageCost, _ := resChLocalStorageCost.Await()
  139. resLocalStorageUsedCost, _ := resChLocalStorageUsedCost.Await()
  140. resLocalStorageBytes, _ := resChLocalStorageBytes.Await()
  141. resLocalActiveMins, _ := resChLocalActiveMins.Await()
  142. if ctx.HasErrors() {
  143. return nil, ctx.ErrorCollection()
  144. }
  145. diskMap := map[string]*Disk{}
  146. for _, result := range resPVCost {
  147. cluster, err := result.GetString("cluster_id")
  148. if err != nil {
  149. cluster = env.GetClusterID()
  150. }
  151. name, err := result.GetString("persistentvolume")
  152. if err != nil {
  153. log.Warningf("ClusterDisks: PV cost data missing persistentvolume")
  154. continue
  155. }
  156. // TODO niko/assets storage class
  157. cost := result.Values[0].Value
  158. key := fmt.Sprintf("%s/%s", cluster, name)
  159. if _, ok := diskMap[key]; !ok {
  160. diskMap[key] = &Disk{
  161. Cluster: cluster,
  162. Name: name,
  163. Breakdown: &ClusterCostsBreakdown{},
  164. }
  165. }
  166. diskMap[key].Cost += cost
  167. providerID, _ := result.GetString("provider_id") // just put the providerID set up here, it's the simplest query.
  168. if providerID != "" {
  169. diskMap[key].ProviderID = provider.ParsePVID(providerID)
  170. }
  171. }
  172. for _, result := range resPVSize {
  173. cluster, err := result.GetString("cluster_id")
  174. if err != nil {
  175. cluster = env.GetClusterID()
  176. }
  177. name, err := result.GetString("persistentvolume")
  178. if err != nil {
  179. log.Warningf("ClusterDisks: PV size data missing persistentvolume")
  180. continue
  181. }
  182. // TODO niko/assets storage class
  183. bytes := result.Values[0].Value
  184. key := fmt.Sprintf("%s/%s", cluster, name)
  185. if _, ok := diskMap[key]; !ok {
  186. diskMap[key] = &Disk{
  187. Cluster: cluster,
  188. Name: name,
  189. Breakdown: &ClusterCostsBreakdown{},
  190. }
  191. }
  192. diskMap[key].Bytes = bytes
  193. }
  194. for _, result := range resLocalStorageCost {
  195. cluster, err := result.GetString("cluster_id")
  196. if err != nil {
  197. cluster = env.GetClusterID()
  198. }
  199. name, err := result.GetString("instance")
  200. if err != nil {
  201. log.Warningf("ClusterDisks: local storage data missing instance")
  202. continue
  203. }
  204. cost := result.Values[0].Value
  205. key := fmt.Sprintf("%s/%s", cluster, name)
  206. if _, ok := diskMap[key]; !ok {
  207. diskMap[key] = &Disk{
  208. Cluster: cluster,
  209. Name: name,
  210. Breakdown: &ClusterCostsBreakdown{},
  211. Local: true,
  212. }
  213. }
  214. diskMap[key].Cost += cost
  215. }
  216. for _, result := range resLocalStorageUsedCost {
  217. cluster, err := result.GetString("cluster_id")
  218. if err != nil {
  219. cluster = env.GetClusterID()
  220. }
  221. name, err := result.GetString("instance")
  222. if err != nil {
  223. log.Warningf("ClusterDisks: local storage usage data missing instance")
  224. continue
  225. }
  226. cost := result.Values[0].Value
  227. key := fmt.Sprintf("%s/%s", cluster, name)
  228. if _, ok := diskMap[key]; !ok {
  229. diskMap[key] = &Disk{
  230. Cluster: cluster,
  231. Name: name,
  232. Breakdown: &ClusterCostsBreakdown{},
  233. Local: true,
  234. }
  235. }
  236. diskMap[key].Breakdown.System = cost / diskMap[key].Cost
  237. }
  238. for _, result := range resLocalStorageBytes {
  239. cluster, err := result.GetString("cluster_id")
  240. if err != nil {
  241. cluster = env.GetClusterID()
  242. }
  243. name, err := result.GetString("instance")
  244. if err != nil {
  245. log.Warningf("ClusterDisks: local storage data missing instance")
  246. continue
  247. }
  248. bytes := result.Values[0].Value
  249. key := fmt.Sprintf("%s/%s", cluster, name)
  250. if _, ok := diskMap[key]; !ok {
  251. diskMap[key] = &Disk{
  252. Cluster: cluster,
  253. Name: name,
  254. Breakdown: &ClusterCostsBreakdown{},
  255. Local: true,
  256. }
  257. }
  258. diskMap[key].Bytes = bytes
  259. }
  260. for _, result := range resActiveMins {
  261. cluster, err := result.GetString("cluster_id")
  262. if err != nil {
  263. cluster = env.GetClusterID()
  264. }
  265. name, err := result.GetString("persistentvolume")
  266. if err != nil {
  267. log.Warningf("ClusterDisks: active mins missing instance")
  268. continue
  269. }
  270. key := fmt.Sprintf("%s/%s", cluster, name)
  271. if _, ok := diskMap[key]; !ok {
  272. log.Warningf("ClusterDisks: active mins for unidentified disk")
  273. continue
  274. }
  275. if len(result.Values) == 0 {
  276. continue
  277. }
  278. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  279. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  280. mins := e.Sub(s).Minutes()
  281. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  282. diskMap[key].End = e
  283. diskMap[key].Start = s
  284. diskMap[key].Minutes = mins
  285. }
  286. for _, result := range resLocalActiveMins {
  287. cluster, err := result.GetString("cluster_id")
  288. if err != nil {
  289. cluster = env.GetClusterID()
  290. }
  291. name, err := result.GetString("node")
  292. if err != nil {
  293. log.Warningf("ClusterDisks: local active mins data missing instance")
  294. continue
  295. }
  296. key := fmt.Sprintf("%s/%s", cluster, name)
  297. if _, ok := diskMap[key]; !ok {
  298. log.Warningf("ClusterDisks: local active mins for unidentified disk")
  299. continue
  300. }
  301. if len(result.Values) == 0 {
  302. continue
  303. }
  304. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  305. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  306. mins := e.Sub(s).Minutes()
  307. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  308. diskMap[key].End = e
  309. diskMap[key].Start = s
  310. diskMap[key].Minutes = mins
  311. }
  312. for _, disk := range diskMap {
  313. // Apply all remaining RAM to Idle
  314. disk.Breakdown.Idle = 1.0 - (disk.Breakdown.System + disk.Breakdown.Other + disk.Breakdown.User)
  315. }
  316. return diskMap, nil
  317. }
  318. type Node struct {
  319. Cluster string
  320. Name string
  321. ProviderID string
  322. NodeType string
  323. CPUCost float64
  324. CPUCores float64
  325. GPUCost float64
  326. RAMCost float64
  327. RAMBytes float64
  328. Discount float64
  329. Preemptible bool
  330. CPUBreakdown *ClusterCostsBreakdown
  331. RAMBreakdown *ClusterCostsBreakdown
  332. Start time.Time
  333. End time.Time
  334. Minutes float64
  335. }
  336. var partialCPUMap = map[string]float64{
  337. "e2-micro": 0.25,
  338. "e2-small": 0.5,
  339. "e2-medium": 1.0,
  340. }
  341. func ClusterNodes(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*Node, error) {
  342. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  343. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  344. if offset < time.Minute {
  345. offsetStr = ""
  346. }
  347. // minsPerResolution determines accuracy and resource use for the following
  348. // queries. Smaller values (higher resolution) result in better accuracy,
  349. // but more expensive queries, and vice-a-versa.
  350. minsPerResolution := 1
  351. resolution := time.Duration(minsPerResolution) * time.Minute
  352. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  353. // value, converts it to a cumulative value; i.e.
  354. // [$/hr] * [min/res]*[hr/min] = [$/res]
  355. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  356. requiredCtx := prom.NewContext(client)
  357. optionalCtx := prom.NewContext(client)
  358. queryNodeCPUCost := fmt.Sprintf(`sum_over_time((avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node) * on(node, cluster_id) group_right avg(node_cpu_hourly_cost) by (cluster_id, node, instance_type, provider_id))[%s:%dm]%s) * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  359. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  360. queryNodeRAMCost := fmt.Sprintf(`sum_over_time((avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node) * on(cluster_id, node) group_right avg(node_ram_hourly_cost) by (cluster_id, node, instance_type, provider_id))[%s:%dm]%s) / 1024 / 1024 / 1024 * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  361. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  362. queryNodeGPUCost := fmt.Sprintf(`sum_over_time((avg(node_gpu_hourly_cost * %d.0 / 60.0) by (cluster_id, node, provider_id))[%s:%dm]%s)`, minsPerResolution, durationStr, minsPerResolution, offsetStr)
  363. queryNodeLabels := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  364. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total[%s:%dm]%s)) by (kubernetes_node, cluster_id, mode)`, durationStr, minsPerResolution, offsetStr)
  365. queryNodeRAMSystemPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (instance, cluster_id) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (node, cluster_id), "instance", "$1", "node", "(.*)")) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  366. queryNodeRAMUserPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace!="kube-system"}[%s:%dm]%s)) by (instance, cluster_id) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (node, cluster_id), "instance", "$1", "node", "(.*)")) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  367. queryActiveMins := fmt.Sprintf(`avg(node_total_hourly_cost) by (node,cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  368. // Return errors if these fail
  369. resChNodeCPUCost := requiredCtx.Query(queryNodeCPUCost)
  370. resChNodeCPUCores := requiredCtx.Query(queryNodeCPUCores)
  371. resChNodeRAMCost := requiredCtx.Query(queryNodeRAMCost)
  372. resChNodeRAMBytes := requiredCtx.Query(queryNodeRAMBytes)
  373. resChNodeGPUCost := requiredCtx.Query(queryNodeGPUCost)
  374. resChNodeLabels := requiredCtx.Query(queryNodeLabels)
  375. resChActiveMins := requiredCtx.Query(queryActiveMins)
  376. // Do not return errors if these fail, but log warnings
  377. resChNodeCPUModeTotal := optionalCtx.Query(queryNodeCPUModeTotal)
  378. resChNodeRAMSystemPct := optionalCtx.Query(queryNodeRAMSystemPct)
  379. resChNodeRAMUserPct := optionalCtx.Query(queryNodeRAMUserPct)
  380. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  381. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  382. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  383. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  384. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  385. resNodeLabels, _ := resChNodeLabels.Await()
  386. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  387. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  388. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  389. resActiveMins, _ := resChActiveMins.Await()
  390. if optionalCtx.HasErrors() {
  391. for _, err := range optionalCtx.Errors() {
  392. log.Warningf("ClusterNodes: %s", err)
  393. }
  394. }
  395. if requiredCtx.HasErrors() {
  396. for _, err := range requiredCtx.Errors() {
  397. log.Errorf("ClusterNodes: %s", err)
  398. }
  399. return nil, requiredCtx.ErrorCollection()
  400. }
  401. nodeMap := map[string]*Node{}
  402. for _, result := range resNodeCPUCost {
  403. cluster, err := result.GetString("cluster_id")
  404. if err != nil {
  405. cluster = env.GetClusterID()
  406. }
  407. name, err := result.GetString("node")
  408. if err != nil {
  409. log.Warningf("ClusterNodes: CPU cost data missing node")
  410. continue
  411. }
  412. nodeType, _ := result.GetString("instance_type")
  413. providerID, _ := result.GetString("provider_id")
  414. cpuCost := result.Values[0].Value
  415. key := fmt.Sprintf("%s/%s", cluster, name)
  416. if _, ok := nodeMap[key]; !ok {
  417. nodeMap[key] = &Node{
  418. Cluster: cluster,
  419. Name: name,
  420. NodeType: nodeType,
  421. ProviderID: cp.ParseID(providerID),
  422. CPUBreakdown: &ClusterCostsBreakdown{},
  423. RAMBreakdown: &ClusterCostsBreakdown{},
  424. }
  425. }
  426. nodeMap[key].CPUCost += cpuCost
  427. nodeMap[key].NodeType = nodeType
  428. if nodeMap[key].ProviderID == "" {
  429. nodeMap[key].ProviderID = cp.ParseID(providerID)
  430. }
  431. }
  432. for _, result := range resNodeCPUCores {
  433. cluster, err := result.GetString("cluster_id")
  434. if err != nil {
  435. cluster = env.GetClusterID()
  436. }
  437. name, err := result.GetString("node")
  438. if err != nil {
  439. log.Warningf("ClusterNodes: CPU cores data missing node")
  440. continue
  441. }
  442. cpuCores := result.Values[0].Value
  443. key := fmt.Sprintf("%s/%s", cluster, name)
  444. if _, ok := nodeMap[key]; !ok {
  445. nodeMap[key] = &Node{
  446. Cluster: cluster,
  447. Name: name,
  448. CPUBreakdown: &ClusterCostsBreakdown{},
  449. RAMBreakdown: &ClusterCostsBreakdown{},
  450. }
  451. }
  452. node := nodeMap[key]
  453. if v, ok := partialCPUMap[node.NodeType]; ok {
  454. node.CPUCores = v
  455. if cpuCores > 0 {
  456. adjustmentFactor := v / cpuCores
  457. node.CPUCost = node.CPUCost * adjustmentFactor
  458. }
  459. } else {
  460. nodeMap[key].CPUCores = cpuCores
  461. }
  462. }
  463. for _, result := range resNodeRAMCost {
  464. cluster, err := result.GetString("cluster_id")
  465. if err != nil {
  466. cluster = env.GetClusterID()
  467. }
  468. name, err := result.GetString("node")
  469. if err != nil {
  470. log.Warningf("ClusterNodes: RAM cost data missing node")
  471. continue
  472. }
  473. nodeType, _ := result.GetString("instance_type")
  474. providerID, _ := result.GetString("provider_id")
  475. ramCost := result.Values[0].Value
  476. key := fmt.Sprintf("%s/%s", cluster, name)
  477. if _, ok := nodeMap[key]; !ok {
  478. nodeMap[key] = &Node{
  479. Cluster: cluster,
  480. Name: name,
  481. NodeType: nodeType,
  482. ProviderID: cp.ParseID(providerID),
  483. CPUBreakdown: &ClusterCostsBreakdown{},
  484. RAMBreakdown: &ClusterCostsBreakdown{},
  485. }
  486. }
  487. nodeMap[key].RAMCost += ramCost
  488. nodeMap[key].NodeType = nodeType
  489. if nodeMap[key].ProviderID == "" {
  490. nodeMap[key].ProviderID = cp.ParseID(providerID)
  491. }
  492. }
  493. for _, result := range resNodeRAMBytes {
  494. cluster, err := result.GetString("cluster_id")
  495. if err != nil {
  496. cluster = env.GetClusterID()
  497. }
  498. name, err := result.GetString("node")
  499. if err != nil {
  500. log.Warningf("ClusterNodes: RAM bytes data missing node")
  501. continue
  502. }
  503. ramBytes := result.Values[0].Value
  504. key := fmt.Sprintf("%s/%s", cluster, name)
  505. if _, ok := nodeMap[key]; !ok {
  506. nodeMap[key] = &Node{
  507. Cluster: cluster,
  508. Name: name,
  509. CPUBreakdown: &ClusterCostsBreakdown{},
  510. RAMBreakdown: &ClusterCostsBreakdown{},
  511. }
  512. }
  513. nodeMap[key].RAMBytes = ramBytes
  514. }
  515. for _, result := range resNodeGPUCost {
  516. cluster, err := result.GetString("cluster_id")
  517. if err != nil {
  518. cluster = env.GetClusterID()
  519. }
  520. name, err := result.GetString("node")
  521. if err != nil {
  522. log.Warningf("ClusterNodes: GPU cost data missing node")
  523. continue
  524. }
  525. nodeType, _ := result.GetString("instance_type")
  526. providerID, _ := result.GetString("provider_id")
  527. gpuCost := result.Values[0].Value
  528. key := fmt.Sprintf("%s/%s", cluster, name)
  529. if _, ok := nodeMap[key]; !ok {
  530. nodeMap[key] = &Node{
  531. Cluster: cluster,
  532. Name: name,
  533. NodeType: nodeType,
  534. ProviderID: cp.ParseID(providerID),
  535. CPUBreakdown: &ClusterCostsBreakdown{},
  536. RAMBreakdown: &ClusterCostsBreakdown{},
  537. }
  538. }
  539. nodeMap[key].GPUCost += gpuCost
  540. if nodeMap[key].ProviderID == "" {
  541. nodeMap[key].ProviderID = cp.ParseID(providerID)
  542. }
  543. }
  544. // Mapping of cluster/node=cpu for computing resource efficiency
  545. clusterNodeCPUTotal := map[string]float64{}
  546. // Mapping of cluster/node:mode=cpu for computing resource efficiency
  547. clusterNodeModeCPUTotal := map[string]map[string]float64{}
  548. // Build intermediate structures for CPU usage by (cluster, node) and by
  549. // (cluster, node, mode) for computing resouce efficiency
  550. for _, result := range resNodeCPUModeTotal {
  551. cluster, err := result.GetString("cluster_id")
  552. if err != nil {
  553. cluster = env.GetClusterID()
  554. }
  555. node, err := result.GetString("kubernetes_node")
  556. if err != nil {
  557. log.DedupedWarningf(5, "ClusterNodes: CPU mode data missing node")
  558. continue
  559. }
  560. mode, err := result.GetString("mode")
  561. if err != nil {
  562. log.Warningf("ClusterNodes: unable to read CPU mode: %s", err)
  563. mode = "other"
  564. }
  565. key := fmt.Sprintf("%s/%s", cluster, node)
  566. total := result.Values[0].Value
  567. // Increment total
  568. clusterNodeCPUTotal[key] += total
  569. // Increment mode
  570. if _, ok := clusterNodeModeCPUTotal[key]; !ok {
  571. clusterNodeModeCPUTotal[key] = map[string]float64{}
  572. }
  573. clusterNodeModeCPUTotal[key][mode] += total
  574. }
  575. // Compute resource efficiency from intermediate structures
  576. for key, total := range clusterNodeCPUTotal {
  577. if modeTotals, ok := clusterNodeModeCPUTotal[key]; ok {
  578. for mode, subtotal := range modeTotals {
  579. // Compute percentage for the current cluster, node, mode
  580. pct := 0.0
  581. if total > 0 {
  582. pct = subtotal / total
  583. }
  584. if _, ok := nodeMap[key]; !ok {
  585. log.Warningf("ClusterNodes: CPU mode data for unidentified node")
  586. continue
  587. }
  588. switch mode {
  589. case "idle":
  590. nodeMap[key].CPUBreakdown.Idle += pct
  591. case "system":
  592. nodeMap[key].CPUBreakdown.System += pct
  593. case "user":
  594. nodeMap[key].CPUBreakdown.User += pct
  595. default:
  596. nodeMap[key].CPUBreakdown.Other += pct
  597. }
  598. }
  599. }
  600. }
  601. for _, result := range resNodeRAMSystemPct {
  602. cluster, err := result.GetString("cluster_id")
  603. if err != nil {
  604. cluster = env.GetClusterID()
  605. }
  606. name, err := result.GetString("instance")
  607. if err != nil {
  608. log.Warningf("ClusterNodes: RAM system percent missing node")
  609. continue
  610. }
  611. pct := result.Values[0].Value
  612. key := fmt.Sprintf("%s/%s", cluster, name)
  613. if _, ok := nodeMap[key]; !ok {
  614. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  615. continue
  616. }
  617. nodeMap[key].RAMBreakdown.System += pct
  618. }
  619. for _, result := range resNodeRAMUserPct {
  620. cluster, err := result.GetString("cluster_id")
  621. if err != nil {
  622. cluster = env.GetClusterID()
  623. }
  624. name, err := result.GetString("instance")
  625. if err != nil {
  626. log.Warningf("ClusterNodes: RAM system percent missing node")
  627. continue
  628. }
  629. pct := result.Values[0].Value
  630. key := fmt.Sprintf("%s/%s", cluster, name)
  631. if _, ok := nodeMap[key]; !ok {
  632. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  633. continue
  634. }
  635. nodeMap[key].RAMBreakdown.User += pct
  636. }
  637. for _, result := range resActiveMins {
  638. cluster, err := result.GetString("cluster_id")
  639. if err != nil {
  640. cluster = env.GetClusterID()
  641. }
  642. name, err := result.GetString("node")
  643. if err != nil {
  644. log.Warningf("ClusterNodes: active mins missing node")
  645. continue
  646. }
  647. key := fmt.Sprintf("%s/%s", cluster, name)
  648. if _, ok := nodeMap[key]; !ok {
  649. log.Warningf("ClusterNodes: active mins for unidentified node")
  650. continue
  651. }
  652. if len(result.Values) == 0 {
  653. continue
  654. }
  655. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  656. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  657. mins := e.Sub(s).Minutes()
  658. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  659. nodeMap[key].End = e
  660. nodeMap[key].Start = s
  661. nodeMap[key].Minutes = mins
  662. }
  663. // Determine preemptibility with node labels
  664. for _, result := range resNodeLabels {
  665. nodeName, err := result.GetString("node")
  666. if err != nil {
  667. continue
  668. }
  669. // GCP preemptible label
  670. pre := result.Values[0].Value
  671. cluster, err := result.GetString("cluster_id")
  672. if err != nil {
  673. cluster = env.GetClusterID()
  674. }
  675. key := fmt.Sprintf("%s/%s", cluster, nodeName)
  676. if node, ok := nodeMap[key]; pre > 0.0 && ok {
  677. node.Preemptible = true
  678. }
  679. // TODO AWS preemptible
  680. // TODO Azure preemptible
  681. }
  682. c, err := cp.GetConfig()
  683. if err != nil {
  684. return nil, err
  685. }
  686. discount, err := ParsePercentString(c.Discount)
  687. if err != nil {
  688. return nil, err
  689. }
  690. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  691. if err != nil {
  692. return nil, err
  693. }
  694. for _, node := range nodeMap {
  695. // TODO take RI into account
  696. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  697. // Apply all remaining resources to Idle
  698. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  699. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  700. }
  701. return nodeMap, nil
  702. }
  703. type LoadBalancer struct {
  704. Cluster string
  705. Name string
  706. ProviderID string
  707. Cost float64
  708. Start time.Time
  709. Minutes float64
  710. }
  711. func ClusterLoadBalancers(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*LoadBalancer, error) {
  712. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  713. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  714. if offset < time.Minute {
  715. offsetStr = ""
  716. }
  717. // minsPerResolution determines accuracy and resource use for the following
  718. // queries. Smaller values (higher resolution) result in better accuracy,
  719. // but more expensive queries, and vice-a-versa.
  720. minsPerResolution := 5
  721. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  722. // value, converts it to a cumulative value; i.e.
  723. // [$/hr] * [min/res]*[hr/min] = [$/res]
  724. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  725. ctx := prom.NewContext(client)
  726. queryLBCost := fmt.Sprintf(`sum_over_time((avg(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id))[%s:%dm]%s) * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  727. queryActiveMins := fmt.Sprintf(`count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  728. resChLBCost := ctx.Query(queryLBCost)
  729. resChActiveMins := ctx.Query(queryActiveMins)
  730. resLBCost, _ := resChLBCost.Await()
  731. resActiveMins, _ := resChActiveMins.Await()
  732. if ctx.HasErrors() {
  733. return nil, ctx.ErrorCollection()
  734. }
  735. loadBalancerMap := map[string]*LoadBalancer{}
  736. for _, result := range resLBCost {
  737. cluster, err := result.GetString("cluster_id")
  738. if err != nil {
  739. cluster = env.GetClusterID()
  740. }
  741. namespace, err := result.GetString("namespace")
  742. if err != nil {
  743. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  744. continue
  745. }
  746. serviceName, err := result.GetString("service_name")
  747. if err != nil {
  748. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  749. continue
  750. }
  751. providerID := ""
  752. lbCost := result.Values[0].Value
  753. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  754. if _, ok := loadBalancerMap[key]; !ok {
  755. loadBalancerMap[key] = &LoadBalancer{
  756. Cluster: cluster,
  757. Name: namespace + "/" + serviceName,
  758. ProviderID: providerID, // cp.ParseID(providerID) if providerID does get recorded later
  759. }
  760. }
  761. loadBalancerMap[key].Cost += lbCost
  762. }
  763. for _, result := range resActiveMins {
  764. cluster, err := result.GetString("cluster_id")
  765. if err != nil {
  766. cluster = env.GetClusterID()
  767. }
  768. namespace, err := result.GetString("namespace")
  769. if err != nil {
  770. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  771. continue
  772. }
  773. serviceName, err := result.GetString("service_name")
  774. if err != nil {
  775. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  776. continue
  777. }
  778. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  779. if len(result.Values) == 0 {
  780. continue
  781. }
  782. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  783. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  784. mins := e.Sub(s).Minutes()
  785. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  786. loadBalancerMap[key].Start = s
  787. loadBalancerMap[key].Minutes = mins
  788. }
  789. return loadBalancerMap, nil
  790. }
  791. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  792. func (a *Accesses) ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  793. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  794. start, end, err := util.ParseTimeRange(window, offset)
  795. if err != nil {
  796. return nil, err
  797. }
  798. mins := end.Sub(*start).Minutes()
  799. // minsPerResolution determines accuracy and resource use for the following
  800. // queries. Smaller values (higher resolution) result in better accuracy,
  801. // but more expensive queries, and vice-a-versa.
  802. minsPerResolution := 5
  803. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  804. // value, converts it to a cumulative value; i.e.
  805. // [$/hr] * [min/res]*[hr/min] = [$/res]
  806. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  807. const fmtQueryDataCount = `
  808. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  809. `
  810. const fmtQueryTotalGPU = `
  811. sum(
  812. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  813. ) by (cluster_id)
  814. `
  815. const fmtQueryTotalCPU = `
  816. sum(
  817. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  818. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  819. ) by (cluster_id)
  820. `
  821. const fmtQueryTotalRAM = `
  822. sum(
  823. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  824. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  825. ) by (cluster_id)
  826. `
  827. const fmtQueryTotalStorage = `
  828. sum(
  829. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  830. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  831. ) by (cluster_id)
  832. `
  833. const fmtQueryCPUModePct = `
  834. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  835. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  836. `
  837. const fmtQueryRAMSystemPct = `
  838. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  839. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  840. `
  841. const fmtQueryRAMUserPct = `
  842. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  843. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  844. `
  845. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  846. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  847. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  848. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  849. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  850. if queryTotalLocalStorage != "" {
  851. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  852. }
  853. fmtOffset := ""
  854. if offset != "" {
  855. fmtOffset = fmt.Sprintf("offset %s", offset)
  856. }
  857. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  858. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  859. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  860. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  861. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  862. ctx := prom.NewContext(client)
  863. resChs := ctx.QueryAll(
  864. queryDataCount,
  865. queryTotalGPU,
  866. queryTotalCPU,
  867. queryTotalRAM,
  868. queryTotalStorage,
  869. )
  870. // Only submit the local storage query if it is valid. Otherwise Prometheus
  871. // will return errors. Always append something to resChs, regardless, to
  872. // maintain indexing.
  873. if queryTotalLocalStorage != "" {
  874. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  875. } else {
  876. resChs = append(resChs, nil)
  877. }
  878. if withBreakdown {
  879. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  880. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  881. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  882. bdResChs := ctx.QueryAll(
  883. queryCPUModePct,
  884. queryRAMSystemPct,
  885. queryRAMUserPct,
  886. )
  887. // Only submit the local storage query if it is valid. Otherwise Prometheus
  888. // will return errors. Always append something to resChs, regardless, to
  889. // maintain indexing.
  890. if queryUsedLocalStorage != "" {
  891. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  892. } else {
  893. bdResChs = append(bdResChs, nil)
  894. }
  895. resChs = append(resChs, bdResChs...)
  896. }
  897. resDataCount, _ := resChs[0].Await()
  898. resTotalGPU, _ := resChs[1].Await()
  899. resTotalCPU, _ := resChs[2].Await()
  900. resTotalRAM, _ := resChs[3].Await()
  901. resTotalStorage, _ := resChs[4].Await()
  902. if ctx.HasErrors() {
  903. return nil, ctx.ErrorCollection()
  904. }
  905. defaultClusterID := env.GetClusterID()
  906. dataMinsByCluster := map[string]float64{}
  907. for _, result := range resDataCount {
  908. clusterID, _ := result.GetString("cluster_id")
  909. if clusterID == "" {
  910. clusterID = defaultClusterID
  911. }
  912. dataMins := mins
  913. if len(result.Values) > 0 {
  914. dataMins = result.Values[0].Value
  915. } else {
  916. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  917. }
  918. dataMinsByCluster[clusterID] = dataMins
  919. }
  920. // Determine combined discount
  921. discount, customDiscount := 0.0, 0.0
  922. c, err := a.CloudProvider.GetConfig()
  923. if err == nil {
  924. discount, err = ParsePercentString(c.Discount)
  925. if err != nil {
  926. discount = 0.0
  927. }
  928. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  929. if err != nil {
  930. customDiscount = 0.0
  931. }
  932. }
  933. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  934. costData := make(map[string]map[string]float64)
  935. // Helper function to iterate over Prom query results, parsing the raw values into
  936. // the intermediate costData structure.
  937. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  938. for _, result := range results {
  939. clusterID, _ := result.GetString("cluster_id")
  940. if clusterID == "" {
  941. clusterID = defaultClusterID
  942. }
  943. if _, ok := costData[clusterID]; !ok {
  944. costData[clusterID] = map[string]float64{}
  945. }
  946. if len(result.Values) > 0 {
  947. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  948. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  949. }
  950. }
  951. }
  952. // Apply both sustained use and custom discounts to RAM and CPU
  953. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  954. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  955. // Apply only custom discount to GPU and storage
  956. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  957. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  958. if queryTotalLocalStorage != "" {
  959. resTotalLocalStorage, err := resChs[5].Await()
  960. if err != nil {
  961. return nil, err
  962. }
  963. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  964. }
  965. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  966. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  967. pvUsedCostMap := map[string]float64{}
  968. if withBreakdown {
  969. resCPUModePct, _ := resChs[6].Await()
  970. resRAMSystemPct, _ := resChs[7].Await()
  971. resRAMUserPct, _ := resChs[8].Await()
  972. if ctx.HasErrors() {
  973. return nil, ctx.ErrorCollection()
  974. }
  975. for _, result := range resCPUModePct {
  976. clusterID, _ := result.GetString("cluster_id")
  977. if clusterID == "" {
  978. clusterID = defaultClusterID
  979. }
  980. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  981. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  982. }
  983. cpuBD := cpuBreakdownMap[clusterID]
  984. mode, err := result.GetString("mode")
  985. if err != nil {
  986. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  987. mode = "other"
  988. }
  989. switch mode {
  990. case "idle":
  991. cpuBD.Idle += result.Values[0].Value
  992. case "system":
  993. cpuBD.System += result.Values[0].Value
  994. case "user":
  995. cpuBD.User += result.Values[0].Value
  996. default:
  997. cpuBD.Other += result.Values[0].Value
  998. }
  999. }
  1000. for _, result := range resRAMSystemPct {
  1001. clusterID, _ := result.GetString("cluster_id")
  1002. if clusterID == "" {
  1003. clusterID = defaultClusterID
  1004. }
  1005. if _, ok := ramBreakdownMap[clusterID]; !ok {
  1006. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  1007. }
  1008. ramBD := ramBreakdownMap[clusterID]
  1009. ramBD.System += result.Values[0].Value
  1010. }
  1011. for _, result := range resRAMUserPct {
  1012. clusterID, _ := result.GetString("cluster_id")
  1013. if clusterID == "" {
  1014. clusterID = defaultClusterID
  1015. }
  1016. if _, ok := ramBreakdownMap[clusterID]; !ok {
  1017. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  1018. }
  1019. ramBD := ramBreakdownMap[clusterID]
  1020. ramBD.User += result.Values[0].Value
  1021. }
  1022. for _, ramBD := range ramBreakdownMap {
  1023. remaining := 1.0
  1024. remaining -= ramBD.Other
  1025. remaining -= ramBD.System
  1026. remaining -= ramBD.User
  1027. ramBD.Idle = remaining
  1028. }
  1029. if queryUsedLocalStorage != "" {
  1030. resUsedLocalStorage, err := resChs[9].Await()
  1031. if err != nil {
  1032. return nil, err
  1033. }
  1034. for _, result := range resUsedLocalStorage {
  1035. clusterID, _ := result.GetString("cluster_id")
  1036. if clusterID == "" {
  1037. clusterID = defaultClusterID
  1038. }
  1039. pvUsedCostMap[clusterID] += result.Values[0].Value
  1040. }
  1041. }
  1042. }
  1043. if ctx.HasErrors() {
  1044. for _, err := range ctx.Errors() {
  1045. log.Errorf("ComputeClusterCosts: %s", err)
  1046. }
  1047. return nil, ctx.ErrorCollection()
  1048. }
  1049. // Convert intermediate structure to Costs instances
  1050. costsByCluster := map[string]*ClusterCosts{}
  1051. for id, cd := range costData {
  1052. dataMins, ok := dataMinsByCluster[id]
  1053. if !ok {
  1054. dataMins = mins
  1055. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  1056. }
  1057. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  1058. if err != nil {
  1059. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  1060. return nil, err
  1061. }
  1062. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  1063. costs.CPUBreakdown = cpuBD
  1064. }
  1065. if ramBD, ok := ramBreakdownMap[id]; ok {
  1066. costs.RAMBreakdown = ramBD
  1067. }
  1068. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  1069. if pvUC, ok := pvUsedCostMap[id]; ok {
  1070. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  1071. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  1072. }
  1073. costs.DataMinutes = dataMins
  1074. costsByCluster[id] = costs
  1075. }
  1076. return costsByCluster, nil
  1077. }
  1078. type Totals struct {
  1079. TotalCost [][]string `json:"totalcost"`
  1080. CPUCost [][]string `json:"cpucost"`
  1081. MemCost [][]string `json:"memcost"`
  1082. StorageCost [][]string `json:"storageCost"`
  1083. }
  1084. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  1085. if len(qrs) == 0 {
  1086. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  1087. }
  1088. result := qrs[0]
  1089. totals := [][]string{}
  1090. for _, value := range result.Values {
  1091. d0 := fmt.Sprintf("%f", value.Timestamp)
  1092. d1 := fmt.Sprintf("%f", value.Value)
  1093. toAppend := []string{
  1094. d0,
  1095. d1,
  1096. }
  1097. totals = append(totals, toAppend)
  1098. }
  1099. return totals, nil
  1100. }
  1101. // ClusterCostsOverTime gives the full cluster costs over time
  1102. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  1103. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  1104. if localStorageQuery != "" {
  1105. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  1106. }
  1107. layout := "2006-01-02T15:04:05.000Z"
  1108. start, err := time.Parse(layout, startString)
  1109. if err != nil {
  1110. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1111. return nil, err
  1112. }
  1113. end, err := time.Parse(layout, endString)
  1114. if err != nil {
  1115. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1116. return nil, err
  1117. }
  1118. window, err := time.ParseDuration(windowString)
  1119. if err != nil {
  1120. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1121. return nil, err
  1122. }
  1123. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  1124. if offset != "" {
  1125. offset = fmt.Sprintf("offset %s", offset)
  1126. }
  1127. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  1128. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  1129. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  1130. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  1131. ctx := prom.NewContext(cli)
  1132. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  1133. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  1134. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  1135. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  1136. resultClusterCores, err := resChClusterCores.Await()
  1137. if err != nil {
  1138. return nil, err
  1139. }
  1140. resultClusterRAM, err := resChClusterRAM.Await()
  1141. if err != nil {
  1142. return nil, err
  1143. }
  1144. resultStorage, err := resChStorage.Await()
  1145. if err != nil {
  1146. return nil, err
  1147. }
  1148. resultTotal, err := resChTotal.Await()
  1149. if err != nil {
  1150. return nil, err
  1151. }
  1152. coreTotal, err := resultToTotals(resultClusterCores)
  1153. if err != nil {
  1154. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  1155. return nil, err
  1156. }
  1157. ramTotal, err := resultToTotals(resultClusterRAM)
  1158. if err != nil {
  1159. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  1160. return nil, err
  1161. }
  1162. storageTotal, err := resultToTotals(resultStorage)
  1163. if err != nil {
  1164. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  1165. }
  1166. clusterTotal, err := resultToTotals(resultTotal)
  1167. if err != nil {
  1168. // If clusterTotal query failed, it's likely because there are no PVs, which
  1169. // causes the qTotal query to return no data. Instead, query only node costs.
  1170. // If that fails, return an error because something is actually wrong.
  1171. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  1172. resultNodes, warnings, err := ctx.QueryRangeSync(qNodes, start, end, window)
  1173. for _, warning := range warnings {
  1174. log.Warningf(warning)
  1175. }
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. clusterTotal, err = resultToTotals(resultNodes)
  1180. if err != nil {
  1181. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  1182. return nil, err
  1183. }
  1184. }
  1185. return &Totals{
  1186. TotalCost: clusterTotal,
  1187. CPUCost: coreTotal,
  1188. MemCost: ramTotal,
  1189. StorageCost: storageTotal,
  1190. }, nil
  1191. }