cluster.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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: cp.ParseID(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: cp.ParseID(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: cp.ParseID(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. cluster, err := result.GetString("cluster_id")
  393. if err != nil {
  394. cluster = env.GetClusterID()
  395. }
  396. key := fmt.Sprintf("%s/%s", cluster, nodeName)
  397. if node, ok := nodeMap[key]; pre == "true" && ok {
  398. node.Preemptible = true
  399. }
  400. // TODO AWS preemptible
  401. // TODO Azure preemptible
  402. }
  403. c, err := cp.GetConfig()
  404. if err != nil {
  405. return nil, []error{err}
  406. }
  407. discount, err := ParsePercentString(c.Discount)
  408. if err != nil {
  409. return nil, []error{err}
  410. }
  411. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  412. if err != nil {
  413. return nil, []error{err}
  414. }
  415. for _, node := range nodeMap {
  416. // TODO take RI into account
  417. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  418. }
  419. return nodeMap, nil
  420. }
  421. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  422. func ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  423. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  424. start, end, err := util.ParseTimeRange(window, offset)
  425. if err != nil {
  426. return nil, err
  427. }
  428. mins := end.Sub(*start).Minutes()
  429. // minsPerResolution determines accuracy and resource use for the following
  430. // queries. Smaller values (higher resolution) result in better accuracy,
  431. // but more expensive queries, and vice-a-versa.
  432. minsPerResolution := 5
  433. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  434. // value, converts it to a cumulative value; i.e.
  435. // [$/hr] * [min/res]*[hr/min] = [$/res]
  436. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  437. const fmtQueryDataCount = `
  438. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  439. `
  440. const fmtQueryTotalGPU = `
  441. sum(
  442. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  443. ) by (cluster_id)
  444. `
  445. const fmtQueryTotalCPU = `
  446. sum(
  447. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  448. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  449. ) by (cluster_id)
  450. `
  451. const fmtQueryTotalRAM = `
  452. sum(
  453. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  454. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  455. ) by (cluster_id)
  456. `
  457. const fmtQueryTotalStorage = `
  458. sum(
  459. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  460. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  461. ) by (cluster_id)
  462. `
  463. const fmtQueryCPUModePct = `
  464. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  465. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  466. `
  467. const fmtQueryRAMSystemPct = `
  468. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  469. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  470. `
  471. const fmtQueryRAMUserPct = `
  472. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  473. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  474. `
  475. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  476. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  477. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  478. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  479. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  480. if queryTotalLocalStorage != "" {
  481. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  482. }
  483. fmtOffset := ""
  484. if offset != "" {
  485. fmtOffset = fmt.Sprintf("offset %s", offset)
  486. }
  487. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  488. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  489. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  490. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  491. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  492. ctx := prom.NewContext(client)
  493. resChs := ctx.QueryAll(
  494. queryDataCount,
  495. queryTotalGPU,
  496. queryTotalCPU,
  497. queryTotalRAM,
  498. queryTotalStorage,
  499. )
  500. // Only submit the local storage query if it is valid. Otherwise Prometheus
  501. // will return errors. Always append something to resChs, regardless, to
  502. // maintain indexing.
  503. if queryTotalLocalStorage != "" {
  504. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  505. } else {
  506. resChs = append(resChs, nil)
  507. }
  508. if withBreakdown {
  509. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  510. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  511. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  512. bdResChs := ctx.QueryAll(
  513. queryCPUModePct,
  514. queryRAMSystemPct,
  515. queryRAMUserPct,
  516. )
  517. // Only submit the local storage query if it is valid. Otherwise Prometheus
  518. // will return errors. Always append something to resChs, regardless, to
  519. // maintain indexing.
  520. if queryUsedLocalStorage != "" {
  521. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  522. } else {
  523. bdResChs = append(bdResChs, nil)
  524. }
  525. resChs = append(resChs, bdResChs...)
  526. }
  527. resDataCount, _ := resChs[0].Await()
  528. resTotalGPU, _ := resChs[1].Await()
  529. resTotalCPU, _ := resChs[2].Await()
  530. resTotalRAM, _ := resChs[3].Await()
  531. resTotalStorage, _ := resChs[4].Await()
  532. if ctx.HasErrors() {
  533. return nil, ctx.Errors()[0]
  534. }
  535. defaultClusterID := env.GetClusterID()
  536. dataMinsByCluster := map[string]float64{}
  537. for _, result := range resDataCount {
  538. clusterID, _ := result.GetString("cluster_id")
  539. if clusterID == "" {
  540. clusterID = defaultClusterID
  541. }
  542. dataMins := mins
  543. if len(result.Values) > 0 {
  544. dataMins = result.Values[0].Value
  545. } else {
  546. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  547. }
  548. dataMinsByCluster[clusterID] = dataMins
  549. }
  550. // Determine combined discount
  551. discount, customDiscount := 0.0, 0.0
  552. c, err := A.Cloud.GetConfig()
  553. if err == nil {
  554. discount, err = ParsePercentString(c.Discount)
  555. if err != nil {
  556. discount = 0.0
  557. }
  558. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  559. if err != nil {
  560. customDiscount = 0.0
  561. }
  562. }
  563. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  564. costData := make(map[string]map[string]float64)
  565. // Helper function to iterate over Prom query results, parsing the raw values into
  566. // the intermediate costData structure.
  567. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  568. for _, result := range results {
  569. clusterID, _ := result.GetString("cluster_id")
  570. if clusterID == "" {
  571. clusterID = defaultClusterID
  572. }
  573. if _, ok := costData[clusterID]; !ok {
  574. costData[clusterID] = map[string]float64{}
  575. }
  576. if len(result.Values) > 0 {
  577. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  578. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  579. }
  580. }
  581. }
  582. // Apply both sustained use and custom discounts to RAM and CPU
  583. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  584. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  585. // Apply only custom discount to GPU and storage
  586. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  587. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  588. if queryTotalLocalStorage != "" {
  589. resTotalLocalStorage, err := resChs[5].Await()
  590. if err != nil {
  591. return nil, err
  592. }
  593. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  594. }
  595. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  596. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  597. pvUsedCostMap := map[string]float64{}
  598. if withBreakdown {
  599. resCPUModePct, _ := resChs[6].Await()
  600. resRAMSystemPct, _ := resChs[7].Await()
  601. resRAMUserPct, _ := resChs[8].Await()
  602. if ctx.HasErrors() {
  603. return nil, ctx.Errors()[0]
  604. }
  605. for _, result := range resCPUModePct {
  606. clusterID, _ := result.GetString("cluster_id")
  607. if clusterID == "" {
  608. clusterID = defaultClusterID
  609. }
  610. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  611. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  612. }
  613. cpuBD := cpuBreakdownMap[clusterID]
  614. mode, err := result.GetString("mode")
  615. if err != nil {
  616. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  617. mode = "other"
  618. }
  619. switch mode {
  620. case "idle":
  621. cpuBD.Idle += result.Values[0].Value
  622. case "system":
  623. cpuBD.System += result.Values[0].Value
  624. case "user":
  625. cpuBD.User += result.Values[0].Value
  626. default:
  627. cpuBD.Other += result.Values[0].Value
  628. }
  629. }
  630. for _, result := range resRAMSystemPct {
  631. clusterID, _ := result.GetString("cluster_id")
  632. if clusterID == "" {
  633. clusterID = defaultClusterID
  634. }
  635. if _, ok := ramBreakdownMap[clusterID]; !ok {
  636. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  637. }
  638. ramBD := ramBreakdownMap[clusterID]
  639. ramBD.System += result.Values[0].Value
  640. }
  641. for _, result := range resRAMUserPct {
  642. clusterID, _ := result.GetString("cluster_id")
  643. if clusterID == "" {
  644. clusterID = defaultClusterID
  645. }
  646. if _, ok := ramBreakdownMap[clusterID]; !ok {
  647. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  648. }
  649. ramBD := ramBreakdownMap[clusterID]
  650. ramBD.User += result.Values[0].Value
  651. }
  652. for _, ramBD := range ramBreakdownMap {
  653. remaining := 1.0
  654. remaining -= ramBD.Other
  655. remaining -= ramBD.System
  656. remaining -= ramBD.User
  657. ramBD.Idle = remaining
  658. }
  659. if queryUsedLocalStorage != "" {
  660. resUsedLocalStorage, err := resChs[9].Await()
  661. if err != nil {
  662. return nil, err
  663. }
  664. for _, result := range resUsedLocalStorage {
  665. clusterID, _ := result.GetString("cluster_id")
  666. if clusterID == "" {
  667. clusterID = defaultClusterID
  668. }
  669. pvUsedCostMap[clusterID] += result.Values[0].Value
  670. }
  671. }
  672. }
  673. if ctx.ErrorCollector.IsError() {
  674. for _, err := range ctx.Errors() {
  675. log.Errorf("ComputeClusterCosts: %s", err)
  676. }
  677. return nil, ctx.Errors()[0]
  678. }
  679. // Convert intermediate structure to Costs instances
  680. costsByCluster := map[string]*ClusterCosts{}
  681. for id, cd := range costData {
  682. dataMins, ok := dataMinsByCluster[id]
  683. if !ok {
  684. dataMins = mins
  685. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  686. }
  687. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  688. if err != nil {
  689. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  690. return nil, err
  691. }
  692. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  693. costs.CPUBreakdown = cpuBD
  694. }
  695. if ramBD, ok := ramBreakdownMap[id]; ok {
  696. costs.RAMBreakdown = ramBD
  697. }
  698. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  699. if pvUC, ok := pvUsedCostMap[id]; ok {
  700. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  701. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  702. }
  703. costs.DataMinutes = dataMins
  704. costsByCluster[id] = costs
  705. }
  706. return costsByCluster, nil
  707. }
  708. type Totals struct {
  709. TotalCost [][]string `json:"totalcost"`
  710. CPUCost [][]string `json:"cpucost"`
  711. MemCost [][]string `json:"memcost"`
  712. StorageCost [][]string `json:"storageCost"`
  713. }
  714. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  715. if len(qrs) == 0 {
  716. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  717. }
  718. result := qrs[0]
  719. totals := [][]string{}
  720. for _, value := range result.Values {
  721. d0 := fmt.Sprintf("%f", value.Timestamp)
  722. d1 := fmt.Sprintf("%f", value.Value)
  723. toAppend := []string{
  724. d0,
  725. d1,
  726. }
  727. totals = append(totals, toAppend)
  728. }
  729. return totals, nil
  730. }
  731. // ClusterCostsOverTime gives the full cluster costs over time
  732. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  733. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  734. if localStorageQuery != "" {
  735. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  736. }
  737. layout := "2006-01-02T15:04:05.000Z"
  738. start, err := time.Parse(layout, startString)
  739. if err != nil {
  740. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  741. return nil, err
  742. }
  743. end, err := time.Parse(layout, endString)
  744. if err != nil {
  745. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  746. return nil, err
  747. }
  748. window, err := time.ParseDuration(windowString)
  749. if err != nil {
  750. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  751. return nil, err
  752. }
  753. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  754. if offset != "" {
  755. offset = fmt.Sprintf("offset %s", offset)
  756. }
  757. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  758. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  759. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  760. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  761. ctx := prom.NewContext(cli)
  762. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  763. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  764. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  765. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  766. resultClusterCores, err := resChClusterCores.Await()
  767. if err != nil {
  768. return nil, err
  769. }
  770. resultClusterRAM, err := resChClusterRAM.Await()
  771. if err != nil {
  772. return nil, err
  773. }
  774. resultStorage, err := resChStorage.Await()
  775. if err != nil {
  776. return nil, err
  777. }
  778. resultTotal, err := resChTotal.Await()
  779. if err != nil {
  780. return nil, err
  781. }
  782. coreTotal, err := resultToTotals(resultClusterCores)
  783. if err != nil {
  784. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  785. return nil, err
  786. }
  787. ramTotal, err := resultToTotals(resultClusterRAM)
  788. if err != nil {
  789. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  790. return nil, err
  791. }
  792. storageTotal, err := resultToTotals(resultStorage)
  793. if err != nil {
  794. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  795. }
  796. clusterTotal, err := resultToTotals(resultTotal)
  797. if err != nil {
  798. // If clusterTotal query failed, it's likely because there are no PVs, which
  799. // causes the qTotal query to return no data. Instead, query only node costs.
  800. // If that fails, return an error because something is actually wrong.
  801. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  802. resultNodes, err := ctx.QueryRangeSync(qNodes, start, end, window)
  803. if err != nil {
  804. return nil, err
  805. }
  806. clusterTotal, err = resultToTotals(resultNodes)
  807. if err != nil {
  808. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  809. return nil, err
  810. }
  811. }
  812. return &Totals{
  813. TotalCost: clusterTotal,
  814. CPUCost: coreTotal,
  815. MemCost: ramTotal,
  816. StorageCost: storageTotal,
  817. }, nil
  818. }