cluster.go 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. package costmodel
  2. import (
  3. "fmt"
  4. "net"
  5. "strconv"
  6. "time"
  7. "github.com/opencost/opencost/pkg/cloud/provider"
  8. prometheus "github.com/prometheus/client_golang/api"
  9. "golang.org/x/exp/slices"
  10. "github.com/opencost/opencost/pkg/cloud/models"
  11. "github.com/opencost/opencost/pkg/env"
  12. "github.com/opencost/opencost/pkg/kubecost"
  13. "github.com/opencost/opencost/pkg/log"
  14. "github.com/opencost/opencost/pkg/prom"
  15. "github.com/opencost/opencost/pkg/util/timeutil"
  16. )
  17. const (
  18. queryClusterCores = `sum(
  19. 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 +
  20. avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, %s) * 730
  21. ) by (%s)`
  22. queryClusterRAM = `sum(
  23. 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
  24. ) by (%s)`
  25. queryStorage = `sum(
  26. avg(avg_over_time(pv_hourly_cost{%s}[%s] %s)) by (persistentvolume, %s) * 730
  27. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[%s] %s)) by (persistentvolume, %s) / 1024 / 1024 / 1024
  28. ) by (%s) %s`
  29. queryTotal = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 +
  30. sum(
  31. avg(avg_over_time(pv_hourly_cost{%s}[1h])) by (persistentvolume, %s) * 730
  32. * avg(avg_over_time(kube_persistentvolume_capacity_bytes{%s}[1h])) by (persistentvolume, %s) / 1024 / 1024 / 1024
  33. ) by (%s) %s`
  34. queryNodes = `sum(avg(node_total_hourly_cost{%s}) by (node, %s)) * 730 %s`
  35. )
  36. const maxLocalDiskSize = 200 // AWS limits root disks to 100 Gi, and occasional metric errors in filesystem size should not contribute to large costs.
  37. // Costs represents cumulative and monthly cluster costs over a given duration. Costs
  38. // are broken down by cores, memory, and storage.
  39. type ClusterCosts struct {
  40. Start *time.Time `json:"startTime"`
  41. End *time.Time `json:"endTime"`
  42. CPUCumulative float64 `json:"cpuCumulativeCost"`
  43. CPUMonthly float64 `json:"cpuMonthlyCost"`
  44. CPUBreakdown *ClusterCostsBreakdown `json:"cpuBreakdown"`
  45. GPUCumulative float64 `json:"gpuCumulativeCost"`
  46. GPUMonthly float64 `json:"gpuMonthlyCost"`
  47. RAMCumulative float64 `json:"ramCumulativeCost"`
  48. RAMMonthly float64 `json:"ramMonthlyCost"`
  49. RAMBreakdown *ClusterCostsBreakdown `json:"ramBreakdown"`
  50. StorageCumulative float64 `json:"storageCumulativeCost"`
  51. StorageMonthly float64 `json:"storageMonthlyCost"`
  52. StorageBreakdown *ClusterCostsBreakdown `json:"storageBreakdown"`
  53. TotalCumulative float64 `json:"totalCumulativeCost"`
  54. TotalMonthly float64 `json:"totalMonthlyCost"`
  55. DataMinutes float64
  56. }
  57. // ClusterCostsBreakdown provides percentage-based breakdown of a resource by
  58. // categories: user for user-space (i.e. non-system) usage, system, and idle.
  59. type ClusterCostsBreakdown struct {
  60. Idle float64 `json:"idle"`
  61. Other float64 `json:"other"`
  62. System float64 `json:"system"`
  63. User float64 `json:"user"`
  64. }
  65. // NewClusterCostsFromCumulative takes cumulative cost data over a given time range, computes
  66. // the associated monthly rate data, and returns the Costs.
  67. func NewClusterCostsFromCumulative(cpu, gpu, ram, storage float64, window, offset time.Duration, dataHours float64) (*ClusterCosts, error) {
  68. start, end := timeutil.ParseTimeRange(window, offset)
  69. // If the number of hours is not given (i.e. is zero) compute one from the window and offset
  70. if dataHours == 0 {
  71. dataHours = end.Sub(start).Hours()
  72. }
  73. // Do not allow zero-length windows to prevent divide-by-zero issues
  74. if dataHours == 0 {
  75. return nil, fmt.Errorf("illegal time range: window %s, offset %s", window, offset)
  76. }
  77. cc := &ClusterCosts{
  78. Start: &start,
  79. End: &end,
  80. CPUCumulative: cpu,
  81. GPUCumulative: gpu,
  82. RAMCumulative: ram,
  83. StorageCumulative: storage,
  84. TotalCumulative: cpu + gpu + ram + storage,
  85. CPUMonthly: cpu / dataHours * (timeutil.HoursPerMonth),
  86. GPUMonthly: gpu / dataHours * (timeutil.HoursPerMonth),
  87. RAMMonthly: ram / dataHours * (timeutil.HoursPerMonth),
  88. StorageMonthly: storage / dataHours * (timeutil.HoursPerMonth),
  89. }
  90. cc.TotalMonthly = cc.CPUMonthly + cc.GPUMonthly + cc.RAMMonthly + cc.StorageMonthly
  91. return cc, nil
  92. }
  93. type Disk struct {
  94. Cluster string
  95. Name string
  96. ProviderID string
  97. StorageClass string
  98. VolumeName string
  99. ClaimName string
  100. ClaimNamespace string
  101. Cost float64
  102. Bytes float64
  103. // These two fields may not be available at all times because they rely on
  104. // a new set of metrics that may or may not be available. Thus, they must
  105. // be nilable to represent the complete absence of the data.
  106. //
  107. // In other words, nilability here lets us distinguish between
  108. // "metric is not available" and "metric is available but is 0".
  109. //
  110. // They end in "Ptr" to distinguish from an earlier version in order to
  111. // ensure that all usages are checked for nil.
  112. BytesUsedAvgPtr *float64
  113. BytesUsedMaxPtr *float64
  114. Local bool
  115. Start time.Time
  116. End time.Time
  117. Minutes float64
  118. Breakdown *ClusterCostsBreakdown
  119. }
  120. type DiskIdentifier struct {
  121. Cluster string
  122. Name string
  123. }
  124. func ClusterDisks(client prometheus.Client, provider models.Provider, start, end time.Time) (map[DiskIdentifier]*Disk, error) {
  125. // Start from the time "end", querying backwards
  126. t := end
  127. // minsPerResolution determines accuracy and resource use for the following
  128. // queries. Smaller values (higher resolution) result in better accuracy,
  129. // but more expensive queries, and vice-a-versa.
  130. resolution := env.GetETLResolution()
  131. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  132. var minsPerResolution int
  133. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  134. minsPerResolution = 1
  135. log.DedupedWarningf(3, "ClusterDisks(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  136. }
  137. durStr := timeutil.DurationString(end.Sub(start))
  138. if durStr == "" {
  139. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  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. // Start from the time "end", querying backwards
  476. t := end
  477. // minsPerResolution determines accuracy and resource use for the following
  478. // queries. Smaller values (higher resolution) result in better accuracy,
  479. // but more expensive queries, and vice-a-versa.
  480. resolution := env.GetETLResolution()
  481. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  482. var minsPerResolution int
  483. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  484. minsPerResolution = 1
  485. log.DedupedWarningf(3, "ClusterNodes(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  486. }
  487. durStr := timeutil.DurationString(end.Sub(start))
  488. if durStr == "" {
  489. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  490. }
  491. requiredCtx := prom.NewNamedContext(client, prom.ClusterContextName)
  492. optionalCtx := prom.NewNamedContext(client, prom.ClusterOptionalContextName)
  493. 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())
  494. queryNodeCPUCoresCapacity := fmt.Sprintf(`avg(avg_over_time(kube_node_status_capacity_cpu_cores{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  495. queryNodeCPUCoresAllocatable := fmt.Sprintf(`avg(avg_over_time(kube_node_status_allocatable_cpu_cores{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  496. 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())
  497. queryNodeRAMBytesCapacity := fmt.Sprintf(`avg(avg_over_time(kube_node_status_capacity_memory_bytes{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  498. queryNodeRAMBytesAllocatable := fmt.Sprintf(`avg(avg_over_time(kube_node_status_allocatable_memory_bytes{%s}[%s])) by (%s, node)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  499. queryNodeGPUCount := fmt.Sprintf(`avg(avg_over_time(node_gpu_count{%s}[%s])) by (%s, node, provider_id)`, env.GetPromClusterFilter(), durStr, env.GetPromClusterLabel())
  500. 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())
  501. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total{%s}[%s:%dm])) by (kubernetes_node, %s, mode)`, env.GetPromClusterFilter(), durStr, minsPerResolution, env.GetPromClusterLabel())
  502. 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())
  503. 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())
  504. queryActiveMins := fmt.Sprintf(`avg(node_total_hourly_cost{%s}) by (node, %s, provider_id)[%s:%dm]`, env.GetPromClusterFilter(), env.GetPromClusterLabel(), durStr, minsPerResolution)
  505. queryIsSpot := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot{%s}[%s:%dm])`, env.GetPromClusterFilter(), durStr, minsPerResolution)
  506. queryLabels := fmt.Sprintf(`count_over_time(kube_node_labels{%s}[%s:%dm])`, env.GetPromClusterFilter(), durStr, minsPerResolution)
  507. // Return errors if these fail
  508. resChNodeCPUHourlyCost := requiredCtx.QueryAtTime(queryNodeCPUHourlyCost, t)
  509. resChNodeCPUCoresCapacity := requiredCtx.QueryAtTime(queryNodeCPUCoresCapacity, t)
  510. resChNodeCPUCoresAllocatable := requiredCtx.QueryAtTime(queryNodeCPUCoresAllocatable, t)
  511. resChNodeRAMHourlyCost := requiredCtx.QueryAtTime(queryNodeRAMHourlyCost, t)
  512. resChNodeRAMBytesCapacity := requiredCtx.QueryAtTime(queryNodeRAMBytesCapacity, t)
  513. resChNodeRAMBytesAllocatable := requiredCtx.QueryAtTime(queryNodeRAMBytesAllocatable, t)
  514. resChNodeGPUCount := requiredCtx.QueryAtTime(queryNodeGPUCount, t)
  515. resChNodeGPUHourlyCost := requiredCtx.QueryAtTime(queryNodeGPUHourlyCost, t)
  516. resChActiveMins := requiredCtx.QueryAtTime(queryActiveMins, t)
  517. resChIsSpot := requiredCtx.QueryAtTime(queryIsSpot, t)
  518. // Do not return errors if these fail, but log warnings
  519. resChNodeCPUModeTotal := optionalCtx.QueryAtTime(queryNodeCPUModeTotal, t)
  520. resChNodeRAMSystemPct := optionalCtx.QueryAtTime(queryNodeRAMSystemPct, t)
  521. resChNodeRAMUserPct := optionalCtx.QueryAtTime(queryNodeRAMUserPct, t)
  522. resChLabels := optionalCtx.QueryAtTime(queryLabels, t)
  523. resNodeCPUHourlyCost, _ := resChNodeCPUHourlyCost.Await()
  524. resNodeCPUCoresCapacity, _ := resChNodeCPUCoresCapacity.Await()
  525. resNodeCPUCoresAllocatable, _ := resChNodeCPUCoresAllocatable.Await()
  526. resNodeGPUCount, _ := resChNodeGPUCount.Await()
  527. resNodeGPUHourlyCost, _ := resChNodeGPUHourlyCost.Await()
  528. resNodeRAMHourlyCost, _ := resChNodeRAMHourlyCost.Await()
  529. resNodeRAMBytesCapacity, _ := resChNodeRAMBytesCapacity.Await()
  530. resNodeRAMBytesAllocatable, _ := resChNodeRAMBytesAllocatable.Await()
  531. resIsSpot, _ := resChIsSpot.Await()
  532. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  533. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  534. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  535. resActiveMins, _ := resChActiveMins.Await()
  536. resLabels, _ := resChLabels.Await()
  537. if optionalCtx.HasErrors() {
  538. for _, err := range optionalCtx.Errors() {
  539. log.Warnf("ClusterNodes: %s", err)
  540. }
  541. }
  542. if requiredCtx.HasErrors() {
  543. for _, err := range requiredCtx.Errors() {
  544. log.Errorf("ClusterNodes: %s", err)
  545. }
  546. return nil, requiredCtx.ErrorCollection()
  547. }
  548. activeDataMap := buildActiveDataMap(resActiveMins, resolution)
  549. gpuCountMap := buildGPUCountMap(resNodeGPUCount)
  550. preemptibleMap := buildPreemptibleMap(resIsSpot)
  551. cpuCostMap, clusterAndNameToType1 := buildCPUCostMap(resNodeCPUHourlyCost, cp, preemptibleMap)
  552. ramCostMap, clusterAndNameToType2 := buildRAMCostMap(resNodeRAMHourlyCost, cp, preemptibleMap)
  553. gpuCostMap, clusterAndNameToType3 := buildGPUCostMap(resNodeGPUHourlyCost, gpuCountMap, cp, preemptibleMap)
  554. clusterAndNameToTypeIntermediate := mergeTypeMaps(clusterAndNameToType1, clusterAndNameToType2)
  555. clusterAndNameToType := mergeTypeMaps(clusterAndNameToTypeIntermediate, clusterAndNameToType3)
  556. cpuCoresCapacityMap := buildCPUCoresMap(resNodeCPUCoresCapacity)
  557. ramBytesCapacityMap := buildRAMBytesMap(resNodeRAMBytesCapacity)
  558. cpuCoresAllocatableMap := buildCPUCoresMap(resNodeCPUCoresAllocatable)
  559. ramBytesAllocatableMap := buildRAMBytesMap(resNodeRAMBytesAllocatable)
  560. overheadMap := buildOverheadMap(ramBytesCapacityMap, ramBytesAllocatableMap, cpuCoresCapacityMap, cpuCoresAllocatableMap)
  561. ramUserPctMap := buildRAMUserPctMap(resNodeRAMUserPct)
  562. ramSystemPctMap := buildRAMSystemPctMap(resNodeRAMSystemPct)
  563. cpuBreakdownMap := buildCPUBreakdownMap(resNodeCPUModeTotal)
  564. labelsMap := buildLabelsMap(resLabels)
  565. costTimesMinuteAndCount(activeDataMap, cpuCostMap, cpuCoresCapacityMap)
  566. costTimesMinuteAndCount(activeDataMap, ramCostMap, ramBytesCapacityMap)
  567. costTimesMinute(activeDataMap, gpuCostMap) // there's no need to do a weird "nodeIdentifierNoProviderID" type match since gpuCounts have a providerID
  568. nodeMap := buildNodeMap(
  569. cpuCostMap, ramCostMap, gpuCostMap, gpuCountMap,
  570. cpuCoresCapacityMap, ramBytesCapacityMap, ramUserPctMap,
  571. ramSystemPctMap,
  572. cpuBreakdownMap,
  573. activeDataMap,
  574. preemptibleMap,
  575. labelsMap,
  576. clusterAndNameToType,
  577. resolution,
  578. overheadMap,
  579. )
  580. c, err := cp.GetConfig()
  581. if err != nil {
  582. return nil, err
  583. }
  584. discount, err := ParsePercentString(c.Discount)
  585. if err != nil {
  586. return nil, err
  587. }
  588. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  589. if err != nil {
  590. return nil, err
  591. }
  592. for _, node := range nodeMap {
  593. // TODO take GKE Reserved Instances into account
  594. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  595. // Apply all remaining resources to Idle
  596. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  597. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  598. }
  599. return nodeMap, nil
  600. }
  601. type LoadBalancerIdentifier struct {
  602. Cluster string
  603. Namespace string
  604. Name string
  605. }
  606. type LoadBalancer struct {
  607. Cluster string
  608. Namespace string
  609. Name string
  610. ProviderID string
  611. Cost float64
  612. Start time.Time
  613. End time.Time
  614. Minutes float64
  615. Private bool
  616. }
  617. func ClusterLoadBalancers(client prometheus.Client, start, end time.Time) (map[LoadBalancerIdentifier]*LoadBalancer, error) {
  618. // Start from the time "end", querying backwards
  619. t := end
  620. // minsPerResolution determines accuracy and resource use for the following
  621. // queries. Smaller values (higher resolution) result in better accuracy,
  622. // but more expensive queries, and vice-a-versa.
  623. resolution := env.GetETLResolution()
  624. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  625. var minsPerResolution int
  626. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) == 0 {
  627. minsPerResolution = 1
  628. log.DedupedWarningf(3, "ClusterLoadBalancers(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  629. }
  630. // Query for the duration between start and end
  631. durStr := timeutil.DurationString(end.Sub(start))
  632. if durStr == "" {
  633. return nil, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  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. providerID, err := result.GetString("ingress_ip")
  712. if err != nil {
  713. log.DedupedWarningf(5, "ClusterLoadBalancers: LB cost data missing ingress_ip")
  714. // only update asset cost when an actual IP was returned
  715. continue
  716. }
  717. key := LoadBalancerIdentifier{
  718. Cluster: cluster,
  719. Namespace: namespace,
  720. Name: name,
  721. }
  722. // Apply cost as price-per-hour * hours
  723. if lb, ok := loadBalancerMap[key]; ok {
  724. lbPricePerHr := result.Values[0].Value
  725. // interpolate any missing data
  726. resultMins := lb.Minutes
  727. scaleFactor := (resultMins + resolution.Minutes()) / resultMins
  728. hrs := (lb.Minutes * scaleFactor) / 60.0
  729. lb.Cost += lbPricePerHr * hrs
  730. lb.Private = privateIPCheck(providerID)
  731. } else {
  732. log.DedupedWarningf(20, "ClusterLoadBalancers: found minutes for key that does not exist: %v", key)
  733. }
  734. }
  735. return loadBalancerMap, nil
  736. }
  737. // Check if an ip is private.
  738. func privateIPCheck(ip string) bool {
  739. ipAddress := net.ParseIP(ip)
  740. return ipAddress.IsPrivate()
  741. }
  742. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  743. func (a *Accesses) ComputeClusterCosts(client prometheus.Client, provider models.Provider, window, offset time.Duration, withBreakdown bool) (map[string]*ClusterCosts, error) {
  744. if window < 10*time.Minute {
  745. return nil, fmt.Errorf("minimum window of 10m required; got %s", window)
  746. }
  747. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  748. start, end := timeutil.ParseTimeRange(window, offset)
  749. mins := end.Sub(start).Minutes()
  750. // minsPerResolution determines accuracy and resource use for the following
  751. // queries. Smaller values (higher resolution) result in better accuracy,
  752. // but more expensive queries, and vice-a-versa.
  753. resolution := env.GetETLResolution()
  754. //Ensuring if ETL_RESOLUTION_SECONDS is less than 60s default it to 1m
  755. var minsPerResolution int
  756. if minsPerResolution = int(resolution.Minutes()); int(resolution.Minutes()) < 1 {
  757. minsPerResolution = 1
  758. log.DedupedWarningf(3, "ComputeClusterCosts(): Configured ETL resolution (%d seconds) is below the 60 seconds threshold. Overriding with 1 minute.", int(resolution.Seconds()))
  759. }
  760. windowStr := timeutil.DurationString(window)
  761. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  762. // value, converts it to a cumulative value; i.e.
  763. // [$/hr] * [min/res]*[hr/min] = [$/res]
  764. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  765. const fmtQueryDataCount = `
  766. count_over_time(sum(kube_node_status_capacity_cpu_cores{%s}) by (%s)[%s:%dm]%s) * %d
  767. `
  768. const fmtQueryTotalGPU = `
  769. sum(
  770. sum_over_time(node_gpu_hourly_cost{%s}[%s:%dm]%s) * %f
  771. ) by (%s)
  772. `
  773. const fmtQueryTotalCPU = `
  774. sum(
  775. sum_over_time(avg(kube_node_status_capacity_cpu_cores{%s}) by (node, %s)[%s:%dm]%s) *
  776. avg(avg_over_time(node_cpu_hourly_cost{%s}[%s:%dm]%s)) by (node, %s) * %f
  777. ) by (%s)
  778. `
  779. const fmtQueryTotalRAM = `
  780. sum(
  781. sum_over_time(avg(kube_node_status_capacity_memory_bytes{%s}) by (node, %s)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  782. avg(avg_over_time(node_ram_hourly_cost{%s}[%s:%dm]%s)) by (node, %s) * %f
  783. ) by (%s)
  784. `
  785. const fmtQueryTotalStorage = `
  786. sum(
  787. sum_over_time(avg(kube_persistentvolume_capacity_bytes{%s}) by (persistentvolume, %s)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  788. avg(avg_over_time(pv_hourly_cost{%s}[%s:%dm]%s)) by (persistentvolume, %s) * %f
  789. ) by (%s)
  790. `
  791. const fmtQueryCPUModePct = `
  792. sum(rate(node_cpu_seconds_total{%s}[%s]%s)) by (%s, mode) / ignoring(mode)
  793. group_left sum(rate(node_cpu_seconds_total{%s}[%s]%s)) by (%s)
  794. `
  795. const fmtQueryRAMSystemPct = `
  796. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system", %s}[%s:%dm]%s)) by (%s)
  797. / sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm]%s)) by (%s)
  798. `
  799. const fmtQueryRAMUserPct = `
  800. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes{%s}[%s:%dm]%s)) by (%s)
  801. / sum(sum_over_time(kube_node_status_capacity_memory_bytes{%s}[%s:%dm]%s)) by (%s)
  802. `
  803. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  804. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  805. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  806. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  807. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  808. if queryTotalLocalStorage != "" {
  809. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  810. }
  811. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  812. queryDataCount := fmt.Sprintf(fmtQueryDataCount, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, minsPerResolution)
  813. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, hourlyToCumulative, env.GetPromClusterLabel())
  814. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  815. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  816. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, env.GetPromClusterFilter(), env.GetPromClusterLabel(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), hourlyToCumulative, env.GetPromClusterLabel())
  817. ctx := prom.NewNamedContext(client, prom.ClusterContextName)
  818. resChs := ctx.QueryAll(
  819. queryDataCount,
  820. queryTotalGPU,
  821. queryTotalCPU,
  822. queryTotalRAM,
  823. queryTotalStorage,
  824. )
  825. // Only submit the local storage query if it is valid. Otherwise Prometheus
  826. // will return errors. Always append something to resChs, regardless, to
  827. // maintain indexing.
  828. if queryTotalLocalStorage != "" {
  829. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  830. } else {
  831. resChs = append(resChs, nil)
  832. }
  833. if withBreakdown {
  834. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, fmtOffset, env.GetPromClusterLabel())
  835. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel())
  836. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), windowStr, minsPerResolution, fmtOffset, env.GetPromClusterLabel())
  837. bdResChs := ctx.QueryAll(
  838. queryCPUModePct,
  839. queryRAMSystemPct,
  840. queryRAMUserPct,
  841. )
  842. // Only submit the local storage query if it is valid. Otherwise Prometheus
  843. // will return errors. Always append something to resChs, regardless, to
  844. // maintain indexing.
  845. if queryUsedLocalStorage != "" {
  846. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  847. } else {
  848. bdResChs = append(bdResChs, nil)
  849. }
  850. resChs = append(resChs, bdResChs...)
  851. }
  852. resDataCount, _ := resChs[0].Await()
  853. resTotalGPU, _ := resChs[1].Await()
  854. resTotalCPU, _ := resChs[2].Await()
  855. resTotalRAM, _ := resChs[3].Await()
  856. resTotalStorage, _ := resChs[4].Await()
  857. if ctx.HasErrors() {
  858. return nil, ctx.ErrorCollection()
  859. }
  860. defaultClusterID := env.GetClusterID()
  861. dataMinsByCluster := map[string]float64{}
  862. for _, result := range resDataCount {
  863. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  864. if clusterID == "" {
  865. clusterID = defaultClusterID
  866. }
  867. dataMins := mins
  868. if len(result.Values) > 0 {
  869. dataMins = result.Values[0].Value
  870. } else {
  871. log.Warnf("Cluster cost data count returned no results for cluster %s", clusterID)
  872. }
  873. dataMinsByCluster[clusterID] = dataMins
  874. }
  875. // Determine combined discount
  876. discount, customDiscount := 0.0, 0.0
  877. c, err := a.CloudProvider.GetConfig()
  878. if err == nil {
  879. discount, err = ParsePercentString(c.Discount)
  880. if err != nil {
  881. discount = 0.0
  882. }
  883. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  884. if err != nil {
  885. customDiscount = 0.0
  886. }
  887. }
  888. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  889. costData := make(map[string]map[string]float64)
  890. // Helper function to iterate over Prom query results, parsing the raw values into
  891. // the intermediate costData structure.
  892. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  893. for _, result := range results {
  894. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  895. if clusterID == "" {
  896. clusterID = defaultClusterID
  897. }
  898. if _, ok := costData[clusterID]; !ok {
  899. costData[clusterID] = map[string]float64{}
  900. }
  901. if len(result.Values) > 0 {
  902. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  903. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  904. }
  905. }
  906. }
  907. // Apply both sustained use and custom discounts to RAM and CPU
  908. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  909. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  910. // Apply only custom discount to GPU and storage
  911. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  912. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  913. if queryTotalLocalStorage != "" {
  914. resTotalLocalStorage, err := resChs[5].Await()
  915. if err != nil {
  916. return nil, err
  917. }
  918. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  919. }
  920. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  921. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  922. pvUsedCostMap := map[string]float64{}
  923. if withBreakdown {
  924. resCPUModePct, _ := resChs[6].Await()
  925. resRAMSystemPct, _ := resChs[7].Await()
  926. resRAMUserPct, _ := resChs[8].Await()
  927. if ctx.HasErrors() {
  928. return nil, ctx.ErrorCollection()
  929. }
  930. for _, result := range resCPUModePct {
  931. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  932. if clusterID == "" {
  933. clusterID = defaultClusterID
  934. }
  935. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  936. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  937. }
  938. cpuBD := cpuBreakdownMap[clusterID]
  939. mode, err := result.GetString("mode")
  940. if err != nil {
  941. log.Warnf("ComputeClusterCosts: unable to read CPU mode: %s", err)
  942. mode = "other"
  943. }
  944. switch mode {
  945. case "idle":
  946. cpuBD.Idle += result.Values[0].Value
  947. case "system":
  948. cpuBD.System += result.Values[0].Value
  949. case "user":
  950. cpuBD.User += result.Values[0].Value
  951. default:
  952. cpuBD.Other += result.Values[0].Value
  953. }
  954. }
  955. for _, result := range resRAMSystemPct {
  956. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  957. if clusterID == "" {
  958. clusterID = defaultClusterID
  959. }
  960. if _, ok := ramBreakdownMap[clusterID]; !ok {
  961. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  962. }
  963. ramBD := ramBreakdownMap[clusterID]
  964. ramBD.System += result.Values[0].Value
  965. }
  966. for _, result := range resRAMUserPct {
  967. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  968. if clusterID == "" {
  969. clusterID = defaultClusterID
  970. }
  971. if _, ok := ramBreakdownMap[clusterID]; !ok {
  972. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  973. }
  974. ramBD := ramBreakdownMap[clusterID]
  975. ramBD.User += result.Values[0].Value
  976. }
  977. for _, ramBD := range ramBreakdownMap {
  978. remaining := 1.0
  979. remaining -= ramBD.Other
  980. remaining -= ramBD.System
  981. remaining -= ramBD.User
  982. ramBD.Idle = remaining
  983. }
  984. if queryUsedLocalStorage != "" {
  985. resUsedLocalStorage, err := resChs[9].Await()
  986. if err != nil {
  987. return nil, err
  988. }
  989. for _, result := range resUsedLocalStorage {
  990. clusterID, _ := result.GetString(env.GetPromClusterLabel())
  991. if clusterID == "" {
  992. clusterID = defaultClusterID
  993. }
  994. pvUsedCostMap[clusterID] += result.Values[0].Value
  995. }
  996. }
  997. }
  998. if ctx.HasErrors() {
  999. for _, err := range ctx.Errors() {
  1000. log.Errorf("ComputeClusterCosts: %s", err)
  1001. }
  1002. return nil, ctx.ErrorCollection()
  1003. }
  1004. // Convert intermediate structure to Costs instances
  1005. costsByCluster := map[string]*ClusterCosts{}
  1006. for id, cd := range costData {
  1007. dataMins, ok := dataMinsByCluster[id]
  1008. if !ok {
  1009. dataMins = mins
  1010. log.Warnf("Cluster cost data count not found for cluster %s", id)
  1011. }
  1012. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/timeutil.MinsPerHour)
  1013. if err != nil {
  1014. log.Warnf("Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  1015. return nil, err
  1016. }
  1017. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  1018. costs.CPUBreakdown = cpuBD
  1019. }
  1020. if ramBD, ok := ramBreakdownMap[id]; ok {
  1021. costs.RAMBreakdown = ramBD
  1022. }
  1023. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  1024. if pvUC, ok := pvUsedCostMap[id]; ok {
  1025. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  1026. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  1027. }
  1028. costs.DataMinutes = dataMins
  1029. costsByCluster[id] = costs
  1030. }
  1031. return costsByCluster, nil
  1032. }
  1033. type Totals struct {
  1034. TotalCost [][]string `json:"totalcost"`
  1035. CPUCost [][]string `json:"cpucost"`
  1036. MemCost [][]string `json:"memcost"`
  1037. StorageCost [][]string `json:"storageCost"`
  1038. }
  1039. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  1040. if len(qrs) == 0 {
  1041. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  1042. }
  1043. result := qrs[0]
  1044. totals := [][]string{}
  1045. for _, value := range result.Values {
  1046. d0 := fmt.Sprintf("%f", value.Timestamp)
  1047. d1 := fmt.Sprintf("%f", value.Value)
  1048. toAppend := []string{
  1049. d0,
  1050. d1,
  1051. }
  1052. totals = append(totals, toAppend)
  1053. }
  1054. return totals, nil
  1055. }
  1056. // ClusterCostsOverTime gives the full cluster costs over time
  1057. func ClusterCostsOverTime(cli prometheus.Client, provider models.Provider, startString, endString string, window, offset time.Duration) (*Totals, error) {
  1058. localStorageQuery := provider.GetLocalStorageQuery(window, offset, true, false)
  1059. if localStorageQuery != "" {
  1060. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  1061. }
  1062. layout := "2006-01-02T15:04:05.000Z"
  1063. start, err := time.Parse(layout, startString)
  1064. if err != nil {
  1065. log.Errorf("Error parsing time %s. Error: %s", startString, err.Error())
  1066. return nil, err
  1067. }
  1068. end, err := time.Parse(layout, endString)
  1069. if err != nil {
  1070. log.Errorf("Error parsing time %s. Error: %s", endString, err.Error())
  1071. return nil, err
  1072. }
  1073. fmtWindow := timeutil.DurationString(window)
  1074. if fmtWindow == "" {
  1075. err := fmt.Errorf("window value invalid or missing")
  1076. log.Errorf("Error parsing time %v. Error: %s", window, err.Error())
  1077. return nil, err
  1078. }
  1079. fmtOffset := timeutil.DurationToPromOffsetString(offset)
  1080. qCores := fmt.Sprintf(queryClusterCores, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1081. qRAM := fmt.Sprintf(queryClusterRAM, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel())
  1082. qStorage := fmt.Sprintf(queryStorage, env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterFilter(), fmtWindow, fmtOffset, env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1083. qTotal := fmt.Sprintf(queryTotal, env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterFilter(), env.GetPromClusterLabel(), env.GetPromClusterLabel(), localStorageQuery)
  1084. ctx := prom.NewNamedContext(cli, prom.ClusterContextName)
  1085. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  1086. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  1087. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  1088. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  1089. resultClusterCores, err := resChClusterCores.Await()
  1090. if err != nil {
  1091. return nil, err
  1092. }
  1093. resultClusterRAM, err := resChClusterRAM.Await()
  1094. if err != nil {
  1095. return nil, err
  1096. }
  1097. resultStorage, err := resChStorage.Await()
  1098. if err != nil {
  1099. return nil, err
  1100. }
  1101. resultTotal, err := resChTotal.Await()
  1102. if err != nil {
  1103. return nil, err
  1104. }
  1105. coreTotal, err := resultToTotals(resultClusterCores)
  1106. if err != nil {
  1107. log.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  1108. return nil, err
  1109. }
  1110. ramTotal, err := resultToTotals(resultClusterRAM)
  1111. if err != nil {
  1112. log.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  1113. return nil, err
  1114. }
  1115. storageTotal, err := resultToTotals(resultStorage)
  1116. if err != nil {
  1117. log.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  1118. }
  1119. clusterTotal, err := resultToTotals(resultTotal)
  1120. if err != nil {
  1121. // If clusterTotal query failed, it's likely because there are no PVs, which
  1122. // causes the qTotal query to return no data. Instead, query only node costs.
  1123. // If that fails, return an error because something is actually wrong.
  1124. qNodes := fmt.Sprintf(queryNodes, env.GetPromClusterFilter(), env.GetPromClusterLabel(), localStorageQuery)
  1125. resultNodes, warnings, err := ctx.QueryRangeSync(qNodes, start, end, window)
  1126. for _, warning := range warnings {
  1127. log.Warnf(warning)
  1128. }
  1129. if err != nil {
  1130. return nil, err
  1131. }
  1132. clusterTotal, err = resultToTotals(resultNodes)
  1133. if err != nil {
  1134. log.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  1135. return nil, err
  1136. }
  1137. }
  1138. return &Totals{
  1139. TotalCost: clusterTotal,
  1140. CPUCost: coreTotal,
  1141. MemCost: ramTotal,
  1142. StorageCost: storageTotal,
  1143. }, nil
  1144. }
  1145. func pvCosts(diskMap map[DiskIdentifier]*Disk, resolution time.Duration, resActiveMins, resPVSize, resPVCost, resPVUsedAvg, resPVUsedMax, resPVCInfo []*prom.QueryResult, cp models.Provider) {
  1146. for _, result := range resActiveMins {
  1147. cluster, err := result.GetString(env.GetPromClusterLabel())
  1148. if err != nil {
  1149. cluster = env.GetClusterID()
  1150. }
  1151. name, err := result.GetString("persistentvolume")
  1152. if err != nil {
  1153. log.Warnf("ClusterDisks: active mins missing pv name")
  1154. continue
  1155. }
  1156. if len(result.Values) == 0 {
  1157. continue
  1158. }
  1159. key := DiskIdentifier{cluster, name}
  1160. if _, ok := diskMap[key]; !ok {
  1161. diskMap[key] = &Disk{
  1162. Cluster: cluster,
  1163. Name: name,
  1164. Breakdown: &ClusterCostsBreakdown{},
  1165. }
  1166. }
  1167. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  1168. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  1169. mins := e.Sub(s).Minutes()
  1170. diskMap[key].End = e
  1171. diskMap[key].Start = s
  1172. diskMap[key].Minutes = mins
  1173. }
  1174. for _, result := range resPVSize {
  1175. cluster, err := result.GetString(env.GetPromClusterLabel())
  1176. if err != nil {
  1177. cluster = env.GetClusterID()
  1178. }
  1179. name, err := result.GetString("persistentvolume")
  1180. if err != nil {
  1181. log.Warnf("ClusterDisks: PV size data missing persistentvolume")
  1182. continue
  1183. }
  1184. // TODO niko/assets storage class
  1185. bytes := result.Values[0].Value
  1186. key := DiskIdentifier{cluster, name}
  1187. if _, ok := diskMap[key]; !ok {
  1188. diskMap[key] = &Disk{
  1189. Cluster: cluster,
  1190. Name: name,
  1191. Breakdown: &ClusterCostsBreakdown{},
  1192. }
  1193. }
  1194. diskMap[key].Bytes = bytes
  1195. }
  1196. customPricingEnabled := provider.CustomPricesEnabled(cp)
  1197. customPricingConfig, err := cp.GetConfig()
  1198. if err != nil {
  1199. log.Warnf("ClusterDisks: failed to load custom pricing: %s", err)
  1200. }
  1201. for _, result := range resPVCost {
  1202. cluster, err := result.GetString(env.GetPromClusterLabel())
  1203. if err != nil {
  1204. cluster = env.GetClusterID()
  1205. }
  1206. name, err := result.GetString("persistentvolume")
  1207. if err != nil {
  1208. log.Warnf("ClusterDisks: PV cost data missing persistentvolume")
  1209. continue
  1210. }
  1211. // TODO niko/assets storage class
  1212. var cost float64
  1213. if customPricingEnabled && customPricingConfig != nil {
  1214. customPVCostStr := customPricingConfig.Storage
  1215. customPVCost, err := strconv.ParseFloat(customPVCostStr, 64)
  1216. if err != nil {
  1217. log.Warnf("ClusterDisks: error parsing custom PV price: %s", customPVCostStr)
  1218. }
  1219. cost = customPVCost
  1220. } else {
  1221. cost = result.Values[0].Value
  1222. }
  1223. key := DiskIdentifier{cluster, name}
  1224. if _, ok := diskMap[key]; !ok {
  1225. diskMap[key] = &Disk{
  1226. Cluster: cluster,
  1227. Name: name,
  1228. Breakdown: &ClusterCostsBreakdown{},
  1229. }
  1230. }
  1231. diskMap[key].Cost = cost * (diskMap[key].Bytes / 1024 / 1024 / 1024) * (diskMap[key].Minutes / 60)
  1232. providerID, _ := result.GetString("provider_id") // just put the providerID set up here, it's the simplest query.
  1233. if providerID != "" {
  1234. diskMap[key].ProviderID = provider.ParsePVID(providerID)
  1235. }
  1236. }
  1237. for _, result := range resPVUsedAvg {
  1238. cluster, err := result.GetString(env.GetPromClusterLabel())
  1239. if err != nil {
  1240. cluster = env.GetClusterID()
  1241. }
  1242. claimName, err := result.GetString("persistentvolumeclaim")
  1243. if err != nil {
  1244. log.Debugf("ClusterDisks: pv usage data missing persistentvolumeclaim")
  1245. continue
  1246. }
  1247. claimNamespace, err := result.GetString("namespace")
  1248. if err != nil {
  1249. log.Debugf("ClusterDisks: pv usage data missing namespace")
  1250. continue
  1251. }
  1252. var volumeName string
  1253. for _, thatRes := range resPVCInfo {
  1254. thatCluster, err := thatRes.GetString(env.GetPromClusterLabel())
  1255. if err != nil {
  1256. thatCluster = env.GetClusterID()
  1257. }
  1258. thatVolumeName, err := thatRes.GetString("volumename")
  1259. if err != nil {
  1260. log.Debugf("ClusterDisks: pv claim data missing volumename")
  1261. continue
  1262. }
  1263. thatClaimName, err := thatRes.GetString("persistentvolumeclaim")
  1264. if err != nil {
  1265. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  1266. continue
  1267. }
  1268. thatClaimNamespace, err := thatRes.GetString("namespace")
  1269. if err != nil {
  1270. log.Debugf("ClusterDisks: pv claim data missing namespace")
  1271. continue
  1272. }
  1273. if cluster == thatCluster && claimName == thatClaimName && claimNamespace == thatClaimNamespace {
  1274. volumeName = thatVolumeName
  1275. }
  1276. }
  1277. usage := result.Values[0].Value
  1278. key := DiskIdentifier{cluster, volumeName}
  1279. if _, ok := diskMap[key]; !ok {
  1280. diskMap[key] = &Disk{
  1281. Cluster: cluster,
  1282. Name: volumeName,
  1283. Breakdown: &ClusterCostsBreakdown{},
  1284. }
  1285. }
  1286. diskMap[key].BytesUsedAvgPtr = &usage
  1287. }
  1288. for _, result := range resPVUsedMax {
  1289. cluster, err := result.GetString(env.GetPromClusterLabel())
  1290. if err != nil {
  1291. cluster = env.GetClusterID()
  1292. }
  1293. claimName, err := result.GetString("persistentvolumeclaim")
  1294. if err != nil {
  1295. log.Debugf("ClusterDisks: pv usage data missing persistentvolumeclaim")
  1296. continue
  1297. }
  1298. claimNamespace, err := result.GetString("namespace")
  1299. if err != nil {
  1300. log.Debugf("ClusterDisks: pv usage data missing namespace")
  1301. continue
  1302. }
  1303. var volumeName string
  1304. for _, thatRes := range resPVCInfo {
  1305. thatCluster, err := thatRes.GetString(env.GetPromClusterLabel())
  1306. if err != nil {
  1307. thatCluster = env.GetClusterID()
  1308. }
  1309. thatVolumeName, err := thatRes.GetString("volumename")
  1310. if err != nil {
  1311. log.Debugf("ClusterDisks: pv claim data missing volumename")
  1312. continue
  1313. }
  1314. thatClaimName, err := thatRes.GetString("persistentvolumeclaim")
  1315. if err != nil {
  1316. log.Debugf("ClusterDisks: pv claim data missing persistentvolumeclaim")
  1317. continue
  1318. }
  1319. thatClaimNamespace, err := thatRes.GetString("namespace")
  1320. if err != nil {
  1321. log.Debugf("ClusterDisks: pv claim data missing namespace")
  1322. continue
  1323. }
  1324. if cluster == thatCluster && claimName == thatClaimName && claimNamespace == thatClaimNamespace {
  1325. volumeName = thatVolumeName
  1326. }
  1327. }
  1328. usage := result.Values[0].Value
  1329. key := DiskIdentifier{cluster, volumeName}
  1330. if _, ok := diskMap[key]; !ok {
  1331. diskMap[key] = &Disk{
  1332. Cluster: cluster,
  1333. Name: volumeName,
  1334. Breakdown: &ClusterCostsBreakdown{},
  1335. }
  1336. }
  1337. diskMap[key].BytesUsedMaxPtr = &usage
  1338. }
  1339. }