cluster.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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 := 1
  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 := 1
  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))[%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))[%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))[%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, err := result.GetString("instance_type")
  281. if err != nil {
  282. log.Warningf("ClusterNodes: CPU cost data missing node type")
  283. }
  284. cpuCost := result.Values[0].Value
  285. key := fmt.Sprintf("%s/%s", cluster, name)
  286. if _, ok := nodeMap[key]; !ok {
  287. nodeMap[key] = &Node{
  288. Cluster: cluster,
  289. Name: name,
  290. NodeType: nodeType,
  291. }
  292. }
  293. nodeMap[key].CPUCost = cpuCost
  294. nodeMap[key].NodeType = nodeType
  295. }
  296. for _, result := range resNodeCPUCores {
  297. cluster, err := result.GetString("cluster_id")
  298. if err != nil {
  299. cluster = env.GetClusterID()
  300. }
  301. name, err := result.GetString("node")
  302. if err != nil {
  303. log.Warningf("ClusterNodes: CPU cores data missing node")
  304. continue
  305. }
  306. cpuCores := result.Values[0].Value
  307. key := fmt.Sprintf("%s/%s", cluster, name)
  308. if _, ok := nodeMap[key]; !ok {
  309. nodeMap[key] = &Node{
  310. Cluster: cluster,
  311. Name: name,
  312. }
  313. }
  314. nodeMap[key].CPUCores = cpuCores
  315. }
  316. for _, result := range resNodeRAMCost {
  317. cluster, err := result.GetString("cluster_id")
  318. if err != nil {
  319. cluster = env.GetClusterID()
  320. }
  321. name, err := result.GetString("node")
  322. if err != nil {
  323. log.Warningf("ClusterNodes: RAM cost data missing node")
  324. continue
  325. }
  326. nodeType, err := result.GetString("instance_type")
  327. if err != nil {
  328. log.Warningf("ClusterNodes: RAM cost data missing node type")
  329. }
  330. ramCost := result.Values[0].Value
  331. key := fmt.Sprintf("%s/%s", cluster, name)
  332. if _, ok := nodeMap[key]; !ok {
  333. nodeMap[key] = &Node{
  334. Cluster: cluster,
  335. Name: name,
  336. NodeType: nodeType,
  337. }
  338. }
  339. nodeMap[key].RAMCost = ramCost
  340. nodeMap[key].NodeType = nodeType
  341. }
  342. for _, result := range resNodeRAMBytes {
  343. cluster, err := result.GetString("cluster_id")
  344. if err != nil {
  345. cluster = env.GetClusterID()
  346. }
  347. name, err := result.GetString("node")
  348. if err != nil {
  349. log.Warningf("ClusterNodes: RAM bytes data missing node")
  350. continue
  351. }
  352. ramBytes := result.Values[0].Value
  353. key := fmt.Sprintf("%s/%s", cluster, name)
  354. if _, ok := nodeMap[key]; !ok {
  355. nodeMap[key] = &Node{
  356. Cluster: cluster,
  357. Name: name,
  358. }
  359. }
  360. nodeMap[key].RAMBytes = ramBytes
  361. }
  362. for _, result := range resNodeGPUCost {
  363. cluster, err := result.GetString("cluster_id")
  364. if err != nil {
  365. cluster = env.GetClusterID()
  366. }
  367. name, err := result.GetString("node")
  368. if err != nil {
  369. log.Warningf("ClusterNodes: GPU cost data missing node")
  370. continue
  371. }
  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. }
  379. }
  380. nodeMap[key].GPUCost = gpuCost
  381. }
  382. // node_labels label_cloud_google_com_gke_preemptible
  383. for _, result := range resNodeLabels {
  384. nodeName, err := result.GetString("node")
  385. if err != nil {
  386. continue
  387. }
  388. // GCP preemptible label
  389. pre, _ := result.GetString("label_cloud_google_com_gke_preemptible")
  390. if node, ok := nodeMap[nodeName]; pre == "true" && ok {
  391. node.Preemptible = true
  392. }
  393. // TODO AWS preemptible
  394. // TODO Azure preemptible
  395. }
  396. c, err := cp.GetConfig()
  397. if err != nil {
  398. return nil, []error{err}
  399. }
  400. discount, err := ParsePercentString(c.Discount)
  401. if err != nil {
  402. return nil, []error{err}
  403. }
  404. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  405. if err != nil {
  406. return nil, []error{err}
  407. }
  408. for _, node := range nodeMap {
  409. if !node.Preemptible {
  410. // TODO determine discount(s) based on:
  411. // - custom settings
  412. // - node RI data
  413. // - provider-specific rules, e.g.
  414. // cp.GetDiscount(instanceType string) float64
  415. node.Discount = (1.0 - (1.0-discount)*(1.0-negotiatedDiscount))
  416. }
  417. }
  418. return nodeMap, nil
  419. }
  420. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  421. func ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  422. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  423. start, end, err := util.ParseTimeRange(window, offset)
  424. if err != nil {
  425. return nil, err
  426. }
  427. mins := end.Sub(*start).Minutes()
  428. // minsPerResolution determines accuracy and resource use for the following
  429. // queries. Smaller values (higher resolution) result in better accuracy,
  430. // but more expensive queries, and vice-a-versa.
  431. minsPerResolution := 5
  432. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  433. // value, converts it to a cumulative value; i.e.
  434. // [$/hr] * [min/res]*[hr/min] = [$/res]
  435. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  436. const fmtQueryDataCount = `
  437. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  438. `
  439. const fmtQueryTotalGPU = `
  440. sum(
  441. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  442. ) by (cluster_id)
  443. `
  444. const fmtQueryTotalCPU = `
  445. sum(
  446. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  447. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  448. ) by (cluster_id)
  449. `
  450. const fmtQueryTotalRAM = `
  451. sum(
  452. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  453. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  454. ) by (cluster_id)
  455. `
  456. const fmtQueryTotalStorage = `
  457. sum(
  458. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  459. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  460. ) by (cluster_id)
  461. `
  462. const fmtQueryCPUModePct = `
  463. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  464. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  465. `
  466. const fmtQueryRAMSystemPct = `
  467. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%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. const fmtQueryRAMUserPct = `
  471. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  472. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  473. `
  474. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  475. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  476. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  477. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  478. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  479. if queryTotalLocalStorage != "" {
  480. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  481. }
  482. fmtOffset := ""
  483. if offset != "" {
  484. fmtOffset = fmt.Sprintf("offset %s", offset)
  485. }
  486. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  487. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  488. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  489. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  490. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  491. ctx := prom.NewContext(client)
  492. resChs := ctx.QueryAll(
  493. queryDataCount,
  494. queryTotalGPU,
  495. queryTotalCPU,
  496. queryTotalRAM,
  497. queryTotalStorage,
  498. )
  499. // Only submit the local storage query if it is valid. Otherwise Prometheus
  500. // will return errors. Always append something to resChs, regardless, to
  501. // maintain indexing.
  502. if queryTotalLocalStorage != "" {
  503. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  504. } else {
  505. resChs = append(resChs, nil)
  506. }
  507. if withBreakdown {
  508. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  509. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  510. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  511. bdResChs := ctx.QueryAll(
  512. queryCPUModePct,
  513. queryRAMSystemPct,
  514. queryRAMUserPct,
  515. )
  516. // Only submit the local storage query if it is valid. Otherwise Prometheus
  517. // will return errors. Always append something to resChs, regardless, to
  518. // maintain indexing.
  519. if queryUsedLocalStorage != "" {
  520. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  521. } else {
  522. bdResChs = append(bdResChs, nil)
  523. }
  524. resChs = append(resChs, bdResChs...)
  525. }
  526. resDataCount, _ := resChs[0].Await()
  527. resTotalGPU, _ := resChs[1].Await()
  528. resTotalCPU, _ := resChs[2].Await()
  529. resTotalRAM, _ := resChs[3].Await()
  530. resTotalStorage, _ := resChs[4].Await()
  531. resTotalLocalStorage, _ := resChs[5].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. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  590. }
  591. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  592. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  593. pvUsedCostMap := map[string]float64{}
  594. if withBreakdown {
  595. resCPUModePct, _ := resChs[6].Await()
  596. resRAMSystemPct, _ := resChs[7].Await()
  597. resRAMUserPct, _ := resChs[8].Await()
  598. resUsedLocalStorage, _ := resChs[9].Await()
  599. if ctx.HasErrors() {
  600. return nil, ctx.Errors()[0]
  601. }
  602. for _, result := range resCPUModePct {
  603. clusterID, _ := result.GetString("cluster_id")
  604. if clusterID == "" {
  605. clusterID = defaultClusterID
  606. }
  607. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  608. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  609. }
  610. cpuBD := cpuBreakdownMap[clusterID]
  611. mode, err := result.GetString("mode")
  612. if err != nil {
  613. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  614. mode = "other"
  615. }
  616. switch mode {
  617. case "idle":
  618. cpuBD.Idle += result.Values[0].Value
  619. case "system":
  620. cpuBD.System += result.Values[0].Value
  621. case "user":
  622. cpuBD.User += result.Values[0].Value
  623. default:
  624. cpuBD.Other += result.Values[0].Value
  625. }
  626. }
  627. for _, result := range resRAMSystemPct {
  628. clusterID, _ := result.GetString("cluster_id")
  629. if clusterID == "" {
  630. clusterID = defaultClusterID
  631. }
  632. if _, ok := ramBreakdownMap[clusterID]; !ok {
  633. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  634. }
  635. ramBD := ramBreakdownMap[clusterID]
  636. ramBD.System += result.Values[0].Value
  637. }
  638. for _, result := range resRAMUserPct {
  639. clusterID, _ := result.GetString("cluster_id")
  640. if clusterID == "" {
  641. clusterID = defaultClusterID
  642. }
  643. if _, ok := ramBreakdownMap[clusterID]; !ok {
  644. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  645. }
  646. ramBD := ramBreakdownMap[clusterID]
  647. ramBD.User += result.Values[0].Value
  648. }
  649. for _, ramBD := range ramBreakdownMap {
  650. remaining := 1.0
  651. remaining -= ramBD.Other
  652. remaining -= ramBD.System
  653. remaining -= ramBD.User
  654. ramBD.Idle = remaining
  655. }
  656. if queryUsedLocalStorage != "" {
  657. for _, result := range resUsedLocalStorage {
  658. clusterID, _ := result.GetString("cluster_id")
  659. if clusterID == "" {
  660. clusterID = defaultClusterID
  661. }
  662. pvUsedCostMap[clusterID] += result.Values[0].Value
  663. }
  664. }
  665. }
  666. if ctx.ErrorCollector.IsError() {
  667. for _, err := range ctx.Errors() {
  668. log.Errorf("ComputeClusterCosts: %s", err)
  669. }
  670. return nil, ctx.Errors()[0]
  671. }
  672. // Convert intermediate structure to Costs instances
  673. costsByCluster := map[string]*ClusterCosts{}
  674. for id, cd := range costData {
  675. dataMins, ok := dataMinsByCluster[id]
  676. if !ok {
  677. dataMins = mins
  678. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  679. }
  680. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  681. if err != nil {
  682. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  683. return nil, err
  684. }
  685. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  686. costs.CPUBreakdown = cpuBD
  687. }
  688. if ramBD, ok := ramBreakdownMap[id]; ok {
  689. costs.RAMBreakdown = ramBD
  690. }
  691. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  692. if pvUC, ok := pvUsedCostMap[id]; ok {
  693. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  694. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  695. }
  696. costs.DataMinutes = dataMins
  697. costsByCluster[id] = costs
  698. }
  699. return costsByCluster, nil
  700. }
  701. type Totals struct {
  702. TotalCost [][]string `json:"totalcost"`
  703. CPUCost [][]string `json:"cpucost"`
  704. MemCost [][]string `json:"memcost"`
  705. StorageCost [][]string `json:"storageCost"`
  706. }
  707. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  708. if len(qrs) == 0 {
  709. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  710. }
  711. result := qrs[0]
  712. totals := [][]string{}
  713. for _, value := range result.Values {
  714. d0 := fmt.Sprintf("%f", value.Timestamp)
  715. d1 := fmt.Sprintf("%f", value.Value)
  716. toAppend := []string{
  717. d0,
  718. d1,
  719. }
  720. totals = append(totals, toAppend)
  721. }
  722. return totals, nil
  723. }
  724. // ClusterCostsOverTime gives the full cluster costs over time
  725. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  726. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  727. if localStorageQuery != "" {
  728. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  729. }
  730. layout := "2006-01-02T15:04:05.000Z"
  731. start, err := time.Parse(layout, startString)
  732. if err != nil {
  733. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  734. return nil, err
  735. }
  736. end, err := time.Parse(layout, endString)
  737. if err != nil {
  738. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  739. return nil, err
  740. }
  741. window, err := time.ParseDuration(windowString)
  742. if err != nil {
  743. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  744. return nil, err
  745. }
  746. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  747. if offset != "" {
  748. offset = fmt.Sprintf("offset %s", offset)
  749. }
  750. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  751. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  752. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  753. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  754. ctx := prom.NewContext(cli)
  755. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  756. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  757. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  758. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  759. resultClusterCores, err := resChClusterCores.Await()
  760. if err != nil {
  761. return nil, err
  762. }
  763. resultClusterRAM, err := resChClusterRAM.Await()
  764. if err != nil {
  765. return nil, err
  766. }
  767. resultStorage, err := resChStorage.Await()
  768. if err != nil {
  769. return nil, err
  770. }
  771. resultTotal, err := resChTotal.Await()
  772. if err != nil {
  773. return nil, err
  774. }
  775. coreTotal, err := resultToTotals(resultClusterCores)
  776. if err != nil {
  777. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  778. return nil, err
  779. }
  780. ramTotal, err := resultToTotals(resultClusterRAM)
  781. if err != nil {
  782. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  783. return nil, err
  784. }
  785. storageTotal, err := resultToTotals(resultStorage)
  786. if err != nil {
  787. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  788. }
  789. clusterTotal, err := resultToTotals(resultTotal)
  790. if err != nil {
  791. // If clusterTotal query failed, it's likely because there are no PVs, which
  792. // causes the qTotal query to return no data. Instead, query only node costs.
  793. // If that fails, return an error because something is actually wrong.
  794. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  795. resultNodes, err := ctx.QueryRangeSync(qNodes, start, end, window)
  796. if err != nil {
  797. return nil, err
  798. }
  799. clusterTotal, err = resultToTotals(resultNodes)
  800. if err != nil {
  801. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  802. return nil, err
  803. }
  804. }
  805. return &Totals{
  806. TotalCost: clusterTotal,
  807. CPUCost: coreTotal,
  808. MemCost: ramTotal,
  809. StorageCost: storageTotal,
  810. }, nil
  811. }