cluster.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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.ErrorCollector.IsError() {
  143. return nil, ctx.Errors()
  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. ctx := prom.NewContext(client)
  357. 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)
  358. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  359. 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)
  360. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  361. 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)
  362. queryNodeLabels := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  363. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total[%s:%dm]%s)) by (kubernetes_node, cluster_id, mode)`, durationStr, minsPerResolution, offsetStr)
  364. 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) / sum(sum_over_time(label_replace(kube_node_status_capacity_memory_bytes, "instance", "$1", "node", "(.*)")[%s:%dm]%s)) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  365. 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) / sum(sum_over_time(label_replace(kube_node_status_capacity_memory_bytes, "instance", "$1", "node", "(.*)")[%s:%dm]%s)) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  366. queryActiveMins := fmt.Sprintf(`node_total_hourly_cost[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  367. resChNodeCPUCost := ctx.Query(queryNodeCPUCost)
  368. resChNodeCPUCores := ctx.Query(queryNodeCPUCores)
  369. resChNodeRAMCost := ctx.Query(queryNodeRAMCost)
  370. resChNodeRAMBytes := ctx.Query(queryNodeRAMBytes)
  371. resChNodeGPUCost := ctx.Query(queryNodeGPUCost)
  372. resChNodeLabels := ctx.Query(queryNodeLabels)
  373. resChNodeCPUModeTotal := ctx.Query(queryNodeCPUModeTotal)
  374. resChNodeRAMSystemPct := ctx.Query(queryNodeRAMSystemPct)
  375. resChNodeRAMUserPct := ctx.Query(queryNodeRAMUserPct)
  376. resChActiveMins := ctx.Query(queryActiveMins)
  377. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  378. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  379. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  380. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  381. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  382. resNodeLabels, _ := resChNodeLabels.Await()
  383. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  384. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  385. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  386. resActiveMins, _ := resChActiveMins.Await()
  387. if ctx.ErrorCollector.IsError() {
  388. return nil, ctx.Errors()
  389. }
  390. nodeMap := map[string]*Node{}
  391. for _, result := range resNodeCPUCost {
  392. cluster, err := result.GetString("cluster_id")
  393. if err != nil {
  394. cluster = env.GetClusterID()
  395. }
  396. name, err := result.GetString("node")
  397. if err != nil {
  398. log.Warningf("ClusterNodes: CPU cost data missing node")
  399. continue
  400. }
  401. nodeType, _ := result.GetString("instance_type")
  402. providerID, _ := result.GetString("provider_id")
  403. cpuCost := result.Values[0].Value
  404. key := fmt.Sprintf("%s/%s", cluster, name)
  405. if _, ok := nodeMap[key]; !ok {
  406. nodeMap[key] = &Node{
  407. Cluster: cluster,
  408. Name: name,
  409. NodeType: nodeType,
  410. ProviderID: cp.ParseID(providerID),
  411. CPUBreakdown: &ClusterCostsBreakdown{},
  412. RAMBreakdown: &ClusterCostsBreakdown{},
  413. }
  414. }
  415. nodeMap[key].CPUCost += cpuCost
  416. nodeMap[key].NodeType = nodeType
  417. if nodeMap[key].ProviderID == "" {
  418. nodeMap[key].ProviderID = cp.ParseID(providerID)
  419. }
  420. }
  421. for _, result := range resNodeCPUCores {
  422. cluster, err := result.GetString("cluster_id")
  423. if err != nil {
  424. cluster = env.GetClusterID()
  425. }
  426. name, err := result.GetString("node")
  427. if err != nil {
  428. log.Warningf("ClusterNodes: CPU cores data missing node")
  429. continue
  430. }
  431. cpuCores := result.Values[0].Value
  432. key := fmt.Sprintf("%s/%s", cluster, name)
  433. if _, ok := nodeMap[key]; !ok {
  434. nodeMap[key] = &Node{
  435. Cluster: cluster,
  436. Name: name,
  437. CPUBreakdown: &ClusterCostsBreakdown{},
  438. RAMBreakdown: &ClusterCostsBreakdown{},
  439. }
  440. }
  441. node := nodeMap[key]
  442. if v, ok := partialCPUMap[node.NodeType]; ok {
  443. node.CPUCores = v
  444. if cpuCores > 0 {
  445. adjustmentFactor := v / cpuCores
  446. node.CPUCost = node.CPUCost * adjustmentFactor
  447. }
  448. } else {
  449. nodeMap[key].CPUCores = cpuCores
  450. }
  451. }
  452. for _, result := range resNodeRAMCost {
  453. cluster, err := result.GetString("cluster_id")
  454. if err != nil {
  455. cluster = env.GetClusterID()
  456. }
  457. name, err := result.GetString("node")
  458. if err != nil {
  459. log.Warningf("ClusterNodes: RAM cost data missing node")
  460. continue
  461. }
  462. nodeType, _ := result.GetString("instance_type")
  463. providerID, _ := result.GetString("provider_id")
  464. ramCost := result.Values[0].Value
  465. key := fmt.Sprintf("%s/%s", cluster, name)
  466. if _, ok := nodeMap[key]; !ok {
  467. nodeMap[key] = &Node{
  468. Cluster: cluster,
  469. Name: name,
  470. NodeType: nodeType,
  471. ProviderID: cp.ParseID(providerID),
  472. CPUBreakdown: &ClusterCostsBreakdown{},
  473. RAMBreakdown: &ClusterCostsBreakdown{},
  474. }
  475. }
  476. nodeMap[key].RAMCost += ramCost
  477. nodeMap[key].NodeType = nodeType
  478. if nodeMap[key].ProviderID == "" {
  479. nodeMap[key].ProviderID = cp.ParseID(providerID)
  480. }
  481. }
  482. for _, result := range resNodeRAMBytes {
  483. cluster, err := result.GetString("cluster_id")
  484. if err != nil {
  485. cluster = env.GetClusterID()
  486. }
  487. name, err := result.GetString("node")
  488. if err != nil {
  489. log.Warningf("ClusterNodes: RAM bytes data missing node")
  490. continue
  491. }
  492. ramBytes := result.Values[0].Value
  493. key := fmt.Sprintf("%s/%s", cluster, name)
  494. if _, ok := nodeMap[key]; !ok {
  495. nodeMap[key] = &Node{
  496. Cluster: cluster,
  497. Name: name,
  498. CPUBreakdown: &ClusterCostsBreakdown{},
  499. RAMBreakdown: &ClusterCostsBreakdown{},
  500. }
  501. }
  502. nodeMap[key].RAMBytes = ramBytes
  503. }
  504. for _, result := range resNodeGPUCost {
  505. cluster, err := result.GetString("cluster_id")
  506. if err != nil {
  507. cluster = env.GetClusterID()
  508. }
  509. name, err := result.GetString("node")
  510. if err != nil {
  511. log.Warningf("ClusterNodes: GPU cost data missing node")
  512. continue
  513. }
  514. nodeType, _ := result.GetString("instance_type")
  515. providerID, _ := result.GetString("provider_id")
  516. gpuCost := result.Values[0].Value
  517. key := fmt.Sprintf("%s/%s", cluster, name)
  518. if _, ok := nodeMap[key]; !ok {
  519. nodeMap[key] = &Node{
  520. Cluster: cluster,
  521. Name: name,
  522. NodeType: nodeType,
  523. ProviderID: cp.ParseID(providerID),
  524. CPUBreakdown: &ClusterCostsBreakdown{},
  525. RAMBreakdown: &ClusterCostsBreakdown{},
  526. }
  527. }
  528. nodeMap[key].GPUCost += gpuCost
  529. if nodeMap[key].ProviderID == "" {
  530. nodeMap[key].ProviderID = cp.ParseID(providerID)
  531. }
  532. }
  533. // Mapping of cluster/node=cpu for computing resource efficiency
  534. clusterNodeCPUTotal := map[string]float64{}
  535. // Mapping of cluster/node:mode=cpu for computing resource efficiency
  536. clusterNodeModeCPUTotal := map[string]map[string]float64{}
  537. // Build intermediate structures for CPU usage by (cluster, node) and by
  538. // (cluster, node, mode) for computing resouce efficiency
  539. for _, result := range resNodeCPUModeTotal {
  540. cluster, err := result.GetString("cluster_id")
  541. if err != nil {
  542. cluster = env.GetClusterID()
  543. }
  544. node, err := result.GetString("kubernetes_node")
  545. if err != nil {
  546. log.DedupedWarningf(5, "ClusterNodes: CPU mode data missing node")
  547. continue
  548. }
  549. mode, err := result.GetString("mode")
  550. if err != nil {
  551. log.Warningf("ClusterNodes: unable to read CPU mode: %s", err)
  552. mode = "other"
  553. }
  554. key := fmt.Sprintf("%s/%s", cluster, node)
  555. total := result.Values[0].Value
  556. // Increment total
  557. clusterNodeCPUTotal[key] += total
  558. // Increment mode
  559. if _, ok := clusterNodeModeCPUTotal[key]; !ok {
  560. clusterNodeModeCPUTotal[key] = map[string]float64{}
  561. }
  562. clusterNodeModeCPUTotal[key][mode] += total
  563. }
  564. // Compute resource efficiency from intermediate structures
  565. for key, total := range clusterNodeCPUTotal {
  566. if modeTotals, ok := clusterNodeModeCPUTotal[key]; ok {
  567. for mode, subtotal := range modeTotals {
  568. // Compute percentage for the current cluster, node, mode
  569. pct := subtotal / total
  570. if _, ok := nodeMap[key]; !ok {
  571. log.Warningf("ClusterNodes: CPU mode data for unidentified node")
  572. continue
  573. }
  574. switch mode {
  575. case "idle":
  576. nodeMap[key].CPUBreakdown.Idle += pct
  577. case "system":
  578. nodeMap[key].CPUBreakdown.System += pct
  579. case "user":
  580. nodeMap[key].CPUBreakdown.User += pct
  581. default:
  582. nodeMap[key].CPUBreakdown.Other += pct
  583. }
  584. }
  585. }
  586. }
  587. for _, result := range resNodeRAMSystemPct {
  588. cluster, err := result.GetString("cluster_id")
  589. if err != nil {
  590. cluster = env.GetClusterID()
  591. }
  592. name, err := result.GetString("instance")
  593. if err != nil {
  594. log.Warningf("ClusterNodes: RAM system percent missing node")
  595. continue
  596. }
  597. pct := result.Values[0].Value
  598. key := fmt.Sprintf("%s/%s", cluster, name)
  599. if _, ok := nodeMap[key]; !ok {
  600. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  601. continue
  602. }
  603. nodeMap[key].RAMBreakdown.System += pct
  604. }
  605. for _, result := range resNodeRAMUserPct {
  606. cluster, err := result.GetString("cluster_id")
  607. if err != nil {
  608. cluster = env.GetClusterID()
  609. }
  610. name, err := result.GetString("instance")
  611. if err != nil {
  612. log.Warningf("ClusterNodes: RAM system percent missing node")
  613. continue
  614. }
  615. pct := result.Values[0].Value
  616. key := fmt.Sprintf("%s/%s", cluster, name)
  617. if _, ok := nodeMap[key]; !ok {
  618. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  619. continue
  620. }
  621. nodeMap[key].RAMBreakdown.User += pct
  622. }
  623. for _, result := range resActiveMins {
  624. cluster, err := result.GetString("cluster_id")
  625. if err != nil {
  626. cluster = env.GetClusterID()
  627. }
  628. name, err := result.GetString("node")
  629. if err != nil {
  630. log.Warningf("ClusterNodes: active mins missing node")
  631. continue
  632. }
  633. key := fmt.Sprintf("%s/%s", cluster, name)
  634. if _, ok := nodeMap[key]; !ok {
  635. log.Warningf("ClusterNodes: active mins for unidentified node")
  636. continue
  637. }
  638. if len(result.Values) == 0 {
  639. continue
  640. }
  641. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  642. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  643. mins := e.Sub(s).Minutes()
  644. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  645. nodeMap[key].End = e
  646. nodeMap[key].Start = s
  647. nodeMap[key].Minutes = mins
  648. }
  649. // Determine preemptibility with node labels
  650. for _, result := range resNodeLabels {
  651. nodeName, err := result.GetString("node")
  652. if err != nil {
  653. continue
  654. }
  655. // GCP preemptible label
  656. pre := result.Values[0].Value
  657. cluster, err := result.GetString("cluster_id")
  658. if err != nil {
  659. cluster = env.GetClusterID()
  660. }
  661. key := fmt.Sprintf("%s/%s", cluster, nodeName)
  662. if node, ok := nodeMap[key]; pre > 0.0 && ok {
  663. node.Preemptible = true
  664. }
  665. // TODO AWS preemptible
  666. // TODO Azure preemptible
  667. }
  668. c, err := cp.GetConfig()
  669. if err != nil {
  670. return nil, []error{err}
  671. }
  672. discount, err := ParsePercentString(c.Discount)
  673. if err != nil {
  674. return nil, []error{err}
  675. }
  676. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  677. if err != nil {
  678. return nil, []error{err}
  679. }
  680. for _, node := range nodeMap {
  681. // TODO take RI into account
  682. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  683. // Apply all remaining resources to Idle
  684. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  685. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  686. }
  687. return nodeMap, nil
  688. }
  689. type LoadBalancer struct {
  690. Cluster string
  691. Name string
  692. ProviderID string
  693. Cost float64
  694. Start time.Time
  695. Minutes float64
  696. }
  697. func ClusterLoadBalancers(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*LoadBalancer, []error) {
  698. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  699. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  700. if offset < time.Minute {
  701. offsetStr = ""
  702. }
  703. // minsPerResolution determines accuracy and resource use for the following
  704. // queries. Smaller values (higher resolution) result in better accuracy,
  705. // but more expensive queries, and vice-a-versa.
  706. minsPerResolution := 5
  707. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  708. // value, converts it to a cumulative value; i.e.
  709. // [$/hr] * [min/res]*[hr/min] = [$/res]
  710. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  711. ctx := prom.NewContext(client)
  712. 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)
  713. queryActiveMins := fmt.Sprintf(`count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  714. resChLBCost := ctx.Query(queryLBCost)
  715. resChActiveMins := ctx.Query(queryActiveMins)
  716. resLBCost, _ := resChLBCost.Await()
  717. resActiveMins, _ := resChActiveMins.Await()
  718. if ctx.ErrorCollector.IsError() {
  719. return nil, ctx.Errors()
  720. }
  721. loadBalancerMap := map[string]*LoadBalancer{}
  722. for _, result := range resLBCost {
  723. cluster, err := result.GetString("cluster_id")
  724. if err != nil {
  725. cluster = env.GetClusterID()
  726. }
  727. namespace, err := result.GetString("namespace")
  728. if err != nil {
  729. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  730. continue
  731. }
  732. serviceName, err := result.GetString("service_name")
  733. if err != nil {
  734. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  735. continue
  736. }
  737. providerID := ""
  738. lbCost := result.Values[0].Value
  739. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  740. if _, ok := loadBalancerMap[key]; !ok {
  741. loadBalancerMap[key] = &LoadBalancer{
  742. Cluster: cluster,
  743. Name: namespace + "/" + serviceName,
  744. ProviderID: providerID, // cp.ParseID(providerID) if providerID does get recorded later
  745. }
  746. }
  747. loadBalancerMap[key].Cost += lbCost
  748. }
  749. for _, result := range resActiveMins {
  750. cluster, err := result.GetString("cluster_id")
  751. if err != nil {
  752. cluster = env.GetClusterID()
  753. }
  754. namespace, err := result.GetString("namespace")
  755. if err != nil {
  756. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  757. continue
  758. }
  759. serviceName, err := result.GetString("service_name")
  760. if err != nil {
  761. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  762. continue
  763. }
  764. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  765. if len(result.Values) == 0 {
  766. continue
  767. }
  768. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  769. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  770. mins := e.Sub(s).Minutes()
  771. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  772. loadBalancerMap[key].Start = s
  773. loadBalancerMap[key].Minutes = mins
  774. }
  775. return loadBalancerMap, nil
  776. }
  777. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  778. func ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  779. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  780. start, end, err := util.ParseTimeRange(window, offset)
  781. if err != nil {
  782. return nil, err
  783. }
  784. mins := end.Sub(*start).Minutes()
  785. // minsPerResolution determines accuracy and resource use for the following
  786. // queries. Smaller values (higher resolution) result in better accuracy,
  787. // but more expensive queries, and vice-a-versa.
  788. minsPerResolution := 5
  789. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  790. // value, converts it to a cumulative value; i.e.
  791. // [$/hr] * [min/res]*[hr/min] = [$/res]
  792. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  793. const fmtQueryDataCount = `
  794. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  795. `
  796. const fmtQueryTotalGPU = `
  797. sum(
  798. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  799. ) by (cluster_id)
  800. `
  801. const fmtQueryTotalCPU = `
  802. sum(
  803. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  804. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  805. ) by (cluster_id)
  806. `
  807. const fmtQueryTotalRAM = `
  808. sum(
  809. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  810. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  811. ) by (cluster_id)
  812. `
  813. const fmtQueryTotalStorage = `
  814. sum(
  815. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  816. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  817. ) by (cluster_id)
  818. `
  819. const fmtQueryCPUModePct = `
  820. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  821. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  822. `
  823. const fmtQueryRAMSystemPct = `
  824. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  825. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  826. `
  827. const fmtQueryRAMUserPct = `
  828. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  829. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  830. `
  831. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  832. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  833. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  834. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  835. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  836. if queryTotalLocalStorage != "" {
  837. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  838. }
  839. fmtOffset := ""
  840. if offset != "" {
  841. fmtOffset = fmt.Sprintf("offset %s", offset)
  842. }
  843. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  844. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  845. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  846. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  847. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  848. ctx := prom.NewContext(client)
  849. resChs := ctx.QueryAll(
  850. queryDataCount,
  851. queryTotalGPU,
  852. queryTotalCPU,
  853. queryTotalRAM,
  854. queryTotalStorage,
  855. )
  856. // Only submit the local storage query if it is valid. Otherwise Prometheus
  857. // will return errors. Always append something to resChs, regardless, to
  858. // maintain indexing.
  859. if queryTotalLocalStorage != "" {
  860. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  861. } else {
  862. resChs = append(resChs, nil)
  863. }
  864. if withBreakdown {
  865. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  866. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  867. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  868. bdResChs := ctx.QueryAll(
  869. queryCPUModePct,
  870. queryRAMSystemPct,
  871. queryRAMUserPct,
  872. )
  873. // Only submit the local storage query if it is valid. Otherwise Prometheus
  874. // will return errors. Always append something to resChs, regardless, to
  875. // maintain indexing.
  876. if queryUsedLocalStorage != "" {
  877. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  878. } else {
  879. bdResChs = append(bdResChs, nil)
  880. }
  881. resChs = append(resChs, bdResChs...)
  882. }
  883. resDataCount, _ := resChs[0].Await()
  884. resTotalGPU, _ := resChs[1].Await()
  885. resTotalCPU, _ := resChs[2].Await()
  886. resTotalRAM, _ := resChs[3].Await()
  887. resTotalStorage, _ := resChs[4].Await()
  888. if ctx.HasErrors() {
  889. return nil, ctx.Errors()[0]
  890. }
  891. defaultClusterID := env.GetClusterID()
  892. dataMinsByCluster := map[string]float64{}
  893. for _, result := range resDataCount {
  894. clusterID, _ := result.GetString("cluster_id")
  895. if clusterID == "" {
  896. clusterID = defaultClusterID
  897. }
  898. dataMins := mins
  899. if len(result.Values) > 0 {
  900. dataMins = result.Values[0].Value
  901. } else {
  902. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  903. }
  904. dataMinsByCluster[clusterID] = dataMins
  905. }
  906. // Determine combined discount
  907. discount, customDiscount := 0.0, 0.0
  908. c, err := A.Cloud.GetConfig()
  909. if err == nil {
  910. discount, err = ParsePercentString(c.Discount)
  911. if err != nil {
  912. discount = 0.0
  913. }
  914. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  915. if err != nil {
  916. customDiscount = 0.0
  917. }
  918. }
  919. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  920. costData := make(map[string]map[string]float64)
  921. // Helper function to iterate over Prom query results, parsing the raw values into
  922. // the intermediate costData structure.
  923. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  924. for _, result := range results {
  925. clusterID, _ := result.GetString("cluster_id")
  926. if clusterID == "" {
  927. clusterID = defaultClusterID
  928. }
  929. if _, ok := costData[clusterID]; !ok {
  930. costData[clusterID] = map[string]float64{}
  931. }
  932. if len(result.Values) > 0 {
  933. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  934. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  935. }
  936. }
  937. }
  938. // Apply both sustained use and custom discounts to RAM and CPU
  939. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  940. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  941. // Apply only custom discount to GPU and storage
  942. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  943. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  944. if queryTotalLocalStorage != "" {
  945. resTotalLocalStorage, err := resChs[5].Await()
  946. if err != nil {
  947. return nil, err
  948. }
  949. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  950. }
  951. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  952. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  953. pvUsedCostMap := map[string]float64{}
  954. if withBreakdown {
  955. resCPUModePct, _ := resChs[6].Await()
  956. resRAMSystemPct, _ := resChs[7].Await()
  957. resRAMUserPct, _ := resChs[8].Await()
  958. if ctx.HasErrors() {
  959. return nil, ctx.Errors()[0]
  960. }
  961. for _, result := range resCPUModePct {
  962. clusterID, _ := result.GetString("cluster_id")
  963. if clusterID == "" {
  964. clusterID = defaultClusterID
  965. }
  966. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  967. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  968. }
  969. cpuBD := cpuBreakdownMap[clusterID]
  970. mode, err := result.GetString("mode")
  971. if err != nil {
  972. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  973. mode = "other"
  974. }
  975. switch mode {
  976. case "idle":
  977. cpuBD.Idle += result.Values[0].Value
  978. case "system":
  979. cpuBD.System += result.Values[0].Value
  980. case "user":
  981. cpuBD.User += result.Values[0].Value
  982. default:
  983. cpuBD.Other += result.Values[0].Value
  984. }
  985. }
  986. for _, result := range resRAMSystemPct {
  987. clusterID, _ := result.GetString("cluster_id")
  988. if clusterID == "" {
  989. clusterID = defaultClusterID
  990. }
  991. if _, ok := ramBreakdownMap[clusterID]; !ok {
  992. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  993. }
  994. ramBD := ramBreakdownMap[clusterID]
  995. ramBD.System += result.Values[0].Value
  996. }
  997. for _, result := range resRAMUserPct {
  998. clusterID, _ := result.GetString("cluster_id")
  999. if clusterID == "" {
  1000. clusterID = defaultClusterID
  1001. }
  1002. if _, ok := ramBreakdownMap[clusterID]; !ok {
  1003. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  1004. }
  1005. ramBD := ramBreakdownMap[clusterID]
  1006. ramBD.User += result.Values[0].Value
  1007. }
  1008. for _, ramBD := range ramBreakdownMap {
  1009. remaining := 1.0
  1010. remaining -= ramBD.Other
  1011. remaining -= ramBD.System
  1012. remaining -= ramBD.User
  1013. ramBD.Idle = remaining
  1014. }
  1015. if queryUsedLocalStorage != "" {
  1016. resUsedLocalStorage, err := resChs[9].Await()
  1017. if err != nil {
  1018. return nil, err
  1019. }
  1020. for _, result := range resUsedLocalStorage {
  1021. clusterID, _ := result.GetString("cluster_id")
  1022. if clusterID == "" {
  1023. clusterID = defaultClusterID
  1024. }
  1025. pvUsedCostMap[clusterID] += result.Values[0].Value
  1026. }
  1027. }
  1028. }
  1029. if ctx.ErrorCollector.IsError() {
  1030. for _, err := range ctx.Errors() {
  1031. log.Errorf("ComputeClusterCosts: %s", err)
  1032. }
  1033. return nil, ctx.Errors()[0]
  1034. }
  1035. // Convert intermediate structure to Costs instances
  1036. costsByCluster := map[string]*ClusterCosts{}
  1037. for id, cd := range costData {
  1038. dataMins, ok := dataMinsByCluster[id]
  1039. if !ok {
  1040. dataMins = mins
  1041. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  1042. }
  1043. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  1044. if err != nil {
  1045. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  1046. return nil, err
  1047. }
  1048. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  1049. costs.CPUBreakdown = cpuBD
  1050. }
  1051. if ramBD, ok := ramBreakdownMap[id]; ok {
  1052. costs.RAMBreakdown = ramBD
  1053. }
  1054. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  1055. if pvUC, ok := pvUsedCostMap[id]; ok {
  1056. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  1057. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  1058. }
  1059. costs.DataMinutes = dataMins
  1060. costsByCluster[id] = costs
  1061. }
  1062. return costsByCluster, nil
  1063. }
  1064. type Totals struct {
  1065. TotalCost [][]string `json:"totalcost"`
  1066. CPUCost [][]string `json:"cpucost"`
  1067. MemCost [][]string `json:"memcost"`
  1068. StorageCost [][]string `json:"storageCost"`
  1069. }
  1070. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  1071. if len(qrs) == 0 {
  1072. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  1073. }
  1074. result := qrs[0]
  1075. totals := [][]string{}
  1076. for _, value := range result.Values {
  1077. d0 := fmt.Sprintf("%f", value.Timestamp)
  1078. d1 := fmt.Sprintf("%f", value.Value)
  1079. toAppend := []string{
  1080. d0,
  1081. d1,
  1082. }
  1083. totals = append(totals, toAppend)
  1084. }
  1085. return totals, nil
  1086. }
  1087. // ClusterCostsOverTime gives the full cluster costs over time
  1088. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  1089. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  1090. if localStorageQuery != "" {
  1091. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  1092. }
  1093. layout := "2006-01-02T15:04:05.000Z"
  1094. start, err := time.Parse(layout, startString)
  1095. if err != nil {
  1096. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1097. return nil, err
  1098. }
  1099. end, err := time.Parse(layout, endString)
  1100. if err != nil {
  1101. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1102. return nil, err
  1103. }
  1104. window, err := time.ParseDuration(windowString)
  1105. if err != nil {
  1106. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1107. return nil, err
  1108. }
  1109. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  1110. if offset != "" {
  1111. offset = fmt.Sprintf("offset %s", offset)
  1112. }
  1113. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  1114. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  1115. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  1116. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  1117. ctx := prom.NewContext(cli)
  1118. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  1119. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  1120. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  1121. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  1122. resultClusterCores, err := resChClusterCores.Await()
  1123. if err != nil {
  1124. return nil, err
  1125. }
  1126. resultClusterRAM, err := resChClusterRAM.Await()
  1127. if err != nil {
  1128. return nil, err
  1129. }
  1130. resultStorage, err := resChStorage.Await()
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. resultTotal, err := resChTotal.Await()
  1135. if err != nil {
  1136. return nil, err
  1137. }
  1138. coreTotal, err := resultToTotals(resultClusterCores)
  1139. if err != nil {
  1140. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  1141. return nil, err
  1142. }
  1143. ramTotal, err := resultToTotals(resultClusterRAM)
  1144. if err != nil {
  1145. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  1146. return nil, err
  1147. }
  1148. storageTotal, err := resultToTotals(resultStorage)
  1149. if err != nil {
  1150. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  1151. }
  1152. clusterTotal, err := resultToTotals(resultTotal)
  1153. if err != nil {
  1154. // If clusterTotal query failed, it's likely because there are no PVs, which
  1155. // causes the qTotal query to return no data. Instead, query only node costs.
  1156. // If that fails, return an error because something is actually wrong.
  1157. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  1158. resultNodes, err := ctx.QueryRangeSync(qNodes, start, end, window)
  1159. if err != nil {
  1160. return nil, err
  1161. }
  1162. clusterTotal, err = resultToTotals(resultNodes)
  1163. if err != nil {
  1164. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  1165. return nil, err
  1166. }
  1167. }
  1168. return &Totals{
  1169. TotalCost: clusterTotal,
  1170. CPUCost: coreTotal,
  1171. MemCost: ramTotal,
  1172. StorageCost: storageTotal,
  1173. }, nil
  1174. }