cluster.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. }
  99. func ClusterDisks(client prometheus.Client, provider cloud.Provider, duration, offset time.Duration) (map[string]*Disk, []error) {
  100. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  101. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  102. if offset < time.Minute {
  103. offsetStr = ""
  104. }
  105. // minsPerResolution determines accuracy and resource use for the following
  106. // queries. Smaller values (higher resolution) result in better accuracy,
  107. // but more expensive queries, and vice-a-versa.
  108. minsPerResolution := 5
  109. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  110. // value, converts it to a cumulative value; i.e.
  111. // [$/hr] * [min/res]*[hr/min] = [$/res]
  112. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  113. // TODO niko/assets how do we not hard-code this price?
  114. costPerGBHr := 0.04 / 730.0
  115. ctx := prom.NewContext(client)
  116. queryPVCost := fmt.Sprintf(`sum_over_time((avg(kube_persistentvolume_capacity_bytes) by (cluster_id, persistentvolume) * avg(pv_hourly_cost) by (cluster_id, persistentvolume))[%s:%dm]%s)/1024/1024/1024 * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  117. queryPVSize := fmt.Sprintf(`avg_over_time(kube_persistentvolume_capacity_bytes[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  118. 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)
  119. queryLocalStorageBytes := fmt.Sprintf(`avg_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  120. resChPVCost := ctx.Query(queryPVCost)
  121. resChPVSize := ctx.Query(queryPVSize)
  122. resChLocalStorageCost := ctx.Query(queryLocalStorageCost)
  123. resChLocalStorageBytes := ctx.Query(queryLocalStorageBytes)
  124. resPVCost, _ := resChPVCost.Await()
  125. resPVSize, _ := resChPVSize.Await()
  126. resLocalStorageCost, _ := resChLocalStorageCost.Await()
  127. resLocalStorageBytes, _ := resChLocalStorageBytes.Await()
  128. if ctx.ErrorCollector.IsError() {
  129. return nil, ctx.Errors()
  130. }
  131. diskMap := map[string]*Disk{}
  132. for _, result := range resPVCost {
  133. cluster, err := result.GetString("cluster_id")
  134. if err != nil {
  135. cluster = env.GetClusterID()
  136. }
  137. name, err := result.GetString("persistentvolume")
  138. if err != nil {
  139. log.Warningf("ClusterDisks: PV cost data missing persistentvolume")
  140. continue
  141. }
  142. // TODO niko/assets storage class
  143. cost := result.Values[0].Value
  144. key := fmt.Sprintf("%s/%s", cluster, name)
  145. if _, ok := diskMap[key]; !ok {
  146. diskMap[key] = &Disk{
  147. Cluster: cluster,
  148. Name: name,
  149. }
  150. }
  151. diskMap[key].Cost += cost
  152. }
  153. for _, result := range resPVSize {
  154. cluster, err := result.GetString("cluster_id")
  155. if err != nil {
  156. cluster = env.GetClusterID()
  157. }
  158. name, err := result.GetString("persistentvolume")
  159. if err != nil {
  160. log.Warningf("ClusterDisks: PV size data missing persistentvolume")
  161. continue
  162. }
  163. // TODO niko/assets storage class
  164. bytes := result.Values[0].Value
  165. key := fmt.Sprintf("%s/%s", cluster, name)
  166. if _, ok := diskMap[key]; !ok {
  167. diskMap[key] = &Disk{
  168. Cluster: cluster,
  169. Name: name,
  170. }
  171. }
  172. diskMap[key].Bytes = bytes
  173. }
  174. for _, result := range resLocalStorageCost {
  175. cluster, err := result.GetString("cluster_id")
  176. if err != nil {
  177. cluster = env.GetClusterID()
  178. }
  179. name, err := result.GetString("instance")
  180. if err != nil {
  181. log.Warningf("ClusterDisks: local storage data missing instance")
  182. continue
  183. }
  184. // TODO niko/assets storage class?
  185. cost := result.Values[0].Value
  186. key := fmt.Sprintf("%s/%s", cluster, name)
  187. if _, ok := diskMap[key]; !ok {
  188. diskMap[key] = &Disk{
  189. Cluster: cluster,
  190. Name: name,
  191. Local: true,
  192. }
  193. }
  194. diskMap[key].Cost += cost
  195. }
  196. for _, result := range resLocalStorageBytes {
  197. cluster, err := result.GetString("cluster_id")
  198. if err != nil {
  199. cluster = env.GetClusterID()
  200. }
  201. name, err := result.GetString("instance")
  202. if err != nil {
  203. log.Warningf("ClusterDisks: local storage data missing instance")
  204. continue
  205. }
  206. // TODO niko/assets storage class
  207. bytes := result.Values[0].Value
  208. key := fmt.Sprintf("%s/%s", cluster, name)
  209. if _, ok := diskMap[key]; !ok {
  210. diskMap[key] = &Disk{
  211. Cluster: cluster,
  212. Name: name,
  213. Local: true,
  214. }
  215. }
  216. diskMap[key].Bytes = bytes
  217. }
  218. return diskMap, nil
  219. }
  220. type Node struct {
  221. Cluster string
  222. Name string
  223. ProviderID string
  224. NodeType string
  225. CPUCost float64
  226. CPUCores float64
  227. GPUCost float64
  228. RAMCost float64
  229. RAMBytes float64
  230. Discount float64
  231. Preemptible bool
  232. }
  233. func ClusterNodes(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*Node, []error) {
  234. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  235. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  236. if offset < time.Minute {
  237. offsetStr = ""
  238. }
  239. // minsPerResolution determines accuracy and resource use for the following
  240. // queries. Smaller values (higher resolution) result in better accuracy,
  241. // but more expensive queries, and vice-a-versa.
  242. minsPerResolution := 5
  243. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  244. // value, converts it to a cumulative value; i.e.
  245. // [$/hr] * [min/res]*[hr/min] = [$/res]
  246. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  247. ctx := prom.NewContext(client)
  248. 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)
  249. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  250. 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)
  251. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  252. queryNodeGPUCost := fmt.Sprintf(`sum_over_time((avg(node_gpu_hourly_cost) by (cluster_id, node, provider_id))[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  253. queryNodeLabels := fmt.Sprintf(`count_over_time(kube_node_labels[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  254. resChNodeCPUCost := ctx.Query(queryNodeCPUCost)
  255. resChNodeCPUCores := ctx.Query(queryNodeCPUCores)
  256. resChNodeRAMCost := ctx.Query(queryNodeRAMCost)
  257. resChNodeRAMBytes := ctx.Query(queryNodeRAMBytes)
  258. resChNodeGPUCost := ctx.Query(queryNodeGPUCost)
  259. resChNodeLabels := ctx.Query(queryNodeLabels)
  260. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  261. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  262. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  263. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  264. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  265. resNodeLabels, _ := resChNodeLabels.Await()
  266. if ctx.ErrorCollector.IsError() {
  267. return nil, ctx.Errors()
  268. }
  269. nodeMap := map[string]*Node{}
  270. for _, result := range resNodeCPUCost {
  271. cluster, err := result.GetString("cluster_id")
  272. if err != nil {
  273. cluster = env.GetClusterID()
  274. }
  275. name, err := result.GetString("node")
  276. if err != nil {
  277. log.Warningf("ClusterNodes: CPU cost data missing node")
  278. continue
  279. }
  280. nodeType, _ := result.GetString("instance_type")
  281. providerID, _ := result.GetString("provider_id")
  282. cpuCost := result.Values[0].Value
  283. key := fmt.Sprintf("%s/%s", cluster, name)
  284. if _, ok := nodeMap[key]; !ok {
  285. nodeMap[key] = &Node{
  286. Cluster: cluster,
  287. Name: name,
  288. NodeType: nodeType,
  289. ProviderID: providerID,
  290. }
  291. }
  292. nodeMap[key].CPUCost += cpuCost
  293. nodeMap[key].NodeType = nodeType
  294. }
  295. for _, result := range resNodeCPUCores {
  296. cluster, err := result.GetString("cluster_id")
  297. if err != nil {
  298. cluster = env.GetClusterID()
  299. }
  300. name, err := result.GetString("node")
  301. if err != nil {
  302. log.Warningf("ClusterNodes: CPU cores data missing node")
  303. continue
  304. }
  305. cpuCores := result.Values[0].Value
  306. key := fmt.Sprintf("%s/%s", cluster, name)
  307. if _, ok := nodeMap[key]; !ok {
  308. nodeMap[key] = &Node{
  309. Cluster: cluster,
  310. Name: name,
  311. }
  312. }
  313. nodeMap[key].CPUCores = cpuCores
  314. }
  315. for _, result := range resNodeRAMCost {
  316. cluster, err := result.GetString("cluster_id")
  317. if err != nil {
  318. cluster = env.GetClusterID()
  319. }
  320. name, err := result.GetString("node")
  321. if err != nil {
  322. log.Warningf("ClusterNodes: RAM cost data missing node")
  323. continue
  324. }
  325. nodeType, _ := result.GetString("instance_type")
  326. providerID, _ := result.GetString("provider_id")
  327. ramCost := result.Values[0].Value
  328. key := fmt.Sprintf("%s/%s", cluster, name)
  329. if _, ok := nodeMap[key]; !ok {
  330. nodeMap[key] = &Node{
  331. Cluster: cluster,
  332. Name: name,
  333. NodeType: nodeType,
  334. ProviderID: providerID,
  335. }
  336. }
  337. nodeMap[key].RAMCost += ramCost
  338. nodeMap[key].NodeType = nodeType
  339. }
  340. for _, result := range resNodeRAMBytes {
  341. cluster, err := result.GetString("cluster_id")
  342. if err != nil {
  343. cluster = env.GetClusterID()
  344. }
  345. name, err := result.GetString("node")
  346. if err != nil {
  347. log.Warningf("ClusterNodes: RAM bytes data missing node")
  348. continue
  349. }
  350. ramBytes := result.Values[0].Value
  351. key := fmt.Sprintf("%s/%s", cluster, name)
  352. if _, ok := nodeMap[key]; !ok {
  353. nodeMap[key] = &Node{
  354. Cluster: cluster,
  355. Name: name,
  356. }
  357. }
  358. nodeMap[key].RAMBytes = ramBytes
  359. }
  360. for _, result := range resNodeGPUCost {
  361. cluster, err := result.GetString("cluster_id")
  362. if err != nil {
  363. cluster = env.GetClusterID()
  364. }
  365. name, err := result.GetString("node")
  366. if err != nil {
  367. log.Warningf("ClusterNodes: GPU cost data missing node")
  368. continue
  369. }
  370. nodeType, _ := result.GetString("instance_type")
  371. providerID, _ := result.GetString("provider_id")
  372. gpuCost := result.Values[0].Value
  373. key := fmt.Sprintf("%s/%s", cluster, name)
  374. if _, ok := nodeMap[key]; !ok {
  375. nodeMap[key] = &Node{
  376. Cluster: cluster,
  377. Name: name,
  378. NodeType: nodeType,
  379. ProviderID: providerID,
  380. }
  381. }
  382. nodeMap[key].GPUCost += gpuCost
  383. }
  384. // Determine preemptibility with node labels
  385. for _, result := range resNodeLabels {
  386. nodeName, err := result.GetString("node")
  387. if err != nil {
  388. continue
  389. }
  390. // GCP preemptible label
  391. pre, _ := result.GetString("label_cloud_google_com_gke_preemptible")
  392. if node, ok := nodeMap[nodeName]; pre == "true" && ok {
  393. node.Preemptible = true
  394. }
  395. // TODO AWS preemptible
  396. // TODO Azure preemptible
  397. }
  398. c, err := cp.GetConfig()
  399. if err != nil {
  400. return nil, []error{err}
  401. }
  402. discount, err := ParsePercentString(c.Discount)
  403. if err != nil {
  404. return nil, []error{err}
  405. }
  406. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  407. if err != nil {
  408. return nil, []error{err}
  409. }
  410. for _, node := range nodeMap {
  411. // TODO take RI into account
  412. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  413. }
  414. return nodeMap, nil
  415. }
  416. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  417. func ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  418. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  419. start, end, err := util.ParseTimeRange(window, offset)
  420. if err != nil {
  421. return nil, err
  422. }
  423. mins := end.Sub(*start).Minutes()
  424. // minsPerResolution determines accuracy and resource use for the following
  425. // queries. Smaller values (higher resolution) result in better accuracy,
  426. // but more expensive queries, and vice-a-versa.
  427. minsPerResolution := 5
  428. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  429. // value, converts it to a cumulative value; i.e.
  430. // [$/hr] * [min/res]*[hr/min] = [$/res]
  431. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  432. const fmtQueryDataCount = `
  433. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  434. `
  435. const fmtQueryTotalGPU = `
  436. sum(
  437. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  438. ) by (cluster_id)
  439. `
  440. const fmtQueryTotalCPU = `
  441. sum(
  442. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  443. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  444. ) by (cluster_id)
  445. `
  446. const fmtQueryTotalRAM = `
  447. sum(
  448. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  449. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  450. ) by (cluster_id)
  451. `
  452. const fmtQueryTotalStorage = `
  453. sum(
  454. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  455. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  456. ) by (cluster_id)
  457. `
  458. const fmtQueryCPUModePct = `
  459. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  460. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  461. `
  462. const fmtQueryRAMSystemPct = `
  463. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  464. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  465. `
  466. const fmtQueryRAMUserPct = `
  467. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  468. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  469. `
  470. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  471. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  472. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  473. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  474. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  475. if queryTotalLocalStorage != "" {
  476. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  477. }
  478. fmtOffset := ""
  479. if offset != "" {
  480. fmtOffset = fmt.Sprintf("offset %s", offset)
  481. }
  482. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  483. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  484. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  485. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  486. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  487. ctx := prom.NewContext(client)
  488. resChs := ctx.QueryAll(
  489. queryDataCount,
  490. queryTotalGPU,
  491. queryTotalCPU,
  492. queryTotalRAM,
  493. queryTotalStorage,
  494. )
  495. // Only submit the local storage query if it is valid. Otherwise Prometheus
  496. // will return errors. Always append something to resChs, regardless, to
  497. // maintain indexing.
  498. if queryTotalLocalStorage != "" {
  499. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  500. } else {
  501. resChs = append(resChs, nil)
  502. }
  503. if withBreakdown {
  504. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  505. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  506. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  507. bdResChs := ctx.QueryAll(
  508. queryCPUModePct,
  509. queryRAMSystemPct,
  510. queryRAMUserPct,
  511. )
  512. // Only submit the local storage query if it is valid. Otherwise Prometheus
  513. // will return errors. Always append something to resChs, regardless, to
  514. // maintain indexing.
  515. if queryUsedLocalStorage != "" {
  516. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  517. } else {
  518. bdResChs = append(bdResChs, nil)
  519. }
  520. resChs = append(resChs, bdResChs...)
  521. }
  522. resDataCount, _ := resChs[0].Await()
  523. resTotalGPU, _ := resChs[1].Await()
  524. resTotalCPU, _ := resChs[2].Await()
  525. resTotalRAM, _ := resChs[3].Await()
  526. resTotalStorage, _ := resChs[4].Await()
  527. if ctx.HasErrors() {
  528. return nil, ctx.Errors()[0]
  529. }
  530. defaultClusterID := env.GetClusterID()
  531. dataMinsByCluster := map[string]float64{}
  532. for _, result := range resDataCount {
  533. clusterID, _ := result.GetString("cluster_id")
  534. if clusterID == "" {
  535. clusterID = defaultClusterID
  536. }
  537. dataMins := mins
  538. if len(result.Values) > 0 {
  539. dataMins = result.Values[0].Value
  540. } else {
  541. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  542. }
  543. dataMinsByCluster[clusterID] = dataMins
  544. }
  545. // Determine combined discount
  546. discount, customDiscount := 0.0, 0.0
  547. c, err := A.Cloud.GetConfig()
  548. if err == nil {
  549. discount, err = ParsePercentString(c.Discount)
  550. if err != nil {
  551. discount = 0.0
  552. }
  553. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  554. if err != nil {
  555. customDiscount = 0.0
  556. }
  557. }
  558. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  559. costData := make(map[string]map[string]float64)
  560. // Helper function to iterate over Prom query results, parsing the raw values into
  561. // the intermediate costData structure.
  562. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  563. for _, result := range results {
  564. clusterID, _ := result.GetString("cluster_id")
  565. if clusterID == "" {
  566. clusterID = defaultClusterID
  567. }
  568. if _, ok := costData[clusterID]; !ok {
  569. costData[clusterID] = map[string]float64{}
  570. }
  571. if len(result.Values) > 0 {
  572. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  573. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  574. }
  575. }
  576. }
  577. // Apply both sustained use and custom discounts to RAM and CPU
  578. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  579. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  580. // Apply only custom discount to GPU and storage
  581. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  582. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  583. if queryTotalLocalStorage != "" {
  584. resTotalLocalStorage, err := resChs[5].Await()
  585. if err != nil {
  586. return nil, err
  587. }
  588. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  589. }
  590. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  591. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  592. pvUsedCostMap := map[string]float64{}
  593. if withBreakdown {
  594. resCPUModePct, _ := resChs[6].Await()
  595. resRAMSystemPct, _ := resChs[7].Await()
  596. resRAMUserPct, _ := resChs[8].Await()
  597. if ctx.HasErrors() {
  598. return nil, ctx.Errors()[0]
  599. }
  600. for _, result := range resCPUModePct {
  601. clusterID, _ := result.GetString("cluster_id")
  602. if clusterID == "" {
  603. clusterID = defaultClusterID
  604. }
  605. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  606. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  607. }
  608. cpuBD := cpuBreakdownMap[clusterID]
  609. mode, err := result.GetString("mode")
  610. if err != nil {
  611. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  612. mode = "other"
  613. }
  614. switch mode {
  615. case "idle":
  616. cpuBD.Idle += result.Values[0].Value
  617. case "system":
  618. cpuBD.System += result.Values[0].Value
  619. case "user":
  620. cpuBD.User += result.Values[0].Value
  621. default:
  622. cpuBD.Other += result.Values[0].Value
  623. }
  624. }
  625. for _, result := range resRAMSystemPct {
  626. clusterID, _ := result.GetString("cluster_id")
  627. if clusterID == "" {
  628. clusterID = defaultClusterID
  629. }
  630. if _, ok := ramBreakdownMap[clusterID]; !ok {
  631. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  632. }
  633. ramBD := ramBreakdownMap[clusterID]
  634. ramBD.System += result.Values[0].Value
  635. }
  636. for _, result := range resRAMUserPct {
  637. clusterID, _ := result.GetString("cluster_id")
  638. if clusterID == "" {
  639. clusterID = defaultClusterID
  640. }
  641. if _, ok := ramBreakdownMap[clusterID]; !ok {
  642. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  643. }
  644. ramBD := ramBreakdownMap[clusterID]
  645. ramBD.User += result.Values[0].Value
  646. }
  647. for _, ramBD := range ramBreakdownMap {
  648. remaining := 1.0
  649. remaining -= ramBD.Other
  650. remaining -= ramBD.System
  651. remaining -= ramBD.User
  652. ramBD.Idle = remaining
  653. }
  654. if queryUsedLocalStorage != "" {
  655. resUsedLocalStorage, err := resChs[9].Await()
  656. if err != nil {
  657. return nil, err
  658. }
  659. for _, result := range resUsedLocalStorage {
  660. clusterID, _ := result.GetString("cluster_id")
  661. if clusterID == "" {
  662. clusterID = defaultClusterID
  663. }
  664. pvUsedCostMap[clusterID] += result.Values[0].Value
  665. }
  666. }
  667. }
  668. if ctx.ErrorCollector.IsError() {
  669. for _, err := range ctx.Errors() {
  670. log.Errorf("ComputeClusterCosts: %s", err)
  671. }
  672. return nil, ctx.Errors()[0]
  673. }
  674. // Convert intermediate structure to Costs instances
  675. costsByCluster := map[string]*ClusterCosts{}
  676. for id, cd := range costData {
  677. dataMins, ok := dataMinsByCluster[id]
  678. if !ok {
  679. dataMins = mins
  680. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  681. }
  682. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  683. if err != nil {
  684. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  685. return nil, err
  686. }
  687. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  688. costs.CPUBreakdown = cpuBD
  689. }
  690. if ramBD, ok := ramBreakdownMap[id]; ok {
  691. costs.RAMBreakdown = ramBD
  692. }
  693. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  694. if pvUC, ok := pvUsedCostMap[id]; ok {
  695. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  696. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  697. }
  698. costs.DataMinutes = dataMins
  699. costsByCluster[id] = costs
  700. }
  701. return costsByCluster, nil
  702. }
  703. type Totals struct {
  704. TotalCost [][]string `json:"totalcost"`
  705. CPUCost [][]string `json:"cpucost"`
  706. MemCost [][]string `json:"memcost"`
  707. StorageCost [][]string `json:"storageCost"`
  708. }
  709. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  710. if len(qrs) == 0 {
  711. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  712. }
  713. result := qrs[0]
  714. totals := [][]string{}
  715. for _, value := range result.Values {
  716. d0 := fmt.Sprintf("%f", value.Timestamp)
  717. d1 := fmt.Sprintf("%f", value.Value)
  718. toAppend := []string{
  719. d0,
  720. d1,
  721. }
  722. totals = append(totals, toAppend)
  723. }
  724. return totals, nil
  725. }
  726. // ClusterCostsOverTime gives the full cluster costs over time
  727. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  728. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  729. if localStorageQuery != "" {
  730. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  731. }
  732. layout := "2006-01-02T15:04:05.000Z"
  733. start, err := time.Parse(layout, startString)
  734. if err != nil {
  735. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  736. return nil, err
  737. }
  738. end, err := time.Parse(layout, endString)
  739. if err != nil {
  740. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  741. return nil, err
  742. }
  743. window, err := time.ParseDuration(windowString)
  744. if err != nil {
  745. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  746. return nil, err
  747. }
  748. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  749. if offset != "" {
  750. offset = fmt.Sprintf("offset %s", offset)
  751. }
  752. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  753. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  754. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  755. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  756. ctx := prom.NewContext(cli)
  757. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  758. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  759. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  760. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  761. resultClusterCores, err := resChClusterCores.Await()
  762. if err != nil {
  763. return nil, err
  764. }
  765. resultClusterRAM, err := resChClusterRAM.Await()
  766. if err != nil {
  767. return nil, err
  768. }
  769. resultStorage, err := resChStorage.Await()
  770. if err != nil {
  771. return nil, err
  772. }
  773. resultTotal, err := resChTotal.Await()
  774. if err != nil {
  775. return nil, err
  776. }
  777. coreTotal, err := resultToTotals(resultClusterCores)
  778. if err != nil {
  779. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  780. return nil, err
  781. }
  782. ramTotal, err := resultToTotals(resultClusterRAM)
  783. if err != nil {
  784. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  785. return nil, err
  786. }
  787. storageTotal, err := resultToTotals(resultStorage)
  788. if err != nil {
  789. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  790. }
  791. clusterTotal, err := resultToTotals(resultTotal)
  792. if err != nil {
  793. // If clusterTotal query failed, it's likely because there are no PVs, which
  794. // causes the qTotal query to return no data. Instead, query only node costs.
  795. // If that fails, return an error because something is actually wrong.
  796. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  797. resultNodes, err := ctx.QueryRangeSync(qNodes, start, end, window)
  798. if err != nil {
  799. return nil, err
  800. }
  801. clusterTotal, err = resultToTotals(resultNodes)
  802. if err != nil {
  803. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  804. return nil, err
  805. }
  806. }
  807. return &Totals{
  808. TotalCost: clusterTotal,
  809. CPUCost: coreTotal,
  810. MemCost: ramTotal,
  811. StorageCost: storageTotal,
  812. }, nil
  813. }