cluster.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. }
  337. // GKE lies about the number of cores e2 nodes have. This table
  338. // contains a mapping from node type -> actual CPU cores
  339. // for those cases.
  340. var partialCPUMap = map[string]float64{
  341. "e2-micro": 0.25,
  342. "e2-small": 0.5,
  343. "e2-medium": 1.0,
  344. }
  345. type NodeIdentifier struct {
  346. Cluster string
  347. Name string
  348. ProviderID string
  349. }
  350. type nodeIdentifierNoProviderID struct {
  351. Cluster string
  352. Name string
  353. }
  354. func ClusterNodes(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[NodeIdentifier]*Node, error) {
  355. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  356. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  357. if offset < time.Minute {
  358. offsetStr = ""
  359. }
  360. // minsPerResolution determines accuracy and resource use for the following
  361. // queries. Smaller values (higher resolution) result in better accuracy,
  362. // but more expensive queries, and vice-a-versa.
  363. minsPerResolution := 1
  364. resolution := time.Duration(minsPerResolution) * time.Minute
  365. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  366. // value, converts it to a cumulative value; i.e.
  367. // [$/hr] * [min/res]*[hr/min] = [$/res]
  368. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  369. requiredCtx := prom.NewContext(client)
  370. optionalCtx := prom.NewContext(client)
  371. 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)
  372. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  373. 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)
  374. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  375. 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)
  376. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total[%s:%dm]%s)) by (kubernetes_node, cluster_id, mode)`, durationStr, minsPerResolution, offsetStr)
  377. 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)
  378. 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)
  379. queryActiveMins := fmt.Sprintf(`avg(node_total_hourly_cost) by (node, cluster_id, provider_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  380. queryIsSpot := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  381. queryLabels := fmt.Sprintf(`count_over_time(kube_node_labels[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  382. // Return errors if these fail
  383. resChNodeCPUCost := requiredCtx.Query(queryNodeCPUCost)
  384. resChNodeCPUCores := requiredCtx.Query(queryNodeCPUCores)
  385. resChNodeRAMCost := requiredCtx.Query(queryNodeRAMCost)
  386. resChNodeRAMBytes := requiredCtx.Query(queryNodeRAMBytes)
  387. resChNodeGPUCost := requiredCtx.Query(queryNodeGPUCost)
  388. resChActiveMins := requiredCtx.Query(queryActiveMins)
  389. resChIsSpot := requiredCtx.Query(queryIsSpot)
  390. // Do not return errors if these fail, but log warnings
  391. resChNodeCPUModeTotal := optionalCtx.Query(queryNodeCPUModeTotal)
  392. resChNodeRAMSystemPct := optionalCtx.Query(queryNodeRAMSystemPct)
  393. resChNodeRAMUserPct := optionalCtx.Query(queryNodeRAMUserPct)
  394. resChLabels := optionalCtx.Query(queryLabels)
  395. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  396. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  397. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  398. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  399. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  400. resIsSpot, _ := resChIsSpot.Await()
  401. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  402. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  403. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  404. resActiveMins, _ := resChActiveMins.Await()
  405. resLabels, _ := resChLabels.Await()
  406. if optionalCtx.HasErrors() {
  407. for _, err := range optionalCtx.Errors() {
  408. log.Warningf("ClusterNodes: %s", err)
  409. }
  410. }
  411. if requiredCtx.HasErrors() {
  412. for _, err := range requiredCtx.Errors() {
  413. log.Errorf("ClusterNodes: %s", err)
  414. }
  415. return nil, requiredCtx.ErrorCollection()
  416. }
  417. cpuCostMap, clusterAndNameToType1 := buildCPUCostMap(resNodeCPUCost, cp.ParseID)
  418. ramCostMap, clusterAndNameToType2 := buildRAMCostMap(resNodeRAMCost, cp.ParseID)
  419. gpuCostMap, clusterAndNameToType3 := buildGPUCostMap(resNodeGPUCost, cp.ParseID)
  420. clusterAndNameToTypeIntermediate := mergeTypeMaps(clusterAndNameToType1, clusterAndNameToType2)
  421. clusterAndNameToType := mergeTypeMaps(clusterAndNameToTypeIntermediate, clusterAndNameToType3)
  422. cpuCoresMap := buildCPUCoresMap(resNodeCPUCores, clusterAndNameToType)
  423. ramBytesMap := buildRAMBytesMap(resNodeRAMBytes)
  424. ramUserPctMap := buildRAMUserPctMap(resNodeRAMUserPct)
  425. ramSystemPctMap := buildRAMSystemPctMap(resNodeRAMSystemPct)
  426. cpuBreakdownMap := buildCPUBreakdownMap(resNodeCPUModeTotal)
  427. activeDataMap := buildActiveDataMap(resActiveMins, resolution, cp.ParseID)
  428. preemptibleMap := buildPreemptibleMap(resIsSpot, cp.ParseID)
  429. labelsMap := buildLabelsMap(resLabels)
  430. nodeMap := buildNodeMap(
  431. cpuCostMap, ramCostMap, gpuCostMap,
  432. cpuCoresMap, ramBytesMap, ramUserPctMap,
  433. ramSystemPctMap,
  434. cpuBreakdownMap,
  435. activeDataMap,
  436. preemptibleMap,
  437. labelsMap,
  438. clusterAndNameToType,
  439. )
  440. c, err := cp.GetConfig()
  441. if err != nil {
  442. return nil, err
  443. }
  444. discount, err := ParsePercentString(c.Discount)
  445. if err != nil {
  446. return nil, err
  447. }
  448. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  449. if err != nil {
  450. return nil, err
  451. }
  452. for _, node := range nodeMap {
  453. // TODO take RI into account
  454. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  455. // Apply all remaining resources to Idle
  456. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  457. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  458. }
  459. return nodeMap, nil
  460. }
  461. type LoadBalancer struct {
  462. Cluster string
  463. Name string
  464. ProviderID string
  465. Cost float64
  466. Start time.Time
  467. Minutes float64
  468. }
  469. func ClusterLoadBalancers(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*LoadBalancer, error) {
  470. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  471. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  472. if offset < time.Minute {
  473. offsetStr = ""
  474. }
  475. // minsPerResolution determines accuracy and resource use for the following
  476. // queries. Smaller values (higher resolution) result in better accuracy,
  477. // but more expensive queries, and vice-a-versa.
  478. minsPerResolution := 5
  479. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  480. // value, converts it to a cumulative value; i.e.
  481. // [$/hr] * [min/res]*[hr/min] = [$/res]
  482. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  483. ctx := prom.NewContext(client)
  484. 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)
  485. queryActiveMins := fmt.Sprintf(`count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  486. resChLBCost := ctx.Query(queryLBCost)
  487. resChActiveMins := ctx.Query(queryActiveMins)
  488. resLBCost, _ := resChLBCost.Await()
  489. resActiveMins, _ := resChActiveMins.Await()
  490. if ctx.HasErrors() {
  491. return nil, ctx.ErrorCollection()
  492. }
  493. loadBalancerMap := map[string]*LoadBalancer{}
  494. for _, result := range resLBCost {
  495. cluster, err := result.GetString("cluster_id")
  496. if err != nil {
  497. cluster = env.GetClusterID()
  498. }
  499. namespace, err := result.GetString("namespace")
  500. if err != nil {
  501. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  502. continue
  503. }
  504. serviceName, err := result.GetString("service_name")
  505. if err != nil {
  506. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  507. continue
  508. }
  509. providerID := ""
  510. lbCost := result.Values[0].Value
  511. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  512. if _, ok := loadBalancerMap[key]; !ok {
  513. loadBalancerMap[key] = &LoadBalancer{
  514. Cluster: cluster,
  515. Name: namespace + "/" + serviceName,
  516. ProviderID: providerID, // cp.ParseID(providerID) if providerID does get recorded later
  517. }
  518. }
  519. loadBalancerMap[key].Cost += lbCost
  520. }
  521. for _, result := range resActiveMins {
  522. cluster, err := result.GetString("cluster_id")
  523. if err != nil {
  524. cluster = env.GetClusterID()
  525. }
  526. namespace, err := result.GetString("namespace")
  527. if err != nil {
  528. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  529. continue
  530. }
  531. serviceName, err := result.GetString("service_name")
  532. if err != nil {
  533. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  534. continue
  535. }
  536. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  537. if len(result.Values) == 0 {
  538. continue
  539. }
  540. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  541. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  542. mins := e.Sub(s).Minutes()
  543. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  544. loadBalancerMap[key].Start = s
  545. loadBalancerMap[key].Minutes = mins
  546. }
  547. return loadBalancerMap, nil
  548. }
  549. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  550. func (a *Accesses) ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  551. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  552. start, end, err := util.ParseTimeRange(window, offset)
  553. if err != nil {
  554. return nil, err
  555. }
  556. mins := end.Sub(*start).Minutes()
  557. // minsPerResolution determines accuracy and resource use for the following
  558. // queries. Smaller values (higher resolution) result in better accuracy,
  559. // but more expensive queries, and vice-a-versa.
  560. minsPerResolution := 5
  561. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  562. // value, converts it to a cumulative value; i.e.
  563. // [$/hr] * [min/res]*[hr/min] = [$/res]
  564. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  565. const fmtQueryDataCount = `
  566. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  567. `
  568. const fmtQueryTotalGPU = `
  569. sum(
  570. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  571. ) by (cluster_id)
  572. `
  573. const fmtQueryTotalCPU = `
  574. sum(
  575. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  576. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  577. ) by (cluster_id)
  578. `
  579. const fmtQueryTotalRAM = `
  580. sum(
  581. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  582. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  583. ) by (cluster_id)
  584. `
  585. const fmtQueryTotalStorage = `
  586. sum(
  587. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  588. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  589. ) by (cluster_id)
  590. `
  591. const fmtQueryCPUModePct = `
  592. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  593. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  594. `
  595. const fmtQueryRAMSystemPct = `
  596. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  597. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  598. `
  599. const fmtQueryRAMUserPct = `
  600. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  601. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  602. `
  603. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  604. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  605. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  606. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  607. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  608. if queryTotalLocalStorage != "" {
  609. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  610. }
  611. fmtOffset := ""
  612. if offset != "" {
  613. fmtOffset = fmt.Sprintf("offset %s", offset)
  614. }
  615. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  616. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  617. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  618. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  619. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  620. ctx := prom.NewContext(client)
  621. resChs := ctx.QueryAll(
  622. queryDataCount,
  623. queryTotalGPU,
  624. queryTotalCPU,
  625. queryTotalRAM,
  626. queryTotalStorage,
  627. )
  628. // Only submit the local storage query if it is valid. Otherwise Prometheus
  629. // will return errors. Always append something to resChs, regardless, to
  630. // maintain indexing.
  631. if queryTotalLocalStorage != "" {
  632. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  633. } else {
  634. resChs = append(resChs, nil)
  635. }
  636. if withBreakdown {
  637. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  638. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  639. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  640. bdResChs := ctx.QueryAll(
  641. queryCPUModePct,
  642. queryRAMSystemPct,
  643. queryRAMUserPct,
  644. )
  645. // Only submit the local storage query if it is valid. Otherwise Prometheus
  646. // will return errors. Always append something to resChs, regardless, to
  647. // maintain indexing.
  648. if queryUsedLocalStorage != "" {
  649. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  650. } else {
  651. bdResChs = append(bdResChs, nil)
  652. }
  653. resChs = append(resChs, bdResChs...)
  654. }
  655. resDataCount, _ := resChs[0].Await()
  656. resTotalGPU, _ := resChs[1].Await()
  657. resTotalCPU, _ := resChs[2].Await()
  658. resTotalRAM, _ := resChs[3].Await()
  659. resTotalStorage, _ := resChs[4].Await()
  660. if ctx.HasErrors() {
  661. return nil, ctx.ErrorCollection()
  662. }
  663. defaultClusterID := env.GetClusterID()
  664. dataMinsByCluster := map[string]float64{}
  665. for _, result := range resDataCount {
  666. clusterID, _ := result.GetString("cluster_id")
  667. if clusterID == "" {
  668. clusterID = defaultClusterID
  669. }
  670. dataMins := mins
  671. if len(result.Values) > 0 {
  672. dataMins = result.Values[0].Value
  673. } else {
  674. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  675. }
  676. dataMinsByCluster[clusterID] = dataMins
  677. }
  678. // Determine combined discount
  679. discount, customDiscount := 0.0, 0.0
  680. c, err := a.CloudProvider.GetConfig()
  681. if err == nil {
  682. discount, err = ParsePercentString(c.Discount)
  683. if err != nil {
  684. discount = 0.0
  685. }
  686. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  687. if err != nil {
  688. customDiscount = 0.0
  689. }
  690. }
  691. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  692. costData := make(map[string]map[string]float64)
  693. // Helper function to iterate over Prom query results, parsing the raw values into
  694. // the intermediate costData structure.
  695. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  696. for _, result := range results {
  697. clusterID, _ := result.GetString("cluster_id")
  698. if clusterID == "" {
  699. clusterID = defaultClusterID
  700. }
  701. if _, ok := costData[clusterID]; !ok {
  702. costData[clusterID] = map[string]float64{}
  703. }
  704. if len(result.Values) > 0 {
  705. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  706. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  707. }
  708. }
  709. }
  710. // Apply both sustained use and custom discounts to RAM and CPU
  711. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  712. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  713. // Apply only custom discount to GPU and storage
  714. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  715. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  716. if queryTotalLocalStorage != "" {
  717. resTotalLocalStorage, err := resChs[5].Await()
  718. if err != nil {
  719. return nil, err
  720. }
  721. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  722. }
  723. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  724. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  725. pvUsedCostMap := map[string]float64{}
  726. if withBreakdown {
  727. resCPUModePct, _ := resChs[6].Await()
  728. resRAMSystemPct, _ := resChs[7].Await()
  729. resRAMUserPct, _ := resChs[8].Await()
  730. if ctx.HasErrors() {
  731. return nil, ctx.ErrorCollection()
  732. }
  733. for _, result := range resCPUModePct {
  734. clusterID, _ := result.GetString("cluster_id")
  735. if clusterID == "" {
  736. clusterID = defaultClusterID
  737. }
  738. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  739. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  740. }
  741. cpuBD := cpuBreakdownMap[clusterID]
  742. mode, err := result.GetString("mode")
  743. if err != nil {
  744. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  745. mode = "other"
  746. }
  747. switch mode {
  748. case "idle":
  749. cpuBD.Idle += result.Values[0].Value
  750. case "system":
  751. cpuBD.System += result.Values[0].Value
  752. case "user":
  753. cpuBD.User += result.Values[0].Value
  754. default:
  755. cpuBD.Other += result.Values[0].Value
  756. }
  757. }
  758. for _, result := range resRAMSystemPct {
  759. clusterID, _ := result.GetString("cluster_id")
  760. if clusterID == "" {
  761. clusterID = defaultClusterID
  762. }
  763. if _, ok := ramBreakdownMap[clusterID]; !ok {
  764. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  765. }
  766. ramBD := ramBreakdownMap[clusterID]
  767. ramBD.System += result.Values[0].Value
  768. }
  769. for _, result := range resRAMUserPct {
  770. clusterID, _ := result.GetString("cluster_id")
  771. if clusterID == "" {
  772. clusterID = defaultClusterID
  773. }
  774. if _, ok := ramBreakdownMap[clusterID]; !ok {
  775. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  776. }
  777. ramBD := ramBreakdownMap[clusterID]
  778. ramBD.User += result.Values[0].Value
  779. }
  780. for _, ramBD := range ramBreakdownMap {
  781. remaining := 1.0
  782. remaining -= ramBD.Other
  783. remaining -= ramBD.System
  784. remaining -= ramBD.User
  785. ramBD.Idle = remaining
  786. }
  787. if queryUsedLocalStorage != "" {
  788. resUsedLocalStorage, err := resChs[9].Await()
  789. if err != nil {
  790. return nil, err
  791. }
  792. for _, result := range resUsedLocalStorage {
  793. clusterID, _ := result.GetString("cluster_id")
  794. if clusterID == "" {
  795. clusterID = defaultClusterID
  796. }
  797. pvUsedCostMap[clusterID] += result.Values[0].Value
  798. }
  799. }
  800. }
  801. if ctx.HasErrors() {
  802. for _, err := range ctx.Errors() {
  803. log.Errorf("ComputeClusterCosts: %s", err)
  804. }
  805. return nil, ctx.ErrorCollection()
  806. }
  807. // Convert intermediate structure to Costs instances
  808. costsByCluster := map[string]*ClusterCosts{}
  809. for id, cd := range costData {
  810. dataMins, ok := dataMinsByCluster[id]
  811. if !ok {
  812. dataMins = mins
  813. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  814. }
  815. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  816. if err != nil {
  817. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  818. return nil, err
  819. }
  820. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  821. costs.CPUBreakdown = cpuBD
  822. }
  823. if ramBD, ok := ramBreakdownMap[id]; ok {
  824. costs.RAMBreakdown = ramBD
  825. }
  826. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  827. if pvUC, ok := pvUsedCostMap[id]; ok {
  828. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  829. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  830. }
  831. costs.DataMinutes = dataMins
  832. costsByCluster[id] = costs
  833. }
  834. return costsByCluster, nil
  835. }
  836. type Totals struct {
  837. TotalCost [][]string `json:"totalcost"`
  838. CPUCost [][]string `json:"cpucost"`
  839. MemCost [][]string `json:"memcost"`
  840. StorageCost [][]string `json:"storageCost"`
  841. }
  842. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  843. if len(qrs) == 0 {
  844. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  845. }
  846. result := qrs[0]
  847. totals := [][]string{}
  848. for _, value := range result.Values {
  849. d0 := fmt.Sprintf("%f", value.Timestamp)
  850. d1 := fmt.Sprintf("%f", value.Value)
  851. toAppend := []string{
  852. d0,
  853. d1,
  854. }
  855. totals = append(totals, toAppend)
  856. }
  857. return totals, nil
  858. }
  859. // ClusterCostsOverTime gives the full cluster costs over time
  860. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  861. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  862. if localStorageQuery != "" {
  863. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  864. }
  865. layout := "2006-01-02T15:04:05.000Z"
  866. start, err := time.Parse(layout, startString)
  867. if err != nil {
  868. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  869. return nil, err
  870. }
  871. end, err := time.Parse(layout, endString)
  872. if err != nil {
  873. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  874. return nil, err
  875. }
  876. window, err := time.ParseDuration(windowString)
  877. if err != nil {
  878. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  879. return nil, err
  880. }
  881. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  882. if offset != "" {
  883. offset = fmt.Sprintf("offset %s", offset)
  884. }
  885. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  886. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  887. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  888. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  889. ctx := prom.NewContext(cli)
  890. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  891. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  892. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  893. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  894. resultClusterCores, err := resChClusterCores.Await()
  895. if err != nil {
  896. return nil, err
  897. }
  898. resultClusterRAM, err := resChClusterRAM.Await()
  899. if err != nil {
  900. return nil, err
  901. }
  902. resultStorage, err := resChStorage.Await()
  903. if err != nil {
  904. return nil, err
  905. }
  906. resultTotal, err := resChTotal.Await()
  907. if err != nil {
  908. return nil, err
  909. }
  910. coreTotal, err := resultToTotals(resultClusterCores)
  911. if err != nil {
  912. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  913. return nil, err
  914. }
  915. ramTotal, err := resultToTotals(resultClusterRAM)
  916. if err != nil {
  917. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  918. return nil, err
  919. }
  920. storageTotal, err := resultToTotals(resultStorage)
  921. if err != nil {
  922. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  923. }
  924. clusterTotal, err := resultToTotals(resultTotal)
  925. if err != nil {
  926. // If clusterTotal query failed, it's likely because there are no PVs, which
  927. // causes the qTotal query to return no data. Instead, query only node costs.
  928. // If that fails, return an error because something is actually wrong.
  929. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  930. resultNodes, warnings, err := ctx.QueryRangeSync(qNodes, start, end, window)
  931. for _, warning := range warnings {
  932. log.Warningf(warning)
  933. }
  934. if err != nil {
  935. return nil, err
  936. }
  937. clusterTotal, err = resultToTotals(resultNodes)
  938. if err != nil {
  939. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  940. return nil, err
  941. }
  942. }
  943. return &Totals{
  944. TotalCost: clusterTotal,
  945. CPUCost: coreTotal,
  946. MemCost: ramTotal,
  947. StorageCost: storageTotal,
  948. }, nil
  949. }