cluster.go 40 KB

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