cluster.go 39 KB

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