cluster.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. package costmodel
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. "github.com/opencost/opencost/pkg/cloud/provider"
  7. prometheus "github.com/prometheus/client_golang/api"
  8. "golang.org/x/exp/slices"
  9. "github.com/opencost/opencost/pkg/cloud/models"
  10. "github.com/opencost/opencost/pkg/env"
  11. "github.com/opencost/opencost/pkg/kubecost"
  12. "github.com/opencost/opencost/pkg/log"
  13. "github.com/opencost/opencost/pkg/prom"
  14. "github.com/opencost/opencost/pkg/util/timeutil"
  15. )
  16. const (
  17. queryClusterCores = `sum(
  18. avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s] %s)) by (node, %s) * avg(avg_over_time(node_cpu_hourly_cost{%s}[%s] %s)) by (node, %s) * 730 +
  19. avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, %s) * 730
  20. ) by (%s)`
  21. queryClusterRAM = `sum(
  22. avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s] %s)) by (node, %s) / 1024 / 1024 / 1024 * avg(avg_over_time(node_ram_hourly_cost{%s}[%s] %s)) by (node, %s) * 730
  23. ) by (%s)`
  24. queryStorage = `sum(
  25. avg(avg_over_time(pv_hourly_cost{%s}[%s] %s)) by (persistentvolume, %s) * 730
  26. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s] %s)) by (persistentvolume, %s) / 1024 / 1024 / 1024
  27. ) by (%s) %s`
  28. queryTotal = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 +
  29. sum(
  30. avg(avg_over_time(pv_hourly_cost{%s}[1h])) by (persistentvolume, %s) * 730
  31. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[1h])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  32. ) by (%s) %s`
  33. queryNodes = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 %s`
  34. )
  35. const maxLocalDiskSize = 200 // AWS limits root disks to 100 Gi, and occasional metric errors in filesystem size should not contribute to large costs.
  36. // Costs represents cumulative and monthly cluster costs over a given duration. Costs
  37. // are broken down by cores, memory, and storage.
  38. type ClusterCosts struct {
  39. Start *time.Time `json:"startTime"`
  40. End *time.Time `json:"endTime"`
  41. CPUCumulative float64 `json:"cpuCumulativeCost"`
  42. CPUMonthly float64 `json:"cpuMonthlyCost"`
  43. CPUBreakdown *ClusterCostsBreakdown `json:"cpuBreakdown"`
  44. GPUCumulative float64 `json:"gpuCumulativeCost"`
  45. GPUMonthly float64 `json:"gpuMonthlyCost"`
  46. RAMCumulative float64 `json:"ramCumulativeCost"`
  47. RAMMonthly float64 `json:"ramMonthlyCost"`
  48. RAMBreakdown *ClusterCostsBreakdown `json:"ramBreakdown"`
  49. StorageCumulative float64 `json:"storageCumulativeCost"`
  50. StorageMonthly float64 `json:"storageMonthlyCost"`
  51. StorageBreakdown *ClusterCostsBreakdown `json:"storageBreakdown"`
  52. TotalCumulative float64 `json:"totalCumulativeCost"`
  53. TotalMonthly float64 `json:"totalMonthlyCost"`
  54. DataMinutes float64
  55. }
  56. // ClusterCostsBreakdown provides percentage-based breakdown of a resource by
  57. // categories: user for user-space (i.e. non-system) usage, system, and idle.
  58. type ClusterCostsBreakdown struct {
  59. Idle float64 `json:"idle"`
  60. Other float64 `json:"other"`
  61. System float64 `json:"system"`
  62. User float64 `json:"user"`
  63. }
  64. // NewClusterCostsFromCumulative takes cumulative cost data over a given time range, computes
  65. // the associated monthly rate data, and returns the Costs.
  66. func NewClusterCostsFromCumulative(cpu, gpu, ram, storage float64, window, offset time.Duration, dataHours float64) (*ClusterCosts, error) {
  67. start, end := timeutil.ParseTimeRange(window, offset)
  68. // If the number of hours is not given (i.e. is zero) compute one from the window and offset
  69. if dataHours == 0 {
  70. dataHours = end.Sub(start).Hours()
  71. }
  72. // Do not allow zero-length windows to prevent divide-by-zero issues
  73. if dataHours == 0 {
  74. return nil, fmt.Errorf("illegal time range: window %s, offset %s", window, offset)
  75. }
  76. cc := &ClusterCosts{
  77. Start: &start,
  78. End: &end,
  79. CPUCumulative: cpu,
  80. GPUCumulative: gpu,
  81. RAMCumulative: ram,
  82. StorageCumulative: storage,
  83. TotalCumulative: cpu + gpu + ram + storage,
  84. CPUMonthly: cpu / dataHours * (timeutil.HoursPerMonth),
  85. GPUMonthly: gpu / dataHours * (timeutil.HoursPerMonth),
  86. RAMMonthly: ram / dataHours * (timeutil.HoursPerMonth),
  87. StorageMonthly: storage / dataHours * (timeutil.HoursPerMonth),
  88. }
  89. cc.TotalMonthly = cc.CPUMonthly + cc.GPUMonthly + cc.RAMMonthly + cc.StorageMonthly
  90. return cc, nil
  91. }
  92. type Disk struct {
  93. Cluster string
  94. Name string
  95. ProviderID string
  96. StorageClass string
  97. VolumeName string
  98. ClaimName string
  99. ClaimNamespace string
  100. Cost float64
  101. Bytes float64
  102. // These two fields may not be available at all times because they rely on
  103. // a new set of metrics that may or may not be available. Thus, they must
  104. // be nilable to represent the complete absence of the data.
  105. //
  106. // In other words, nilability here lets us distinguish between
  107. // "metric is not available" and "metric is available but is 0".
  108. //
  109. // They end in "Ptr" to distinguish from an earlier version in order to
  110. // ensure that all usages are checked for nil.
  111. BytesUsedAvgPtr *float64
  112. BytesUsedMaxPtr *float64
  113. Local bool
  114. Start time.Time
  115. End time.Time
  116. Minutes float64
  117. Breakdown *ClusterCostsBreakdown
  118. }
  119. type DiskIdentifier struct {
  120. Cluster string
  121. Name string
  122. }
  123. func ClusterDisks(client prometheus.Client, provider models.Provider, start, end time.Time) (map[DiskIdentifier]*Disk, error) {
  124. // Query for the duration between start and end
  125. durStr := timeutil.DurationString(end.Sub(start))
  126. if durStr == "" {
  127. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  128. }
  129. // Start from the time "end", querying backwards
  130. t := end
  131. // minsPerResolution determines accuracy and resource use for the following
  132. // queries. Smaller values (higher resolution) result in better accuracy,
  133. // but more expensive queries, and vice-a-versa.
  134. resolution := env.GetETLResolution()
  135. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  136. var minsPerResolution int
  137. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  138. minsPerResolution = 1
  139. log.DedupedWarningf(3, "ClusterDisks(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  140. }
  141. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  142. // value, converts it to a cumulative value; i.e.
  143. // [$/hr] * [min/res]*[hr/min] = [$/res]
  144. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  145. // TODO niko/assets how do we not hard-code this price?
  146. costPerGBHr := 0.04 / 730.0
  147. ctx := prom.NewNamedContext(client, prom.ClusterContextName)
  148. queryPVCost := fmt.Sprintf(`avg(avg_over_time(pv_hourly_cost{%s}[%s])) by (%s, persistentvolume,provider_id)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  149. queryPVSize := fmt.Sprintf(`avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s])) by (%s, persistentvolume)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  150. queryActiveMins := fmt.Sprintf(`avg(kube_persistentvolume_capacity_bytes{%s}) by (%s, persistentvolume)[%s:%dm]`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  151. queryPVStorageClass := fmt.Sprintf(`avg(avg_over_time(kubecost_pv_info{%s}[%s])) by (%s, persistentvolume, storageclass)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  152. queryPVUsedAvg := fmt.Sprintf(`avg(avg_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  153. queryPVUsedMax := fmt.Sprintf(`max(max_over_time(kubelet_volume_stats_used_bytes{%s}[%s])) by (%s, persistentvolumeclaim, namespace)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  154. queryPVCInfo := fmt.Sprintf(`avg(avg_over_time(kube_persistentvolumeclaim_info{%s}[%s])) by (%s, volumename, persistentvolumeclaim, namespace)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  155. queryLocalStorageCost := fmt.Sprintf(`sum_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/", %s}) by (instance, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  156. queryLocalStorageUsedCost := fmt.Sprintf(`sum_over_time(sum(container_fs_usage_bytes{device!="tmpfs", id="/", %s}) by (instance, %s)[%s:%dm]) / 1024 / 1024 / 1024 * %f * %f`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution, hourlyToCumulative, costPerGBHr)
  157. queryLocalStorageUsedAvg := fmt.Sprintf(`avg(avg_over_time(container_fs_usage_bytes{device!="tmpfs", id="/", %s}[%s])) by (instance, %s)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  158. queryLocalStorageUsedMax := fmt.Sprintf(`max(max_over_time(container_fs_usage_bytes{device!="tmpfs", id="/", %s}[%s])) by (instance, %s)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  159. queryLocalStorageBytes := fmt.Sprintf(`avg_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/", %s}) by (instance, %s)[%s:%dm])`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  160. queryLocalActiveMins := fmt.Sprintf(`count(node_total_hourly_cost{%s}) by (%s, node)[%s:%dm]`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  161. resChPVCost := ctx.QueryAtTime(queryPVCost, t)
  162. resChPVSize := ctx.QueryAtTime(queryPVSize, t)
  163. resChActiveMins := ctx.QueryAtTime(queryActiveMins, t)
  164. resChPVStorageClass := ctx.QueryAtTime(queryPVStorageClass, t)
  165. resChPVUsedAvg := ctx.QueryAtTime(queryPVUsedAvg, t)
  166. resChPVUsedMax := ctx.QueryAtTime(queryPVUsedMax, t)
  167. resChPVCInfo := ctx.QueryAtTime(queryPVCInfo, t)
  168. resChLocalStorageCost := ctx.QueryAtTime(queryLocalStorageCost, t)
  169. resChLocalStorageUsedCost := ctx.QueryAtTime(queryLocalStorageUsedCost, t)
  170. resChLocalStoreageUsedAvg := ctx.QueryAtTime(queryLocalStorageUsedAvg, t)
  171. resChLocalStoreageUsedMax := ctx.QueryAtTime(queryLocalStorageUsedMax, t)
  172. resChLocalStorageBytes := ctx.QueryAtTime(queryLocalStorageBytes, t)
  173. resChLocalActiveMins := ctx.QueryAtTime(queryLocalActiveMins, t)
  174. resPVCost, _ := resChPVCost.Await()
  175. resPVSize, _ := resChPVSize.Await()
  176. resActiveMins, _ := resChActiveMins.Await()
  177. resPVStorageClass, _ := resChPVStorageClass.Await()
  178. resPVUsedAvg, _ := resChPVUsedAvg.Await()
  179. resPVUsedMax, _ := resChPVUsedMax.Await()
  180. resPVCInfo, _ := resChPVCInfo.Await()
  181. resLocalStorageCost, _ := resChLocalStorageCost.Await()
  182. resLocalStorageUsedCost, _ := resChLocalStorageUsedCost.Await()
  183. resLocalStorageUsedAvg, _ := resChLocalStoreageUsedAvg.Await()
  184. resLocalStorageUsedMax, _ := resChLocalStoreageUsedMax.Await()
  185. resLocalStorageBytes, _ := resChLocalStorageBytes.Await()
  186. resLocalActiveMins, _ := resChLocalActiveMins.Await()
  187. if ctx.HasErrors() {
  188. return nil, ctx.ErrorCollection()
  189. }
  190. diskMap := map[DiskIdentifier]*Disk{}
  191. for _, result := range resPVCInfo {
  192. cluster, err := result.GetString(env.GetPromClusterLabel())
  193. if err != nil {
  194. cluster = env.GetClusterID()
  195. }
  196. volumeName, err := result.GetString("volumename")
  197. if err != nil {
  198. log.Debugf("ClusterDisks: pv claim data missing volumename")
  199. continue
  200. }
  201. claimName, err := result.GetString("persistentvolumeclaim")
  202. if err != nil {
  203. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  204. continue
  205. }
  206. claimNamespace, err := result.GetString("namespace")
  207. if err != nil {
  208. log.Debugf("ClusterDisks: pv claim data missing namespace")
  209. continue
  210. }
  211. key := DiskIdentifier{cluster, volumeName}
  212. if _, ok := diskMap[key]; !ok {
  213. diskMap[key] = &Disk{
  214. Cluster: cluster,
  215. Name: volumeName,
  216. Breakdown: &ClusterCostsBreakdown{},
  217. }
  218. }
  219. diskMap[key].VolumeName = volumeName
  220. diskMap[key].ClaimName = claimName
  221. diskMap[key].ClaimNamespace = claimNamespace
  222. }
  223. pvCosts(diskMap, resolution, resActiveMins, resPVSize, resPVCost, resPVUsedAvg, resPVUsedMax, resPVCInfo, provider)
  224. for _, result := range resLocalStorageCost {
  225. cluster, err := result.GetString(env.GetPromClusterLabel())
  226. if err != nil {
  227. cluster = env.GetClusterID()
  228. }
  229. name, err := result.GetString("instance")
  230. if err != nil {
  231. log.Warnf("ClusterDisks: local storage data missing instance")
  232. continue
  233. }
  234. cost := result.Values[0].Value
  235. key := DiskIdentifier{cluster, name}
  236. if _, ok := diskMap[key]; !ok {
  237. diskMap[key] = &Disk{
  238. Cluster: cluster,
  239. Name: name,
  240. Breakdown: &ClusterCostsBreakdown{},
  241. Local: true,
  242. }
  243. }
  244. diskMap[key].Cost += cost
  245. //Assigning explicitly the storage class of local storage to local
  246. diskMap[key].StorageClass = kubecost.LocalStorageClass
  247. }
  248. for _, result := range resLocalStorageUsedCost {
  249. cluster, err := result.GetString(env.GetPromClusterLabel())
  250. if err != nil {
  251. cluster = env.GetClusterID()
  252. }
  253. name, err := result.GetString("instance")
  254. if err != nil {
  255. log.Warnf("ClusterDisks: local storage usage data missing instance")
  256. continue
  257. }
  258. cost := result.Values[0].Value
  259. key := DiskIdentifier{cluster, name}
  260. if _, ok := diskMap[key]; !ok {
  261. diskMap[key] = &Disk{
  262. Cluster: cluster,
  263. Name: name,
  264. Breakdown: &ClusterCostsBreakdown{},
  265. Local: true,
  266. }
  267. }
  268. diskMap[key].Breakdown.System = cost / diskMap[key].Cost
  269. }
  270. for _, result := range resLocalStorageUsedAvg {
  271. cluster, err := result.GetString(env.GetPromClusterLabel())
  272. if err != nil {
  273. cluster = env.GetClusterID()
  274. }
  275. name, err := result.GetString("instance")
  276. if err != nil {
  277. log.Warnf("ClusterDisks: local storage data missing instance")
  278. continue
  279. }
  280. bytesAvg := result.Values[0].Value
  281. key := DiskIdentifier{cluster, name}
  282. if _, ok := diskMap[key]; !ok {
  283. diskMap[key] = &Disk{
  284. Cluster: cluster,
  285. Name: name,
  286. Breakdown: &ClusterCostsBreakdown{},
  287. Local: true,
  288. }
  289. }
  290. diskMap[key].BytesUsedAvgPtr = &bytesAvg
  291. }
  292. for _, result := range resLocalStorageUsedMax {
  293. cluster, err := result.GetString(env.GetPromClusterLabel())
  294. if err != nil {
  295. cluster = env.GetClusterID()
  296. }
  297. name, err := result.GetString("instance")
  298. if err != nil {
  299. log.Warnf("ClusterDisks: local storage data missing instance")
  300. continue
  301. }
  302. bytesMax := result.Values[0].Value
  303. key := DiskIdentifier{cluster, name}
  304. if _, ok := diskMap[key]; !ok {
  305. diskMap[key] = &Disk{
  306. Cluster: cluster,
  307. Name: name,
  308. Breakdown: &ClusterCostsBreakdown{},
  309. Local: true,
  310. }
  311. }
  312. diskMap[key].BytesUsedMaxPtr = &bytesMax
  313. }
  314. for _, result := range resLocalStorageBytes {
  315. cluster, err := result.GetString(env.GetPromClusterLabel())
  316. if err != nil {
  317. cluster = env.GetClusterID()
  318. }
  319. name, err := result.GetString("instance")
  320. if err != nil {
  321. log.Warnf("ClusterDisks: local storage data missing instance")
  322. continue
  323. }
  324. bytes := result.Values[0].Value
  325. key := DiskIdentifier{cluster, name}
  326. if _, ok := diskMap[key]; !ok {
  327. diskMap[key] = &Disk{
  328. Cluster: cluster,
  329. Name: name,
  330. Breakdown: &ClusterCostsBreakdown{},
  331. Local: true,
  332. }
  333. }
  334. diskMap[key].Bytes = bytes
  335. if bytes/1024/1024/1024 > maxLocalDiskSize {
  336. log.DedupedWarningf(5, "Deleting large root disk/localstorage disk from analysis")
  337. delete(diskMap, key)
  338. }
  339. }
  340. for _, result := range resLocalActiveMins {
  341. cluster, err := result.GetString(env.GetPromClusterLabel())
  342. if err != nil {
  343. cluster = env.GetClusterID()
  344. }
  345. name, err := result.GetString("node")
  346. if err != nil {
  347. log.DedupedWarningf(5, "ClusterDisks: local active mins data missing instance")
  348. continue
  349. }
  350. key := DiskIdentifier{cluster, name}
  351. if _, ok := diskMap[key]; !ok {
  352. log.DedupedWarningf(5, "ClusterDisks: local active mins for unidentified disk or disk deleted from analysis")
  353. continue
  354. }
  355. if len(result.Values) == 0 {
  356. continue
  357. }
  358. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  359. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  360. mins := e.Sub(s).Minutes()
  361. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  362. diskMap[key].End = e
  363. diskMap[key].Start = s
  364. diskMap[key].Minutes = mins
  365. }
  366. var unTracedDiskLogData []DiskIdentifier
  367. //Iterating through Persistent Volume given by custom metrics kubecost_pv_info and assign the storage class if known and __unknown__ if not populated.
  368. for _, result := range resPVStorageClass {
  369. cluster, err := result.GetString(env.GetPromClusterLabel())
  370. if err != nil {
  371. cluster = env.GetClusterID()
  372. }
  373. name, _ := result.GetString("persistentvolume")
  374. key := DiskIdentifier{cluster, name}
  375. if _, ok := diskMap[key]; !ok {
  376. if !slices.Contains(unTracedDiskLogData, key) {
  377. unTracedDiskLogData = append(unTracedDiskLogData, key)
  378. }
  379. continue
  380. }
  381. if len(result.Values) == 0 {
  382. continue
  383. }
  384. storageClass, err := result.GetString("storageclass")
  385. if err != nil {
  386. diskMap[key].StorageClass = kubecost.UnknownStorageClass
  387. } else {
  388. diskMap[key].StorageClass = storageClass
  389. }
  390. }
  391. // Logging the unidentified disk information outside the loop
  392. for _, unIdentifiedDisk := range unTracedDiskLogData {
  393. log.Warnf("ClusterDisks: Cluster %s has Storage Class information for unidentified disk %s or disk deleted from analysis", unIdentifiedDisk.Cluster, unIdentifiedDisk.Name)
  394. }
  395. for _, disk := range diskMap {
  396. // Apply all remaining RAM to Idle
  397. disk.Breakdown.Idle = 1.0 - (disk.Breakdown.System + disk.Breakdown.Other + disk.Breakdown.User)
  398. // Set provider Id to the name for reconciliation
  399. if disk.ProviderID == "" {
  400. disk.ProviderID = disk.Name
  401. }
  402. }
  403. return diskMap, nil
  404. }
  405. type NodeOverhead struct {
  406. CpuOverheadFraction float64
  407. RamOverheadFraction float64
  408. }
  409. type Node struct {
  410. Cluster string
  411. Name string
  412. ProviderID string
  413. NodeType string
  414. CPUCost float64
  415. CPUCores float64
  416. GPUCost float64
  417. GPUCount float64
  418. RAMCost float64
  419. RAMBytes float64
  420. Discount float64
  421. Preemptible bool
  422. CPUBreakdown *ClusterCostsBreakdown
  423. RAMBreakdown *ClusterCostsBreakdown
  424. Start time.Time
  425. End time.Time
  426. Minutes float64
  427. Labels map[string]string
  428. CostPerCPUHr float64
  429. CostPerRAMGiBHr float64
  430. CostPerGPUHr float64
  431. Overhead *NodeOverhead
  432. }
  433. // GKE lies about the number of cores e2 nodes have. This table
  434. // contains a mapping from node type -> actual CPU cores
  435. // for those cases.
  436. var partialCPUMap = map[string]float64{
  437. "e2-micro": 0.25,
  438. "e2-small": 0.5,
  439. "e2-medium": 1.0,
  440. }
  441. type NodeIdentifier struct {
  442. Cluster string
  443. Name string
  444. ProviderID string
  445. }
  446. type nodeIdentifierNoProviderID struct {
  447. Cluster string
  448. Name string
  449. }
  450. func costTimesMinuteAndCount(activeDataMap map[NodeIdentifier]activeData, costMap map[NodeIdentifier]float64, resourceCountMap map[nodeIdentifierNoProviderID]float64) {
  451. for k, v := range activeDataMap {
  452. keyNon := nodeIdentifierNoProviderID{
  453. Cluster: k.Cluster,
  454. Name: k.Name,
  455. }
  456. if cost, ok := costMap[k]; ok {
  457. minutes := v.minutes
  458. count := 1.0
  459. if c, ok := resourceCountMap[keyNon]; ok {
  460. count = c
  461. }
  462. costMap[k] = cost * (minutes / 60) * count
  463. }
  464. }
  465. }
  466. func costTimesMinute(activeDataMap map[NodeIdentifier]activeData, costMap map[NodeIdentifier]float64) {
  467. for k, v := range activeDataMap {
  468. if cost, ok := costMap[k]; ok {
  469. minutes := v.minutes
  470. costMap[k] = cost * (minutes / 60)
  471. }
  472. }
  473. }
  474. func ClusterNodes(cp models.Provider, client prometheus.Client, start, end time.Time) (map[NodeIdentifier]*Node, error) {
  475. // Query for the duration between start and end
  476. durStr := timeutil.DurationString(end.Sub(start))
  477. if durStr == "" {
  478. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  479. }
  480. // Start from the time "end", querying backwards
  481. t := end
  482. // minsPerResolution determines accuracy and resource use for the following
  483. // queries. Smaller values (higher resolution) result in better accuracy,
  484. // but more expensive queries, and vice-a-versa.
  485. resolution := env.GetETLResolution()
  486. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  487. var minsPerResolution int
  488. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  489. minsPerResolution = 1
  490. log.DedupedWarningf(3, "ClusterNodes(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  491. }
  492. requiredCtx := prom.NewNamedContext(client, prom.ClusterContextName)
  493. optionalCtx := prom.NewNamedContext(client, prom.ClusterOptionalContextName)
  494. queryNodeCPUHourlyCost := fmt.Sprintf(`avg(avg_over_time(node_cpu_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  495. queryNodeCPUCoresCapacity := fmt.Sprintf(`avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  496. queryNodeCPUCoresAllocatable := fmt.Sprintf(`avg(avg_over_time(kube_node_status_allocatable_cpu_cores{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  497. queryNodeRAMHourlyCost := fmt.Sprintf(`avg(avg_over_time(node_ram_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id) / 1024 / 1024 / 1024`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  498. queryNodeRAMBytesCapacity := fmt.Sprintf(`avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  499. queryNodeRAMBytesAllocatable := fmt.Sprintf(`avg(avg_over_time(kube_node_status_allocatable_memory_bytes{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  500. queryNodeGPUCount := fmt.Sprintf(`avg(avg_over_time(node_gpu_count{%s}[%s])) by (%s, node, provider_id)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  501. queryNodeGPUHourlyCost := fmt.Sprintf(`avg(avg_over_time(node_gpu_hourly_cost{%s}[%s])) by (%s, node, instance_type, provider_id)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  502. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total{%s}[%s:%dm])) by (kubernetes_node, %s, mode)`, env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel())
  503. queryNodeRAMSystemPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace="kube-system", %s}[%s:%dm])) by (instance, %s) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm])) by (node, %s), "instance", "$1", "node", "(.*)")) by (instance, %s)`, env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  504. queryNodeRAMUserPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace!="kube-system", %s}[%s:%dm])) by (instance, %s) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm])) by (node, %s), "instance", "$1", "node", "(.*)")) by (instance, %s)`, env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  505. queryActiveMins := fmt.Sprintf(`avg(node_total_hourly_cost{%s}) by (node, %s, provider_id)[%s:%dm]`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  506. queryIsSpot := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot{%s}[%s:%dm])`, env.GetPromClusterFilter(), durStr, minsPerResolution)
  507. queryLabels := fmt.Sprintf(`count_over_time(kube_node_labels{%s}[%s:%dm])`, env.GetPromClusterFilter(), durStr, minsPerResolution)
  508. // Return errors if these fail
  509. resChNodeCPUHourlyCost := requiredCtx.QueryAtTime(queryNodeCPUHourlyCost, t)
  510. resChNodeCPUCoresCapacity := requiredCtx.QueryAtTime(queryNodeCPUCoresCapacity, t)
  511. resChNodeCPUCoresAllocatable := requiredCtx.QueryAtTime(queryNodeCPUCoresAllocatable, t)
  512. resChNodeRAMHourlyCost := requiredCtx.QueryAtTime(queryNodeRAMHourlyCost, t)
  513. resChNodeRAMBytesCapacity := requiredCtx.QueryAtTime(queryNodeRAMBytesCapacity, t)
  514. resChNodeRAMBytesAllocatable := requiredCtx.QueryAtTime(queryNodeRAMBytesAllocatable, t)
  515. resChNodeGPUCount := requiredCtx.QueryAtTime(queryNodeGPUCount, t)
  516. resChNodeGPUHourlyCost := requiredCtx.QueryAtTime(queryNodeGPUHourlyCost, t)
  517. resChActiveMins := requiredCtx.QueryAtTime(queryActiveMins, t)
  518. resChIsSpot := requiredCtx.QueryAtTime(queryIsSpot, t)
  519. // Do not return errors if these fail, but log warnings
  520. resChNodeCPUModeTotal := optionalCtx.QueryAtTime(queryNodeCPUModeTotal, t)
  521. resChNodeRAMSystemPct := optionalCtx.QueryAtTime(queryNodeRAMSystemPct, t)
  522. resChNodeRAMUserPct := optionalCtx.QueryAtTime(queryNodeRAMUserPct, t)
  523. resChLabels := optionalCtx.QueryAtTime(queryLabels, t)
  524. resNodeCPUHourlyCost, _ := resChNodeCPUHourlyCost.Await()
  525. resNodeCPUCoresCapacity, _ := resChNodeCPUCoresCapacity.Await()
  526. resNodeCPUCoresAllocatable, _ := resChNodeCPUCoresAllocatable.Await()
  527. resNodeGPUCount, _ := resChNodeGPUCount.Await()
  528. resNodeGPUHourlyCost, _ := resChNodeGPUHourlyCost.Await()
  529. resNodeRAMHourlyCost, _ := resChNodeRAMHourlyCost.Await()
  530. resNodeRAMBytesCapacity, _ := resChNodeRAMBytesCapacity.Await()
  531. resNodeRAMBytesAllocatable, _ := resChNodeRAMBytesAllocatable.Await()
  532. resIsSpot, _ := resChIsSpot.Await()
  533. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  534. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  535. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  536. resActiveMins, _ := resChActiveMins.Await()
  537. resLabels, _ := resChLabels.Await()
  538. if optionalCtx.HasErrors() {
  539. for _, err := range optionalCtx.Errors() {
  540. log.Warnf("ClusterNodes: %s", err)
  541. }
  542. }
  543. if requiredCtx.HasErrors() {
  544. for _, err := range requiredCtx.Errors() {
  545. log.Errorf("ClusterNodes: %s", err)
  546. }
  547. return nil, requiredCtx.ErrorCollection()
  548. }
  549. activeDataMap := buildActiveDataMap(resActiveMins, resolution)
  550. gpuCountMap := buildGPUCountMap(resNodeGPUCount)
  551. preemptibleMap := buildPreemptibleMap(resIsSpot)
  552. cpuCostMap, clusterAndNameToType1 := buildCPUCostMap(resNodeCPUHourlyCost, cp, preemptibleMap)
  553. ramCostMap, clusterAndNameToType2 := buildRAMCostMap(resNodeRAMHourlyCost, cp, preemptibleMap)
  554. gpuCostMap, clusterAndNameToType3 := buildGPUCostMap(resNodeGPUHourlyCost, gpuCountMap, cp, preemptibleMap)
  555. clusterAndNameToTypeIntermediate := mergeTypeMaps(clusterAndNameToType1, clusterAndNameToType2)
  556. clusterAndNameToType := mergeTypeMaps(clusterAndNameToTypeIntermediate, clusterAndNameToType3)
  557. cpuCoresCapacityMap := buildCPUCoresMap(resNodeCPUCoresCapacity)
  558. ramBytesCapacityMap := buildRAMBytesMap(resNodeRAMBytesCapacity)
  559. cpuCoresAllocatableMap := buildCPUCoresMap(resNodeCPUCoresAllocatable)
  560. ramBytesAllocatableMap := buildRAMBytesMap(resNodeRAMBytesAllocatable)
  561. overheadMap := buildOverheadMap(ramBytesCapacityMap, ramBytesAllocatableMap, cpuCoresCapacityMap, cpuCoresAllocatableMap)
  562. ramUserPctMap := buildRAMUserPctMap(resNodeRAMUserPct)
  563. ramSystemPctMap := buildRAMSystemPctMap(resNodeRAMSystemPct)
  564. cpuBreakdownMap := buildCPUBreakdownMap(resNodeCPUModeTotal)
  565. labelsMap := buildLabelsMap(resLabels)
  566. costTimesMinuteAndCount(activeDataMap, cpuCostMap, cpuCoresCapacityMap)
  567. costTimesMinuteAndCount(activeDataMap, ramCostMap, ramBytesCapacityMap)
  568. costTimesMinute(activeDataMap, gpuCostMap) // there's no need to do a weird "nodeIdentifierNoProviderID" type match since gpuCounts have a providerID
  569. nodeMap := buildNodeMap(
  570. cpuCostMap, ramCostMap, gpuCostMap, gpuCountMap,
  571. cpuCoresCapacityMap, ramBytesCapacityMap, ramUserPctMap,
  572. ramSystemPctMap,
  573. cpuBreakdownMap,
  574. activeDataMap,
  575. preemptibleMap,
  576. labelsMap,
  577. clusterAndNameToType,
  578. resolution,
  579. overheadMap,
  580. )
  581. c, err := cp.GetConfig()
  582. if err != nil {
  583. return nil, err
  584. }
  585. discount, err := ParsePercentString(c.Discount)
  586. if err != nil {
  587. return nil, err
  588. }
  589. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  590. if err != nil {
  591. return nil, err
  592. }
  593. for _, node := range nodeMap {
  594. // TODO take GKE Reserved Instances into account
  595. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  596. // Apply all remaining resources to Idle
  597. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  598. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  599. }
  600. return nodeMap, nil
  601. }
  602. type LoadBalancerIdentifier struct {
  603. Cluster string
  604. Namespace string
  605. Name string
  606. }
  607. type LoadBalancer struct {
  608. Cluster string
  609. Namespace string
  610. Name string
  611. ProviderID string
  612. Cost float64
  613. Start time.Time
  614. End time.Time
  615. Minutes float64
  616. }
  617. func ClusterLoadBalancers(client prometheus.Client, start, end time.Time) (map[LoadBalancerIdentifier]*LoadBalancer, error) {
  618. // Query for the duration between start and end
  619. durStr := timeutil.DurationString(end.Sub(start))
  620. if durStr == "" {
  621. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  622. }
  623. // Start from the time "end", querying backwards
  624. t := end
  625. // minsPerResolution determines accuracy and resource use for the following
  626. // queries. Smaller values (higher resolution) result in better accuracy,
  627. // but more expensive queries, and vice-a-versa.
  628. resolution := env.GetETLResolution()
  629. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  630. var minsPerResolution int
  631. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  632. minsPerResolution = 1
  633. log.DedupedWarningf(3, "ClusterLoadBalancers(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  634. }
  635. ctx := prom.NewNamedContext(client, prom.ClusterContextName)
  636. queryLBCost := fmt.Sprintf(`avg(avg_over_time(kubecost_load_balancer_cost{%s}[%s])) by (namespace, service_name, %s, ingress_ip)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  637. queryActiveMins := fmt.Sprintf(`avg(kubecost_load_balancer_cost{%s}) by (namespace, service_name, %s, ingress_ip)[%s:%dm]`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  638. resChLBCost := ctx.QueryAtTime(queryLBCost, t)
  639. resChActiveMins := ctx.QueryAtTime(queryActiveMins, t)
  640. resLBCost, _ := resChLBCost.Await()
  641. resActiveMins, _ := resChActiveMins.Await()
  642. if ctx.HasErrors() {
  643. return nil, ctx.ErrorCollection()
  644. }
  645. loadBalancerMap := make(map[LoadBalancerIdentifier]*LoadBalancer, len(resActiveMins))
  646. for _, result := range resActiveMins {
  647. cluster, err := result.GetString(env.GetPromClusterLabel())
  648. if err != nil {
  649. cluster = env.GetClusterID()
  650. }
  651. namespace, err := result.GetString("namespace")
  652. if err != nil {
  653. log.Warnf("ClusterLoadBalancers: LB cost data missing namespace")
  654. continue
  655. }
  656. name, err := result.GetString("service_name")
  657. if err != nil {
  658. log.Warnf("ClusterLoadBalancers: LB cost data missing service_name")
  659. continue
  660. }
  661. providerID, err := result.GetString("ingress_ip")
  662. if err != nil {
  663. log.DedupedWarningf(5, "ClusterLoadBalancers: LB cost data missing ingress_ip")
  664. providerID = ""
  665. }
  666. key := LoadBalancerIdentifier{
  667. Cluster: cluster,
  668. Namespace: namespace,
  669. Name: name,
  670. }
  671. // Skip if there are no data
  672. if len(result.Values) == 0 {
  673. continue
  674. }
  675. // Add load balancer to the set of load balancers
  676. if _, ok := loadBalancerMap[key]; !ok {
  677. loadBalancerMap[key] = &LoadBalancer{
  678. Cluster: cluster,
  679. Namespace: namespace,
  680. Name: fmt.Sprintf("%s/%s", namespace, name), // TODO:ETL this is kept for backwards-compatibility, but not good
  681. ProviderID: provider.ParseLBID(providerID),
  682. }
  683. }
  684. // Append start, end, and minutes. This should come before all other data.
  685. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  686. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  687. loadBalancerMap[key].Start = s
  688. loadBalancerMap[key].End = e
  689. loadBalancerMap[key].Minutes = e.Sub(s).Minutes()
  690. // Fill in Provider ID if it is available and missing in the loadBalancerMap
  691. // Prevents there from being a duplicate LoadBalancers on the same day
  692. if providerID != "" && loadBalancerMap[key].ProviderID == "" {
  693. loadBalancerMap[key].ProviderID = providerID
  694. }
  695. }
  696. for _, result := range resLBCost {
  697. cluster, err := result.GetString(env.GetPromClusterLabel())
  698. if err != nil {
  699. cluster = env.GetClusterID()
  700. }
  701. namespace, err := result.GetString("namespace")
  702. if err != nil {
  703. log.Warnf("ClusterLoadBalancers: LB cost data missing namespace")
  704. continue
  705. }
  706. name, err := result.GetString("service_name")
  707. if err != nil {
  708. log.Warnf("ClusterLoadBalancers: LB cost data missing service_name")
  709. continue
  710. }
  711. key := LoadBalancerIdentifier{
  712. Cluster: cluster,
  713. Namespace: namespace,
  714. Name: name,
  715. }
  716. // Apply cost as price-per-hour * hours
  717. if lb, ok := loadBalancerMap[key]; ok {
  718. lbPricePerHr := result.Values[0].Value
  719. hrs := lb.Minutes / 60.0
  720. lb.Cost += lbPricePerHr * hrs
  721. } else {
  722. log.DedupedWarningf(20, "ClusterLoadBalancers: found minutes for key that does not exist: %s", key)
  723. }
  724. }
  725. return loadBalancerMap, nil
  726. }
  727. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  728. func (a *Accesses) ComputeClusterCosts(client prometheus.Client, provider models.Provider, window, offset time.Duration, withBreakdown bool) (map[string]*ClusterCosts, error) {
  729. if window < 10*time.Minute {
  730. return nil, fmt.Errorf("minimum window of 10m required; got %s", window)
  731. }
  732. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  733. start, end := timeutil.ParseTimeRange(window, offset)
  734. mins := end.Sub(start).Minutes()
  735. windowStr := timeutil.DurationString(window)
  736. // minsPerResolution determines accuracy and resource use for the following
  737. // queries. Smaller values (higher resolution) result in better accuracy,
  738. // but more expensive queries, and vice-a-versa.
  739. resolution := env.GetETLResolution()
  740. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  741. var minsPerResolution int
  742. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) < 1 {
  743. minsPerResolution = 1
  744. log.DedupedWarningf(3, "ComputeClusterCosts(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  745. }
  746. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  747. // value, converts it to a cumulative value; i.e.
  748. // [$/hr] * [min/res]*[hr/min] = [$/res]
  749. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  750. const fmtQueryDataCount = `
  751. count_over_time(sum(kube_node_status_capacity_cpu_cores{%s}) by (%s)[%s:%dm]%s) * %d
  752. `
  753. const fmtQueryTotalGPU = `
  754. sum(
  755. sum_over_time(node_gpu_hourly_cost{%s}[%s:%dm]%s) * %f
  756. ) by (%s)
  757. `
  758. const fmtQueryTotalCPU = `
  759. sum(
  760. sum_over_time(avg(kube_node_status_capacity_cpu_cores{%s}) by (node, %s)[%s:%dm]%s) *
  761. avg(avg_over_time(node_cpu_hourly_cost{%s}[%s:%dm]%s)) by (node, %s) * %f
  762. ) by (%s)
  763. `
  764. const fmtQueryTotalRAM = `
  765. sum(
  766. sum_over_time(avg(kube_node_status_capacity_memory_bytes{%s}) by (node, %s)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  767. avg(avg_over_time(node_ram_hourly_cost{%s}[%s:%dm]%s)) by (node, %s) * %f
  768. ) by (%s)
  769. `
  770. const fmtQueryTotalStorage = `
  771. sum(
  772. sum_over_time(avg(kube_persistentvolume_capacity_bytes{%s}) by (persistentvolume, %s)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  773. avg(avg_over_time(pv_hourly_cost{%s}[%s:%dm]%s)) by (persistentvolume, %s) * %f
  774. ) by (%s)
  775. `
  776. const fmtQueryCPUModePct = `
  777. sum(rate(node_cpu_seconds_total{%s}[%s]%s)) by (%s, mode) / ignoring(mode)
  778. group_left sum(rate(node_cpu_seconds_total{%s}[%s]%s)) by (%s)
  779. `
  780. const fmtQueryRAMSystemPct = `
  781. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system", %s}[%s:%dm]%s)) by (%s)
  782. / sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm]%s)) by (%s)
  783. `
  784. const fmtQueryRAMUserPct = `
  785. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes{%s}[%s:%dm]%s)) by (%s)
  786. / sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm]%s)) by (%s)
  787. `
  788. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  789. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  790. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  791. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  792. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  793. if queryTotalLocalStorage != "" {
  794. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  795. }
  796. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  797. queryDataCount := fmt.Sprintf(fmtQueryDataCount, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, minsPerResolution)
  798. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, hourlyToCumulative, env.GetPromClusterLabel())
  799. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  800. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  801. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  802. ctx := prom.NewNamedContext(client, prom.ClusterContextName)
  803. resChs := ctx.QueryAll(
  804. queryDataCount,
  805. queryTotalGPU,
  806. queryTotalCPU,
  807. queryTotalRAM,
  808. queryTotalStorage,
  809. )
  810. // Only submit the local storage query if it is valid. Otherwise Prometheus
  811. // will return errors. Always append something to resChs, regardless, to
  812. // maintain indexing.
  813. if queryTotalLocalStorage != "" {
  814. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  815. } else {
  816. resChs = append(resChs, nil)
  817. }
  818. if withBreakdown {
  819. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel())
  820. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel())
  821. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel())
  822. bdResChs := ctx.QueryAll(
  823. queryCPUModePct,
  824. queryRAMSystemPct,
  825. queryRAMUserPct,
  826. )
  827. // Only submit the local storage query if it is valid. Otherwise Prometheus
  828. // will return errors. Always append something to resChs, regardless, to
  829. // maintain indexing.
  830. if queryUsedLocalStorage != "" {
  831. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  832. } else {
  833. bdResChs = append(bdResChs, nil)
  834. }
  835. resChs = append(resChs, bdResChs...)
  836. }
  837. resDataCount, _ := resChs[0].Await()
  838. resTotalGPU, _ := resChs[1].Await()
  839. resTotalCPU, _ := resChs[2].Await()
  840. resTotalRAM, _ := resChs[3].Await()
  841. resTotalStorage, _ := resChs[4].Await()
  842. if ctx.HasErrors() {
  843. return nil, ctx.ErrorCollection()
  844. }
  845. defaultClusterID := env.GetClusterID()
  846. dataMinsByCluster := map[string]float64{}
  847. for _, result := range resDataCount {
  848. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  849. if clusterID == "" {
  850. clusterID = defaultClusterID
  851. }
  852. dataMins := mins
  853. if len(result.Values) > 0 {
  854. dataMins = result.Values[0].Value
  855. } else {
  856. log.Warnf("Cluster cost data count returned no results for cluster %s", clusterID)
  857. }
  858. dataMinsByCluster[clusterID] = dataMins
  859. }
  860. // Determine combined discount
  861. discount, customDiscount := 0.0, 0.0
  862. c, err := a.CloudProvider.GetConfig()
  863. if err == nil {
  864. discount, err = ParsePercentString(c.Discount)
  865. if err != nil {
  866. discount = 0.0
  867. }
  868. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  869. if err != nil {
  870. customDiscount = 0.0
  871. }
  872. }
  873. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  874. costData := make(map[string]map[string]float64)
  875. // Helper function to iterate over Prom query results, parsing the raw values into
  876. // the intermediate costData structure.
  877. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  878. for _, result := range results {
  879. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  880. if clusterID == "" {
  881. clusterID = defaultClusterID
  882. }
  883. if _, ok := costData[clusterID]; !ok {
  884. costData[clusterID] = map[string]float64{}
  885. }
  886. if len(result.Values) > 0 {
  887. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  888. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  889. }
  890. }
  891. }
  892. // Apply both sustained use and custom discounts to RAM and CPU
  893. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  894. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  895. // Apply only custom discount to GPU and storage
  896. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  897. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  898. if queryTotalLocalStorage != "" {
  899. resTotalLocalStorage, err := resChs[5].Await()
  900. if err != nil {
  901. return nil, err
  902. }
  903. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  904. }
  905. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  906. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  907. pvUsedCostMap := map[string]float64{}
  908. if withBreakdown {
  909. resCPUModePct, _ := resChs[6].Await()
  910. resRAMSystemPct, _ := resChs[7].Await()
  911. resRAMUserPct, _ := resChs[8].Await()
  912. if ctx.HasErrors() {
  913. return nil, ctx.ErrorCollection()
  914. }
  915. for _, result := range resCPUModePct {
  916. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  917. if clusterID == "" {
  918. clusterID = defaultClusterID
  919. }
  920. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  921. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  922. }
  923. cpuBD := cpuBreakdownMap[clusterID]
  924. mode, err := result.GetString("mode")
  925. if err != nil {
  926. log.Warnf("ComputeClusterCosts: unable to read CPU mode: %s", err)
  927. mode = "other"
  928. }
  929. switch mode {
  930. case "idle":
  931. cpuBD.Idle += result.Values[0].Value
  932. case "system":
  933. cpuBD.System += result.Values[0].Value
  934. case "user":
  935. cpuBD.User += result.Values[0].Value
  936. default:
  937. cpuBD.Other += result.Values[0].Value
  938. }
  939. }
  940. for _, result := range resRAMSystemPct {
  941. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  942. if clusterID == "" {
  943. clusterID = defaultClusterID
  944. }
  945. if _, ok := ramBreakdownMap[clusterID]; !ok {
  946. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  947. }
  948. ramBD := ramBreakdownMap[clusterID]
  949. ramBD.System += result.Values[0].Value
  950. }
  951. for _, result := range resRAMUserPct {
  952. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  953. if clusterID == "" {
  954. clusterID = defaultClusterID
  955. }
  956. if _, ok := ramBreakdownMap[clusterID]; !ok {
  957. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  958. }
  959. ramBD := ramBreakdownMap[clusterID]
  960. ramBD.User += result.Values[0].Value
  961. }
  962. for _, ramBD := range ramBreakdownMap {
  963. remaining := 1.0
  964. remaining -= ramBD.Other
  965. remaining -= ramBD.System
  966. remaining -= ramBD.User
  967. ramBD.Idle = remaining
  968. }
  969. if queryUsedLocalStorage != "" {
  970. resUsedLocalStorage, err := resChs[9].Await()
  971. if err != nil {
  972. return nil, err
  973. }
  974. for _, result := range resUsedLocalStorage {
  975. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  976. if clusterID == "" {
  977. clusterID = defaultClusterID
  978. }
  979. pvUsedCostMap[clusterID] += result.Values[0].Value
  980. }
  981. }
  982. }
  983. if ctx.HasErrors() {
  984. for _, err := range ctx.Errors() {
  985. log.Errorf("ComputeClusterCosts: %s", err)
  986. }
  987. return nil, ctx.ErrorCollection()
  988. }
  989. // Convert intermediate structure to Costs instances
  990. costsByCluster := map[string]*ClusterCosts{}
  991. for id, cd := range costData {
  992. dataMins, ok := dataMinsByCluster[id]
  993. if !ok {
  994. dataMins = mins
  995. log.Warnf("Cluster cost data count not found for cluster %s", id)
  996. }
  997. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/timeutil.MinsPerHour)
  998. if err != nil {
  999. log.Warnf("Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  1000. return nil, err
  1001. }
  1002. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  1003. costs.CPUBreakdown = cpuBD
  1004. }
  1005. if ramBD, ok := ramBreakdownMap[id]; ok {
  1006. costs.RAMBreakdown = ramBD
  1007. }
  1008. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  1009. if pvUC, ok := pvUsedCostMap[id]; ok {
  1010. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  1011. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  1012. }
  1013. costs.DataMinutes = dataMins
  1014. costsByCluster[id] = costs
  1015. }
  1016. return costsByCluster, nil
  1017. }
  1018. type Totals struct {
  1019. TotalCost [][]string `json:"totalcost"`
  1020. CPUCost [][]string `json:"cpucost"`
  1021. MemCost [][]string `json:"memcost"`
  1022. StorageCost [][]string `json:"storageCost"`
  1023. }
  1024. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  1025. if len(qrs) == 0 {
  1026. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  1027. }
  1028. result := qrs[0]
  1029. totals := [][]string{}
  1030. for _, value := range result.Values {
  1031. d0 := fmt.Sprintf("%f", value.Timestamp)
  1032. d1 := fmt.Sprintf("%f", value.Value)
  1033. toAppend := []string{
  1034. d0,
  1035. d1,
  1036. }
  1037. totals = append(totals, toAppend)
  1038. }
  1039. return totals, nil
  1040. }
  1041. // ClusterCostsOverTime gives the full cluster costs over time
  1042. func ClusterCostsOverTime(cli prometheus.Client, provider models.Provider, startString, endString string, window, offset time.Duration) (*Totals, error) {
  1043. localStorageQuery := provider.GetLocalStorageQuery(window, offset, true, false)
  1044. if localStorageQuery != "" {
  1045. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  1046. }
  1047. layout := "2006-01-02T15:04:05.000Z"
  1048. start, err := time.Parse(layout, startString)
  1049. if err != nil {
  1050. log.Errorf("Error parsing time %s. Error: %s", startString, err.Error())
  1051. return nil, err
  1052. }
  1053. end, err := time.Parse(layout, endString)
  1054. if err != nil {
  1055. log.Errorf("Error parsing time %s. Error: %s", endString, err.Error())
  1056. return nil, err
  1057. }
  1058. fmtWindow := timeutil.DurationString(window)
  1059. if fmtWindow == "" {
  1060. err := fmt.Errorf("window value invalid or missing")
  1061. log.Errorf("Error parsing time %v. Error: %s", window, err.Error())
  1062. return nil, err
  1063. }
  1064. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  1065. qCores := fmt.Sprintf(queryClusterCores, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1066. qRAM := fmt.Sprintf(queryClusterRAM, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1067. qStorage := fmt.Sprintf(queryStorage, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1068. qTotal := fmt.Sprintf(queryTotal, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1069. ctx := prom.NewNamedContext(cli, prom.ClusterContextName)
  1070. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  1071. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  1072. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  1073. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  1074. resultClusterCores, err := resChClusterCores.Await()
  1075. if err != nil {
  1076. return nil, err
  1077. }
  1078. resultClusterRAM, err := resChClusterRAM.Await()
  1079. if err != nil {
  1080. return nil, err
  1081. }
  1082. resultStorage, err := resChStorage.Await()
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. resultTotal, err := resChTotal.Await()
  1087. if err != nil {
  1088. return nil, err
  1089. }
  1090. coreTotal, err := resultToTotals(resultClusterCores)
  1091. if err != nil {
  1092. log.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  1093. return nil, err
  1094. }
  1095. ramTotal, err := resultToTotals(resultClusterRAM)
  1096. if err != nil {
  1097. log.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  1098. return nil, err
  1099. }
  1100. storageTotal, err := resultToTotals(resultStorage)
  1101. if err != nil {
  1102. log.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  1103. }
  1104. clusterTotal, err := resultToTotals(resultTotal)
  1105. if err != nil {
  1106. // If clusterTotal query failed, it's likely because there are no PVs, which
  1107. // causes the qTotal query to return no data. Instead, query only node costs.
  1108. // If that fails, return an error because something is actually wrong.
  1109. qNodes := fmt.Sprintf(queryNodes, env.GetPromClusterFilter(), env.GetPromClusterLabel(), localStorageQuery)
  1110. resultNodes, warnings, err := ctx.QueryRangeSync(qNodes, start, end, window)
  1111. for _, warning := range warnings {
  1112. log.Warnf(warning)
  1113. }
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. clusterTotal, err = resultToTotals(resultNodes)
  1118. if err != nil {
  1119. log.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  1120. return nil, err
  1121. }
  1122. }
  1123. return &Totals{
  1124. TotalCost: clusterTotal,
  1125. CPUCost: coreTotal,
  1126. MemCost: ramTotal,
  1127. StorageCost: storageTotal,
  1128. }, nil
  1129. }
  1130. func pvCosts(diskMap map[DiskIdentifier]*Disk, resolution time.Duration, resActiveMins, resPVSize, resPVCost, resPVUsedAvg, resPVUsedMax, resPVCInfo []*prom.QueryResult, cp models.Provider) {
  1131. for _, result := range resActiveMins {
  1132. cluster, err := result.GetString(env.GetPromClusterLabel())
  1133. if err != nil {
  1134. cluster = env.GetClusterID()
  1135. }
  1136. name, err := result.GetString("persistentvolume")
  1137. if err != nil {
  1138. log.Warnf("ClusterDisks: active mins missing pv name")
  1139. continue
  1140. }
  1141. if len(result.Values) == 0 {
  1142. continue
  1143. }
  1144. key := DiskIdentifier{cluster, name}
  1145. if _, ok := diskMap[key]; !ok {
  1146. diskMap[key] = &Disk{
  1147. Cluster: cluster,
  1148. Name: name,
  1149. Breakdown: &ClusterCostsBreakdown{},
  1150. }
  1151. }
  1152. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  1153. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  1154. mins := e.Sub(s).Minutes()
  1155. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  1156. diskMap[key].End = e
  1157. diskMap[key].Start = s
  1158. diskMap[key].Minutes = mins
  1159. }
  1160. for _, result := range resPVSize {
  1161. cluster, err := result.GetString(env.GetPromClusterLabel())
  1162. if err != nil {
  1163. cluster = env.GetClusterID()
  1164. }
  1165. name, err := result.GetString("persistentvolume")
  1166. if err != nil {
  1167. log.Warnf("ClusterDisks: PV size data missing persistentvolume")
  1168. continue
  1169. }
  1170. // TODO niko/assets storage class
  1171. bytes := result.Values[0].Value
  1172. key := DiskIdentifier{cluster, name}
  1173. if _, ok := diskMap[key]; !ok {
  1174. diskMap[key] = &Disk{
  1175. Cluster: cluster,
  1176. Name: name,
  1177. Breakdown: &ClusterCostsBreakdown{},
  1178. }
  1179. }
  1180. diskMap[key].Bytes = bytes
  1181. }
  1182. customPricingEnabled := provider.CustomPricesEnabled(cp)
  1183. customPricingConfig, err := cp.GetConfig()
  1184. if err != nil {
  1185. log.Warnf("ClusterDisks: failed to load custom pricing: %s", err)
  1186. }
  1187. for _, result := range resPVCost {
  1188. cluster, err := result.GetString(env.GetPromClusterLabel())
  1189. if err != nil {
  1190. cluster = env.GetClusterID()
  1191. }
  1192. name, err := result.GetString("persistentvolume")
  1193. if err != nil {
  1194. log.Warnf("ClusterDisks: PV cost data missing persistentvolume")
  1195. continue
  1196. }
  1197. // TODO niko/assets storage class
  1198. var cost float64
  1199. if customPricingEnabled && customPricingConfig != nil {
  1200. customPVCostStr := customPricingConfig.Storage
  1201. customPVCost, err := strconv.ParseFloat(customPVCostStr, 64)
  1202. if err != nil {
  1203. log.Warnf("ClusterDisks: error parsing custom PV price: %s", customPVCostStr)
  1204. }
  1205. cost = customPVCost
  1206. } else {
  1207. cost = result.Values[0].Value
  1208. }
  1209. key := DiskIdentifier{cluster, name}
  1210. if _, ok := diskMap[key]; !ok {
  1211. diskMap[key] = &Disk{
  1212. Cluster: cluster,
  1213. Name: name,
  1214. Breakdown: &ClusterCostsBreakdown{},
  1215. }
  1216. }
  1217. diskMap[key].Cost = cost * (diskMap[key].Bytes / 1024 / 1024 / 1024) * (diskMap[key].Minutes / 60)
  1218. providerID, _ := result.GetString("provider_id") // just put the providerID set up here, it's the simplest query.
  1219. if providerID != "" {
  1220. diskMap[key].ProviderID = provider.ParsePVID(providerID)
  1221. }
  1222. }
  1223. for _, result := range resPVUsedAvg {
  1224. cluster, err := result.GetString(env.GetPromClusterLabel())
  1225. if err != nil {
  1226. cluster = env.GetClusterID()
  1227. }
  1228. claimName, err := result.GetString("persistentvolumeclaim")
  1229. if err != nil {
  1230. log.Debugf("ClusterDisks: pv usage data missing persistentvolumeclaim")
  1231. continue
  1232. }
  1233. claimNamespace, err := result.GetString("namespace")
  1234. if err != nil {
  1235. log.Debugf("ClusterDisks: pv usage data missing namespace")
  1236. continue
  1237. }
  1238. var volumeName string
  1239. for _, thatRes := range resPVCInfo {
  1240. thatCluster, err := thatRes.GetString(env.GetPromClusterLabel())
  1241. if err != nil {
  1242. thatCluster = env.GetClusterID()
  1243. }
  1244. thatVolumeName, err := thatRes.GetString("volumename")
  1245. if err != nil {
  1246. log.Debugf("ClusterDisks: pv claim data missing volumename")
  1247. continue
  1248. }
  1249. thatClaimName, err := thatRes.GetString("persistentvolumeclaim")
  1250. if err != nil {
  1251. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  1252. continue
  1253. }
  1254. thatClaimNamespace, err := thatRes.GetString("namespace")
  1255. if err != nil {
  1256. log.Debugf("ClusterDisks: pv claim data missing namespace")
  1257. continue
  1258. }
  1259. if cluster == thatCluster && claimName == thatClaimName && claimNamespace == thatClaimNamespace {
  1260. volumeName = thatVolumeName
  1261. }
  1262. }
  1263. usage := result.Values[0].Value
  1264. key := DiskIdentifier{cluster, volumeName}
  1265. if _, ok := diskMap[key]; !ok {
  1266. diskMap[key] = &Disk{
  1267. Cluster: cluster,
  1268. Name: volumeName,
  1269. Breakdown: &ClusterCostsBreakdown{},
  1270. }
  1271. }
  1272. diskMap[key].BytesUsedAvgPtr = &usage
  1273. }
  1274. for _, result := range resPVUsedMax {
  1275. cluster, err := result.GetString(env.GetPromClusterLabel())
  1276. if err != nil {
  1277. cluster = env.GetClusterID()
  1278. }
  1279. claimName, err := result.GetString("persistentvolumeclaim")
  1280. if err != nil {
  1281. log.Debugf("ClusterDisks: pv usage data missing persistentvolumeclaim")
  1282. continue
  1283. }
  1284. claimNamespace, err := result.GetString("namespace")
  1285. if err != nil {
  1286. log.Debugf("ClusterDisks: pv usage data missing namespace")
  1287. continue
  1288. }
  1289. var volumeName string
  1290. for _, thatRes := range resPVCInfo {
  1291. thatCluster, err := thatRes.GetString(env.GetPromClusterLabel())
  1292. if err != nil {
  1293. thatCluster = env.GetClusterID()
  1294. }
  1295. thatVolumeName, err := thatRes.GetString("volumename")
  1296. if err != nil {
  1297. log.Debugf("ClusterDisks: pv claim data missing volumename")
  1298. continue
  1299. }
  1300. thatClaimName, err := thatRes.GetString("persistentvolumeclaim")
  1301. if err != nil {
  1302. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  1303. continue
  1304. }
  1305. thatClaimNamespace, err := thatRes.GetString("namespace")
  1306. if err != nil {
  1307. log.Debugf("ClusterDisks: pv claim data missing namespace")
  1308. continue
  1309. }
  1310. if cluster == thatCluster && claimName == thatClaimName && claimNamespace == thatClaimNamespace {
  1311. volumeName = thatVolumeName
  1312. }
  1313. }
  1314. usage := result.Values[0].Value
  1315. key := DiskIdentifier{cluster, volumeName}
  1316. if _, ok := diskMap[key]; !ok {
  1317. diskMap[key] = &Disk{
  1318. Cluster: cluster,
  1319. Name: volumeName,
  1320. Breakdown: &ClusterCostsBreakdown{},
  1321. }
  1322. }
  1323. diskMap[key].BytesUsedMaxPtr = &usage
  1324. }
  1325. }