cluster.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. defaultClusterID := env.GetClusterID()
  527. dataMinsByCluster := map[string]float64{}
  528. for _, result := range resChs[0].Await() {
  529. clusterID, _ := result.GetString("cluster_id")
  530. if clusterID == "" {
  531. clusterID = defaultClusterID
  532. }
  533. dataMins := mins
  534. if len(result.Values) > 0 {
  535. dataMins = result.Values[0].Value
  536. } else {
  537. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  538. }
  539. dataMinsByCluster[clusterID] = dataMins
  540. }
  541. // Determine combined discount
  542. discount, customDiscount := 0.0, 0.0
  543. c, err := A.Cloud.GetConfig()
  544. if err == nil {
  545. discount, err = ParsePercentString(c.Discount)
  546. if err != nil {
  547. discount = 0.0
  548. }
  549. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  550. if err != nil {
  551. customDiscount = 0.0
  552. }
  553. }
  554. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  555. costData := make(map[string]map[string]float64)
  556. // Helper function to iterate over Prom query results, parsing the raw values into
  557. // the intermediate costData structure.
  558. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  559. for _, result := range results {
  560. clusterID, _ := result.GetString("cluster_id")
  561. if clusterID == "" {
  562. clusterID = defaultClusterID
  563. }
  564. if _, ok := costData[clusterID]; !ok {
  565. costData[clusterID] = map[string]float64{}
  566. }
  567. if len(result.Values) > 0 {
  568. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  569. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  570. }
  571. }
  572. }
  573. // Apply both sustained use and custom discounts to RAM and CPU
  574. setCostsFromResults(costData, resChs[2].Await(), "cpu", discount, customDiscount)
  575. setCostsFromResults(costData, resChs[3].Await(), "ram", discount, customDiscount)
  576. // Apply only custom discount to GPU and storage
  577. setCostsFromResults(costData, resChs[1].Await(), "gpu", 0.0, customDiscount)
  578. setCostsFromResults(costData, resChs[4].Await(), "storage", 0.0, customDiscount)
  579. if queryTotalLocalStorage != "" {
  580. setCostsFromResults(costData, resChs[5].Await(), "localstorage", 0.0, customDiscount)
  581. }
  582. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  583. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  584. pvUsedCostMap := map[string]float64{}
  585. if withBreakdown {
  586. for _, result := range resChs[6].Await() {
  587. clusterID, _ := result.GetString("cluster_id")
  588. if clusterID == "" {
  589. clusterID = defaultClusterID
  590. }
  591. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  592. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  593. }
  594. cpuBD := cpuBreakdownMap[clusterID]
  595. mode, err := result.GetString("mode")
  596. if err != nil {
  597. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  598. mode = "other"
  599. }
  600. switch mode {
  601. case "idle":
  602. cpuBD.Idle += result.Values[0].Value
  603. case "system":
  604. cpuBD.System += result.Values[0].Value
  605. case "user":
  606. cpuBD.User += result.Values[0].Value
  607. default:
  608. cpuBD.Other += result.Values[0].Value
  609. }
  610. }
  611. for _, result := range resChs[7].Await() {
  612. clusterID, _ := result.GetString("cluster_id")
  613. if clusterID == "" {
  614. clusterID = defaultClusterID
  615. }
  616. if _, ok := ramBreakdownMap[clusterID]; !ok {
  617. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  618. }
  619. ramBD := ramBreakdownMap[clusterID]
  620. ramBD.System += result.Values[0].Value
  621. }
  622. for _, result := range resChs[8].Await() {
  623. clusterID, _ := result.GetString("cluster_id")
  624. if clusterID == "" {
  625. clusterID = defaultClusterID
  626. }
  627. if _, ok := ramBreakdownMap[clusterID]; !ok {
  628. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  629. }
  630. ramBD := ramBreakdownMap[clusterID]
  631. ramBD.User += result.Values[0].Value
  632. }
  633. for _, ramBD := range ramBreakdownMap {
  634. remaining := 1.0
  635. remaining -= ramBD.Other
  636. remaining -= ramBD.System
  637. remaining -= ramBD.User
  638. ramBD.Idle = remaining
  639. }
  640. if queryUsedLocalStorage != "" {
  641. for _, result := range resChs[9].Await() {
  642. clusterID, _ := result.GetString("cluster_id")
  643. if clusterID == "" {
  644. clusterID = defaultClusterID
  645. }
  646. pvUsedCostMap[clusterID] += result.Values[0].Value
  647. }
  648. }
  649. }
  650. if ctx.ErrorCollector.IsError() {
  651. for _, err := range ctx.Errors() {
  652. log.Errorf("ComputeClusterCosts: %s", err)
  653. }
  654. return nil, ctx.Errors()[0]
  655. }
  656. // Convert intermediate structure to Costs instances
  657. costsByCluster := map[string]*ClusterCosts{}
  658. for id, cd := range costData {
  659. dataMins, ok := dataMinsByCluster[id]
  660. if !ok {
  661. dataMins = mins
  662. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  663. }
  664. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  665. if err != nil {
  666. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  667. return nil, err
  668. }
  669. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  670. costs.CPUBreakdown = cpuBD
  671. }
  672. if ramBD, ok := ramBreakdownMap[id]; ok {
  673. costs.RAMBreakdown = ramBD
  674. }
  675. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  676. if pvUC, ok := pvUsedCostMap[id]; ok {
  677. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  678. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  679. }
  680. costs.DataMinutes = dataMins
  681. costsByCluster[id] = costs
  682. }
  683. return costsByCluster, nil
  684. }
  685. type Totals struct {
  686. TotalCost [][]string `json:"totalcost"`
  687. CPUCost [][]string `json:"cpucost"`
  688. MemCost [][]string `json:"memcost"`
  689. StorageCost [][]string `json:"storageCost"`
  690. }
  691. func resultToTotals(qr interface{}) ([][]string, error) {
  692. // TODO: Provide an actual query instead of resultToTotals
  693. qResults, err := prom.NewQueryResults("resultToTotals", qr)
  694. if err != nil {
  695. return nil, err
  696. }
  697. results := qResults.Results
  698. if len(results) == 0 {
  699. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  700. }
  701. result := results[0]
  702. totals := [][]string{}
  703. for _, value := range result.Values {
  704. d0 := fmt.Sprintf("%f", value.Timestamp)
  705. d1 := fmt.Sprintf("%f", value.Value)
  706. toAppend := []string{
  707. d0,
  708. d1,
  709. }
  710. totals = append(totals, toAppend)
  711. }
  712. return totals, nil
  713. }
  714. // ClusterCostsOverTime gives the full cluster costs over time
  715. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  716. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  717. if localStorageQuery != "" {
  718. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  719. }
  720. layout := "2006-01-02T15:04:05.000Z"
  721. start, err := time.Parse(layout, startString)
  722. if err != nil {
  723. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  724. return nil, err
  725. }
  726. end, err := time.Parse(layout, endString)
  727. if err != nil {
  728. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  729. return nil, err
  730. }
  731. window, err := time.ParseDuration(windowString)
  732. if err != nil {
  733. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  734. return nil, err
  735. }
  736. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  737. if offset != "" {
  738. offset = fmt.Sprintf("offset %s", offset)
  739. }
  740. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  741. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  742. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  743. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  744. resultClusterCores, err := QueryRange(cli, qCores, start, end, window)
  745. if err != nil {
  746. return nil, err
  747. }
  748. resultClusterRAM, err := QueryRange(cli, qRAM, start, end, window)
  749. if err != nil {
  750. return nil, err
  751. }
  752. resultStorage, err := QueryRange(cli, qStorage, start, end, window)
  753. if err != nil {
  754. return nil, err
  755. }
  756. resultTotal, err := QueryRange(cli, qTotal, start, end, window)
  757. if err != nil {
  758. return nil, err
  759. }
  760. coreTotal, err := resultToTotals(resultClusterCores)
  761. if err != nil {
  762. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  763. return nil, err
  764. }
  765. ramTotal, err := resultToTotals(resultClusterRAM)
  766. if err != nil {
  767. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  768. return nil, err
  769. }
  770. storageTotal, err := resultToTotals(resultStorage)
  771. if err != nil {
  772. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  773. }
  774. clusterTotal, err := resultToTotals(resultTotal)
  775. if err != nil {
  776. // If clusterTotal query failed, it's likely because there are no PVs, which
  777. // causes the qTotal query to return no data. Instead, query only node costs.
  778. // If that fails, return an error because something is actually wrong.
  779. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  780. resultNodes, err := QueryRange(cli, qNodes, start, end, window)
  781. if err != nil {
  782. return nil, err
  783. }
  784. clusterTotal, err = resultToTotals(resultNodes)
  785. if err != nil {
  786. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  787. return nil, err
  788. }
  789. }
  790. return &Totals{
  791. TotalCost: clusterTotal,
  792. CPUCost: coreTotal,
  793. MemCost: ramTotal,
  794. StorageCost: storageTotal,
  795. }, nil
  796. }