cluster.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/kubecost/cost-model/pkg/cloud"
  6. "github.com/kubecost/cost-model/pkg/env"
  7. "github.com/kubecost/cost-model/pkg/log"
  8. "github.com/kubecost/cost-model/pkg/prom"
  9. "github.com/kubecost/cost-model/pkg/util"
  10. prometheus "github.com/prometheus/client_golang/api"
  11. "k8s.io/klog"
  12. )
  13. const (
  14. queryClusterCores = `sum(
  15. avg(avg_over_time(kube_node_status_capacity_cpu_cores[%s] %s)) by (node, cluster_id) * avg(avg_over_time(node_cpu_hourly_cost[%s] %s)) by (node, cluster_id) * 730 +
  16. avg(avg_over_time(node_gpu_hourly_cost[%s] %s)) by (node, cluster_id) * 730
  17. ) by (cluster_id)`
  18. queryClusterRAM = `sum(
  19. avg(avg_over_time(kube_node_status_capacity_memory_bytes[%s] %s)) by (node, cluster_id) / 1024 / 1024 / 1024 * avg(avg_over_time(node_ram_hourly_cost[%s] %s)) by (node, cluster_id) * 730
  20. ) by (cluster_id)`
  21. queryStorage = `sum(
  22. avg(avg_over_time(pv_hourly_cost[%s] %s)) by (persistentvolume, cluster_id) * 730
  23. * avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s] %s)) by (persistentvolume, cluster_id) / 1024 / 1024 / 1024
  24. ) by (cluster_id) %s`
  25. queryTotal = `sum(avg(node_total_hourly_cost) by (node, cluster_id)) * 730 +
  26. sum(
  27. avg(avg_over_time(pv_hourly_cost[1h])) by (persistentvolume, cluster_id) * 730
  28. * avg(avg_over_time(kube_persistentvolume_capacity_bytes[1h])) by (persistentvolume, cluster_id) / 1024 / 1024 / 1024
  29. ) by (cluster_id) %s`
  30. queryNodes = `sum(avg(node_total_hourly_cost) by (node, cluster_id)) * 730 %s`
  31. )
  32. // Costs represents cumulative and monthly cluster costs over a given duration. Costs
  33. // are broken down by cores, memory, and storage.
  34. type ClusterCosts struct {
  35. Start *time.Time `json:"startTime"`
  36. End *time.Time `json:"endTime"`
  37. CPUCumulative float64 `json:"cpuCumulativeCost"`
  38. CPUMonthly float64 `json:"cpuMonthlyCost"`
  39. CPUBreakdown *ClusterCostsBreakdown `json:"cpuBreakdown"`
  40. GPUCumulative float64 `json:"gpuCumulativeCost"`
  41. GPUMonthly float64 `json:"gpuMonthlyCost"`
  42. RAMCumulative float64 `json:"ramCumulativeCost"`
  43. RAMMonthly float64 `json:"ramMonthlyCost"`
  44. RAMBreakdown *ClusterCostsBreakdown `json:"ramBreakdown"`
  45. StorageCumulative float64 `json:"storageCumulativeCost"`
  46. StorageMonthly float64 `json:"storageMonthlyCost"`
  47. StorageBreakdown *ClusterCostsBreakdown `json:"storageBreakdown"`
  48. TotalCumulative float64 `json:"totalCumulativeCost"`
  49. TotalMonthly float64 `json:"totalMonthlyCost"`
  50. DataMinutes float64
  51. }
  52. // ClusterCostsBreakdown provides percentage-based breakdown of a resource by
  53. // categories: user for user-space (i.e. non-system) usage, system, and idle.
  54. type ClusterCostsBreakdown struct {
  55. Idle float64 `json:"idle"`
  56. Other float64 `json:"other"`
  57. System float64 `json:"system"`
  58. User float64 `json:"user"`
  59. }
  60. // NewClusterCostsFromCumulative takes cumulative cost data over a given time range, computes
  61. // the associated monthly rate data, and returns the Costs.
  62. func NewClusterCostsFromCumulative(cpu, gpu, ram, storage float64, window, offset string, dataHours float64) (*ClusterCosts, error) {
  63. start, end, err := util.ParseTimeRange(window, offset)
  64. if err != nil {
  65. return nil, err
  66. }
  67. // If the number of hours is not given (i.e. is zero) compute one from the window and offset
  68. if dataHours == 0 {
  69. dataHours = end.Sub(*start).Hours()
  70. }
  71. // Do not allow zero-length windows to prevent divide-by-zero issues
  72. if dataHours == 0 {
  73. return nil, fmt.Errorf("illegal time range: window %s, offset %s", window, offset)
  74. }
  75. cc := &ClusterCosts{
  76. Start: start,
  77. End: end,
  78. CPUCumulative: cpu,
  79. GPUCumulative: gpu,
  80. RAMCumulative: ram,
  81. StorageCumulative: storage,
  82. TotalCumulative: cpu + gpu + ram + storage,
  83. CPUMonthly: cpu / dataHours * (util.HoursPerMonth),
  84. GPUMonthly: gpu / dataHours * (util.HoursPerMonth),
  85. RAMMonthly: ram / dataHours * (util.HoursPerMonth),
  86. StorageMonthly: storage / dataHours * (util.HoursPerMonth),
  87. }
  88. cc.TotalMonthly = cc.CPUMonthly + cc.GPUMonthly + cc.RAMMonthly + cc.StorageMonthly
  89. return cc, nil
  90. }
  91. type Disk struct {
  92. Cluster string
  93. Name string
  94. ProviderID string
  95. Cost float64
  96. Bytes float64
  97. Local bool
  98. Start time.Time
  99. End time.Time
  100. Minutes float64
  101. Breakdown *ClusterCostsBreakdown
  102. }
  103. func ClusterDisks(client prometheus.Client, provider cloud.Provider, duration, offset time.Duration) (map[string]*Disk, error) {
  104. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  105. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  106. if offset < time.Minute {
  107. offsetStr = ""
  108. }
  109. // minsPerResolution determines accuracy and resource use for the following
  110. // queries. Smaller values (higher resolution) result in better accuracy,
  111. // but more expensive queries, and vice-a-versa.
  112. minsPerResolution := 1
  113. resolution := time.Duration(minsPerResolution) * time.Minute
  114. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  115. // value, converts it to a cumulative value; i.e.
  116. // [$/hr] * [min/res]*[hr/min] = [$/res]
  117. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  118. // TODO niko/assets how do we not hard-code this price?
  119. costPerGBHr := 0.04 / 730.0
  120. ctx := prom.NewContext(client)
  121. queryPVCost := fmt.Sprintf(`sum_over_time((avg(kube_persistentvolume_capacity_bytes) by (cluster_id, persistentvolume) * on(cluster_id, persistentvolume) group_right avg(pv_hourly_cost) by (cluster_id, persistentvolume,provider_id))[%s:%dm]%s)/1024/1024/1024 * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  122. queryPVSize := fmt.Sprintf(`avg_over_time(kube_persistentvolume_capacity_bytes[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  123. queryActiveMins := fmt.Sprintf(`count(pv_hourly_cost) by (cluster_id, persistentvolume)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  124. queryLocalStorageCost := fmt.Sprintf(`sum_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 * %f * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative, costPerGBHr)
  125. queryLocalStorageUsedCost := fmt.Sprintf(`sum_over_time(sum(container_fs_usage_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 * %f * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative, costPerGBHr)
  126. queryLocalStorageBytes := fmt.Sprintf(`avg_over_time(sum(container_fs_limit_bytes{device!="tmpfs", id="/"}) by (instance, cluster_id)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  127. queryLocalActiveMins := fmt.Sprintf(`count(node_total_hourly_cost) by (cluster_id, node)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  128. resChPVCost := ctx.Query(queryPVCost)
  129. resChPVSize := ctx.Query(queryPVSize)
  130. resChActiveMins := ctx.Query(queryActiveMins)
  131. resChLocalStorageCost := ctx.Query(queryLocalStorageCost)
  132. resChLocalStorageUsedCost := ctx.Query(queryLocalStorageUsedCost)
  133. resChLocalStorageBytes := ctx.Query(queryLocalStorageBytes)
  134. resChLocalActiveMins := ctx.Query(queryLocalActiveMins)
  135. resPVCost, _ := resChPVCost.Await()
  136. resPVSize, _ := resChPVSize.Await()
  137. resActiveMins, _ := resChActiveMins.Await()
  138. resLocalStorageCost, _ := resChLocalStorageCost.Await()
  139. resLocalStorageUsedCost, _ := resChLocalStorageUsedCost.Await()
  140. resLocalStorageBytes, _ := resChLocalStorageBytes.Await()
  141. resLocalActiveMins, _ := resChLocalActiveMins.Await()
  142. if ctx.HasErrors() {
  143. return nil, ctx.ErrorCollection()
  144. }
  145. diskMap := map[string]*Disk{}
  146. for _, result := range resPVCost {
  147. cluster, err := result.GetString("cluster_id")
  148. if err != nil {
  149. cluster = env.GetClusterID()
  150. }
  151. name, err := result.GetString("persistentvolume")
  152. if err != nil {
  153. log.Warningf("ClusterDisks: PV cost data missing persistentvolume")
  154. continue
  155. }
  156. // TODO niko/assets storage class
  157. cost := result.Values[0].Value
  158. key := fmt.Sprintf("%s/%s", cluster, name)
  159. if _, ok := diskMap[key]; !ok {
  160. diskMap[key] = &Disk{
  161. Cluster: cluster,
  162. Name: name,
  163. Breakdown: &ClusterCostsBreakdown{},
  164. }
  165. }
  166. diskMap[key].Cost += cost
  167. providerID, _ := result.GetString("provider_id") // just put the providerID set up here, it's the simplest query.
  168. if providerID != "" {
  169. diskMap[key].ProviderID = provider.ParsePVID(providerID)
  170. }
  171. }
  172. for _, result := range resPVSize {
  173. cluster, err := result.GetString("cluster_id")
  174. if err != nil {
  175. cluster = env.GetClusterID()
  176. }
  177. name, err := result.GetString("persistentvolume")
  178. if err != nil {
  179. log.Warningf("ClusterDisks: PV size data missing persistentvolume")
  180. continue
  181. }
  182. // TODO niko/assets storage class
  183. bytes := result.Values[0].Value
  184. key := fmt.Sprintf("%s/%s", cluster, name)
  185. if _, ok := diskMap[key]; !ok {
  186. diskMap[key] = &Disk{
  187. Cluster: cluster,
  188. Name: name,
  189. Breakdown: &ClusterCostsBreakdown{},
  190. }
  191. }
  192. diskMap[key].Bytes = bytes
  193. }
  194. for _, result := range resLocalStorageCost {
  195. cluster, err := result.GetString("cluster_id")
  196. if err != nil {
  197. cluster = env.GetClusterID()
  198. }
  199. name, err := result.GetString("instance")
  200. if err != nil {
  201. log.Warningf("ClusterDisks: local storage data missing instance")
  202. continue
  203. }
  204. cost := result.Values[0].Value
  205. key := fmt.Sprintf("%s/%s", cluster, name)
  206. if _, ok := diskMap[key]; !ok {
  207. diskMap[key] = &Disk{
  208. Cluster: cluster,
  209. Name: name,
  210. Breakdown: &ClusterCostsBreakdown{},
  211. Local: true,
  212. }
  213. }
  214. diskMap[key].Cost += cost
  215. }
  216. for _, result := range resLocalStorageUsedCost {
  217. cluster, err := result.GetString("cluster_id")
  218. if err != nil {
  219. cluster = env.GetClusterID()
  220. }
  221. name, err := result.GetString("instance")
  222. if err != nil {
  223. log.Warningf("ClusterDisks: local storage usage data missing instance")
  224. continue
  225. }
  226. cost := result.Values[0].Value
  227. key := fmt.Sprintf("%s/%s", cluster, name)
  228. if _, ok := diskMap[key]; !ok {
  229. diskMap[key] = &Disk{
  230. Cluster: cluster,
  231. Name: name,
  232. Breakdown: &ClusterCostsBreakdown{},
  233. Local: true,
  234. }
  235. }
  236. diskMap[key].Breakdown.System = cost / diskMap[key].Cost
  237. }
  238. for _, result := range resLocalStorageBytes {
  239. cluster, err := result.GetString("cluster_id")
  240. if err != nil {
  241. cluster = env.GetClusterID()
  242. }
  243. name, err := result.GetString("instance")
  244. if err != nil {
  245. log.Warningf("ClusterDisks: local storage data missing instance")
  246. continue
  247. }
  248. bytes := result.Values[0].Value
  249. key := fmt.Sprintf("%s/%s", cluster, name)
  250. if _, ok := diskMap[key]; !ok {
  251. diskMap[key] = &Disk{
  252. Cluster: cluster,
  253. Name: name,
  254. Breakdown: &ClusterCostsBreakdown{},
  255. Local: true,
  256. }
  257. }
  258. diskMap[key].Bytes = bytes
  259. }
  260. for _, result := range resActiveMins {
  261. cluster, err := result.GetString("cluster_id")
  262. if err != nil {
  263. cluster = env.GetClusterID()
  264. }
  265. name, err := result.GetString("persistentvolume")
  266. if err != nil {
  267. log.Warningf("ClusterDisks: active mins missing instance")
  268. continue
  269. }
  270. key := fmt.Sprintf("%s/%s", cluster, name)
  271. if _, ok := diskMap[key]; !ok {
  272. log.Warningf("ClusterDisks: active mins for unidentified disk")
  273. continue
  274. }
  275. if len(result.Values) == 0 {
  276. continue
  277. }
  278. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  279. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  280. mins := e.Sub(s).Minutes()
  281. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  282. diskMap[key].End = e
  283. diskMap[key].Start = s
  284. diskMap[key].Minutes = mins
  285. }
  286. for _, result := range resLocalActiveMins {
  287. cluster, err := result.GetString("cluster_id")
  288. if err != nil {
  289. cluster = env.GetClusterID()
  290. }
  291. name, err := result.GetString("node")
  292. if err != nil {
  293. log.Warningf("ClusterDisks: local active mins data missing instance")
  294. continue
  295. }
  296. key := fmt.Sprintf("%s/%s", cluster, name)
  297. if _, ok := diskMap[key]; !ok {
  298. log.Warningf("ClusterDisks: local active mins for unidentified disk")
  299. continue
  300. }
  301. if len(result.Values) == 0 {
  302. continue
  303. }
  304. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  305. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  306. mins := e.Sub(s).Minutes()
  307. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  308. diskMap[key].End = e
  309. diskMap[key].Start = s
  310. diskMap[key].Minutes = mins
  311. }
  312. for _, disk := range diskMap {
  313. // Apply all remaining RAM to Idle
  314. disk.Breakdown.Idle = 1.0 - (disk.Breakdown.System + disk.Breakdown.Other + disk.Breakdown.User)
  315. // Set provider Id to the name for reconciliation on Azure
  316. if fmt.Sprintf("%T", provider) == "*provider.Azure"{
  317. if disk.ProviderID == "" {
  318. disk.ProviderID = disk.Name
  319. }
  320. }
  321. }
  322. return diskMap, nil
  323. }
  324. type Node struct {
  325. Cluster string
  326. Name string
  327. ProviderID string
  328. NodeType string
  329. CPUCost float64
  330. CPUCores float64
  331. GPUCost float64
  332. RAMCost float64
  333. RAMBytes float64
  334. Discount float64
  335. Preemptible bool
  336. CPUBreakdown *ClusterCostsBreakdown
  337. RAMBreakdown *ClusterCostsBreakdown
  338. Start time.Time
  339. End time.Time
  340. Minutes float64
  341. Labels map[string]string
  342. }
  343. // GKE lies about the number of cores e2 nodes have. This table
  344. // contains a mapping from node type -> actual CPU cores
  345. // for those cases.
  346. var partialCPUMap = map[string]float64{
  347. "e2-micro": 0.25,
  348. "e2-small": 0.5,
  349. "e2-medium": 1.0,
  350. }
  351. type NodeIdentifier struct {
  352. Cluster string
  353. Name string
  354. ProviderID string
  355. }
  356. type nodeIdentifierNoProviderID struct {
  357. Cluster string
  358. Name string
  359. }
  360. func ClusterNodes(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[NodeIdentifier]*Node, error) {
  361. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  362. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  363. if offset < time.Minute {
  364. offsetStr = ""
  365. }
  366. // minsPerResolution determines accuracy and resource use for the following
  367. // queries. Smaller values (higher resolution) result in better accuracy,
  368. // but more expensive queries, and vice-a-versa.
  369. minsPerResolution := 1
  370. resolution := time.Duration(minsPerResolution) * time.Minute
  371. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  372. // value, converts it to a cumulative value; i.e.
  373. // [$/hr] * [min/res]*[hr/min] = [$/res]
  374. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  375. requiredCtx := prom.NewContext(client)
  376. optionalCtx := prom.NewContext(client)
  377. 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)
  378. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  379. 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)
  380. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  381. queryNodeGPUCost := fmt.Sprintf(`sum_over_time((avg(node_gpu_hourly_cost * %d.0 / 60.0) by (cluster_id, node, provider_id))[%s:%dm]%s)`, minsPerResolution, durationStr, minsPerResolution, offsetStr)
  382. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total[%s:%dm]%s)) by (kubernetes_node, cluster_id, mode)`, durationStr, minsPerResolution, offsetStr)
  383. queryNodeRAMSystemPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (instance, cluster_id) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (node, cluster_id), "instance", "$1", "node", "(.*)")) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  384. queryNodeRAMUserPct := fmt.Sprintf(`sum(sum_over_time(container_memory_working_set_bytes{container_name!="POD",container_name!="",namespace!="kube-system"}[%s:%dm]%s)) by (instance, cluster_id) / avg(label_replace(sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (node, cluster_id), "instance", "$1", "node", "(.*)")) by (instance, cluster_id)`, durationStr, minsPerResolution, offsetStr, durationStr, minsPerResolution, offsetStr)
  385. queryActiveMins := fmt.Sprintf(`avg(node_total_hourly_cost) by (node, cluster_id, provider_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  386. queryIsSpot := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  387. queryLabels := fmt.Sprintf(`count_over_time(kube_node_labels[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  388. // Return errors if these fail
  389. resChNodeCPUCost := requiredCtx.Query(queryNodeCPUCost)
  390. resChNodeCPUCores := requiredCtx.Query(queryNodeCPUCores)
  391. resChNodeRAMCost := requiredCtx.Query(queryNodeRAMCost)
  392. resChNodeRAMBytes := requiredCtx.Query(queryNodeRAMBytes)
  393. resChNodeGPUCost := requiredCtx.Query(queryNodeGPUCost)
  394. resChActiveMins := requiredCtx.Query(queryActiveMins)
  395. resChIsSpot := requiredCtx.Query(queryIsSpot)
  396. // Do not return errors if these fail, but log warnings
  397. resChNodeCPUModeTotal := optionalCtx.Query(queryNodeCPUModeTotal)
  398. resChNodeRAMSystemPct := optionalCtx.Query(queryNodeRAMSystemPct)
  399. resChNodeRAMUserPct := optionalCtx.Query(queryNodeRAMUserPct)
  400. resChLabels := optionalCtx.Query(queryLabels)
  401. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  402. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  403. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  404. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  405. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  406. resIsSpot, _ := resChIsSpot.Await()
  407. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  408. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  409. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  410. resActiveMins, _ := resChActiveMins.Await()
  411. resLabels, _ := resChLabels.Await()
  412. if optionalCtx.HasErrors() {
  413. for _, err := range optionalCtx.Errors() {
  414. log.Warningf("ClusterNodes: %s", err)
  415. }
  416. }
  417. if requiredCtx.HasErrors() {
  418. for _, err := range requiredCtx.Errors() {
  419. log.Errorf("ClusterNodes: %s", err)
  420. }
  421. return nil, requiredCtx.ErrorCollection()
  422. }
  423. cpuCostMap, clusterAndNameToType1 := buildCPUCostMap(resNodeCPUCost, cp.ParseID)
  424. ramCostMap, clusterAndNameToType2 := buildRAMCostMap(resNodeRAMCost, cp.ParseID)
  425. gpuCostMap, clusterAndNameToType3 := buildGPUCostMap(resNodeGPUCost, cp.ParseID)
  426. clusterAndNameToTypeIntermediate := mergeTypeMaps(clusterAndNameToType1, clusterAndNameToType2)
  427. clusterAndNameToType := mergeTypeMaps(clusterAndNameToTypeIntermediate, clusterAndNameToType3)
  428. cpuCoresMap := buildCPUCoresMap(resNodeCPUCores, clusterAndNameToType)
  429. ramBytesMap := buildRAMBytesMap(resNodeRAMBytes)
  430. ramUserPctMap := buildRAMUserPctMap(resNodeRAMUserPct)
  431. ramSystemPctMap := buildRAMSystemPctMap(resNodeRAMSystemPct)
  432. cpuBreakdownMap := buildCPUBreakdownMap(resNodeCPUModeTotal)
  433. activeDataMap := buildActiveDataMap(resActiveMins, resolution, cp.ParseID)
  434. preemptibleMap := buildPreemptibleMap(resIsSpot, cp.ParseID)
  435. labelsMap := buildLabelsMap(resLabels)
  436. nodeMap := buildNodeMap(
  437. cpuCostMap, ramCostMap, gpuCostMap,
  438. cpuCoresMap, ramBytesMap, ramUserPctMap,
  439. ramSystemPctMap,
  440. cpuBreakdownMap,
  441. activeDataMap,
  442. preemptibleMap,
  443. labelsMap,
  444. clusterAndNameToType,
  445. )
  446. c, err := cp.GetConfig()
  447. if err != nil {
  448. return nil, err
  449. }
  450. discount, err := ParsePercentString(c.Discount)
  451. if err != nil {
  452. return nil, err
  453. }
  454. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  455. if err != nil {
  456. return nil, err
  457. }
  458. for _, node := range nodeMap {
  459. // TODO take RI into account
  460. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  461. // Apply all remaining resources to Idle
  462. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  463. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  464. }
  465. return nodeMap, nil
  466. }
  467. type LoadBalancer struct {
  468. Cluster string
  469. Name string
  470. ProviderID string
  471. Cost float64
  472. Start time.Time
  473. Minutes float64
  474. }
  475. func ClusterLoadBalancers(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*LoadBalancer, error) {
  476. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  477. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  478. if offset < time.Minute {
  479. offsetStr = ""
  480. }
  481. // minsPerResolution determines accuracy and resource use for the following
  482. // queries. Smaller values (higher resolution) result in better accuracy,
  483. // but more expensive queries, and vice-a-versa.
  484. minsPerResolution := 5
  485. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  486. // value, converts it to a cumulative value; i.e.
  487. // [$/hr] * [min/res]*[hr/min] = [$/res]
  488. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  489. ctx := prom.NewContext(client)
  490. queryLBCost := fmt.Sprintf(`sum_over_time((avg(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id))[%s:%dm]%s) * %f`, durationStr, minsPerResolution, offsetStr, hourlyToCumulative)
  491. queryActiveMins := fmt.Sprintf(`count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  492. resChLBCost := ctx.Query(queryLBCost)
  493. resChActiveMins := ctx.Query(queryActiveMins)
  494. resLBCost, _ := resChLBCost.Await()
  495. resActiveMins, _ := resChActiveMins.Await()
  496. if ctx.HasErrors() {
  497. return nil, ctx.ErrorCollection()
  498. }
  499. loadBalancerMap := map[string]*LoadBalancer{}
  500. for _, result := range resLBCost {
  501. cluster, err := result.GetString("cluster_id")
  502. if err != nil {
  503. cluster = env.GetClusterID()
  504. }
  505. namespace, err := result.GetString("namespace")
  506. if err != nil {
  507. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  508. continue
  509. }
  510. serviceName, err := result.GetString("service_name")
  511. if err != nil {
  512. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  513. continue
  514. }
  515. providerID := ""
  516. lbCost := result.Values[0].Value
  517. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  518. if _, ok := loadBalancerMap[key]; !ok {
  519. loadBalancerMap[key] = &LoadBalancer{
  520. Cluster: cluster,
  521. Name: namespace + "/" + serviceName,
  522. ProviderID: providerID, // cp.ParseID(providerID) if providerID does get recorded later
  523. }
  524. }
  525. loadBalancerMap[key].Cost += lbCost
  526. }
  527. for _, result := range resActiveMins {
  528. cluster, err := result.GetString("cluster_id")
  529. if err != nil {
  530. cluster = env.GetClusterID()
  531. }
  532. namespace, err := result.GetString("namespace")
  533. if err != nil {
  534. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  535. continue
  536. }
  537. serviceName, err := result.GetString("service_name")
  538. if err != nil {
  539. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  540. continue
  541. }
  542. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  543. if len(result.Values) == 0 {
  544. continue
  545. }
  546. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  547. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  548. mins := e.Sub(s).Minutes()
  549. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  550. loadBalancerMap[key].Start = s
  551. loadBalancerMap[key].Minutes = mins
  552. }
  553. return loadBalancerMap, nil
  554. }
  555. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  556. func (a *Accesses) ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  557. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  558. start, end, err := util.ParseTimeRange(window, offset)
  559. if err != nil {
  560. return nil, err
  561. }
  562. mins := end.Sub(*start).Minutes()
  563. // minsPerResolution determines accuracy and resource use for the following
  564. // queries. Smaller values (higher resolution) result in better accuracy,
  565. // but more expensive queries, and vice-a-versa.
  566. minsPerResolution := 5
  567. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  568. // value, converts it to a cumulative value; i.e.
  569. // [$/hr] * [min/res]*[hr/min] = [$/res]
  570. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  571. const fmtQueryDataCount = `
  572. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  573. `
  574. const fmtQueryTotalGPU = `
  575. sum(
  576. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  577. ) by (cluster_id)
  578. `
  579. const fmtQueryTotalCPU = `
  580. sum(
  581. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  582. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  583. ) by (cluster_id)
  584. `
  585. const fmtQueryTotalRAM = `
  586. sum(
  587. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  588. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  589. ) by (cluster_id)
  590. `
  591. const fmtQueryTotalStorage = `
  592. sum(
  593. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  594. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  595. ) by (cluster_id)
  596. `
  597. const fmtQueryCPUModePct = `
  598. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  599. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  600. `
  601. const fmtQueryRAMSystemPct = `
  602. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  603. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  604. `
  605. const fmtQueryRAMUserPct = `
  606. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  607. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  608. `
  609. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  610. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  611. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  612. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  613. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  614. if queryTotalLocalStorage != "" {
  615. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  616. }
  617. fmtOffset := ""
  618. if offset != "" {
  619. fmtOffset = fmt.Sprintf("offset %s", offset)
  620. }
  621. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  622. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  623. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  624. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  625. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  626. ctx := prom.NewContext(client)
  627. resChs := ctx.QueryAll(
  628. queryDataCount,
  629. queryTotalGPU,
  630. queryTotalCPU,
  631. queryTotalRAM,
  632. queryTotalStorage,
  633. )
  634. // Only submit the local storage query if it is valid. Otherwise Prometheus
  635. // will return errors. Always append something to resChs, regardless, to
  636. // maintain indexing.
  637. if queryTotalLocalStorage != "" {
  638. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  639. } else {
  640. resChs = append(resChs, nil)
  641. }
  642. if withBreakdown {
  643. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  644. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  645. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  646. bdResChs := ctx.QueryAll(
  647. queryCPUModePct,
  648. queryRAMSystemPct,
  649. queryRAMUserPct,
  650. )
  651. // Only submit the local storage query if it is valid. Otherwise Prometheus
  652. // will return errors. Always append something to resChs, regardless, to
  653. // maintain indexing.
  654. if queryUsedLocalStorage != "" {
  655. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  656. } else {
  657. bdResChs = append(bdResChs, nil)
  658. }
  659. resChs = append(resChs, bdResChs...)
  660. }
  661. resDataCount, _ := resChs[0].Await()
  662. resTotalGPU, _ := resChs[1].Await()
  663. resTotalCPU, _ := resChs[2].Await()
  664. resTotalRAM, _ := resChs[3].Await()
  665. resTotalStorage, _ := resChs[4].Await()
  666. if ctx.HasErrors() {
  667. return nil, ctx.ErrorCollection()
  668. }
  669. defaultClusterID := env.GetClusterID()
  670. dataMinsByCluster := map[string]float64{}
  671. for _, result := range resDataCount {
  672. clusterID, _ := result.GetString("cluster_id")
  673. if clusterID == "" {
  674. clusterID = defaultClusterID
  675. }
  676. dataMins := mins
  677. if len(result.Values) > 0 {
  678. dataMins = result.Values[0].Value
  679. } else {
  680. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  681. }
  682. dataMinsByCluster[clusterID] = dataMins
  683. }
  684. // Determine combined discount
  685. discount, customDiscount := 0.0, 0.0
  686. c, err := a.CloudProvider.GetConfig()
  687. if err == nil {
  688. discount, err = ParsePercentString(c.Discount)
  689. if err != nil {
  690. discount = 0.0
  691. }
  692. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  693. if err != nil {
  694. customDiscount = 0.0
  695. }
  696. }
  697. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  698. costData := make(map[string]map[string]float64)
  699. // Helper function to iterate over Prom query results, parsing the raw values into
  700. // the intermediate costData structure.
  701. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  702. for _, result := range results {
  703. clusterID, _ := result.GetString("cluster_id")
  704. if clusterID == "" {
  705. clusterID = defaultClusterID
  706. }
  707. if _, ok := costData[clusterID]; !ok {
  708. costData[clusterID] = map[string]float64{}
  709. }
  710. if len(result.Values) > 0 {
  711. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  712. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  713. }
  714. }
  715. }
  716. // Apply both sustained use and custom discounts to RAM and CPU
  717. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  718. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  719. // Apply only custom discount to GPU and storage
  720. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  721. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  722. if queryTotalLocalStorage != "" {
  723. resTotalLocalStorage, err := resChs[5].Await()
  724. if err != nil {
  725. return nil, err
  726. }
  727. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  728. }
  729. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  730. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  731. pvUsedCostMap := map[string]float64{}
  732. if withBreakdown {
  733. resCPUModePct, _ := resChs[6].Await()
  734. resRAMSystemPct, _ := resChs[7].Await()
  735. resRAMUserPct, _ := resChs[8].Await()
  736. if ctx.HasErrors() {
  737. return nil, ctx.ErrorCollection()
  738. }
  739. for _, result := range resCPUModePct {
  740. clusterID, _ := result.GetString("cluster_id")
  741. if clusterID == "" {
  742. clusterID = defaultClusterID
  743. }
  744. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  745. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  746. }
  747. cpuBD := cpuBreakdownMap[clusterID]
  748. mode, err := result.GetString("mode")
  749. if err != nil {
  750. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  751. mode = "other"
  752. }
  753. switch mode {
  754. case "idle":
  755. cpuBD.Idle += result.Values[0].Value
  756. case "system":
  757. cpuBD.System += result.Values[0].Value
  758. case "user":
  759. cpuBD.User += result.Values[0].Value
  760. default:
  761. cpuBD.Other += result.Values[0].Value
  762. }
  763. }
  764. for _, result := range resRAMSystemPct {
  765. clusterID, _ := result.GetString("cluster_id")
  766. if clusterID == "" {
  767. clusterID = defaultClusterID
  768. }
  769. if _, ok := ramBreakdownMap[clusterID]; !ok {
  770. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  771. }
  772. ramBD := ramBreakdownMap[clusterID]
  773. ramBD.System += result.Values[0].Value
  774. }
  775. for _, result := range resRAMUserPct {
  776. clusterID, _ := result.GetString("cluster_id")
  777. if clusterID == "" {
  778. clusterID = defaultClusterID
  779. }
  780. if _, ok := ramBreakdownMap[clusterID]; !ok {
  781. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  782. }
  783. ramBD := ramBreakdownMap[clusterID]
  784. ramBD.User += result.Values[0].Value
  785. }
  786. for _, ramBD := range ramBreakdownMap {
  787. remaining := 1.0
  788. remaining -= ramBD.Other
  789. remaining -= ramBD.System
  790. remaining -= ramBD.User
  791. ramBD.Idle = remaining
  792. }
  793. if queryUsedLocalStorage != "" {
  794. resUsedLocalStorage, err := resChs[9].Await()
  795. if err != nil {
  796. return nil, err
  797. }
  798. for _, result := range resUsedLocalStorage {
  799. clusterID, _ := result.GetString("cluster_id")
  800. if clusterID == "" {
  801. clusterID = defaultClusterID
  802. }
  803. pvUsedCostMap[clusterID] += result.Values[0].Value
  804. }
  805. }
  806. }
  807. if ctx.HasErrors() {
  808. for _, err := range ctx.Errors() {
  809. log.Errorf("ComputeClusterCosts: %s", err)
  810. }
  811. return nil, ctx.ErrorCollection()
  812. }
  813. // Convert intermediate structure to Costs instances
  814. costsByCluster := map[string]*ClusterCosts{}
  815. for id, cd := range costData {
  816. dataMins, ok := dataMinsByCluster[id]
  817. if !ok {
  818. dataMins = mins
  819. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  820. }
  821. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  822. if err != nil {
  823. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  824. return nil, err
  825. }
  826. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  827. costs.CPUBreakdown = cpuBD
  828. }
  829. if ramBD, ok := ramBreakdownMap[id]; ok {
  830. costs.RAMBreakdown = ramBD
  831. }
  832. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  833. if pvUC, ok := pvUsedCostMap[id]; ok {
  834. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  835. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  836. }
  837. costs.DataMinutes = dataMins
  838. costsByCluster[id] = costs
  839. }
  840. return costsByCluster, nil
  841. }
  842. type Totals struct {
  843. TotalCost [][]string `json:"totalcost"`
  844. CPUCost [][]string `json:"cpucost"`
  845. MemCost [][]string `json:"memcost"`
  846. StorageCost [][]string `json:"storageCost"`
  847. }
  848. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  849. if len(qrs) == 0 {
  850. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  851. }
  852. result := qrs[0]
  853. totals := [][]string{}
  854. for _, value := range result.Values {
  855. d0 := fmt.Sprintf("%f", value.Timestamp)
  856. d1 := fmt.Sprintf("%f", value.Value)
  857. toAppend := []string{
  858. d0,
  859. d1,
  860. }
  861. totals = append(totals, toAppend)
  862. }
  863. return totals, nil
  864. }
  865. // ClusterCostsOverTime gives the full cluster costs over time
  866. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  867. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  868. if localStorageQuery != "" {
  869. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  870. }
  871. layout := "2006-01-02T15:04:05.000Z"
  872. start, err := time.Parse(layout, startString)
  873. if err != nil {
  874. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  875. return nil, err
  876. }
  877. end, err := time.Parse(layout, endString)
  878. if err != nil {
  879. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  880. return nil, err
  881. }
  882. window, err := time.ParseDuration(windowString)
  883. if err != nil {
  884. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  885. return nil, err
  886. }
  887. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  888. if offset != "" {
  889. offset = fmt.Sprintf("offset %s", offset)
  890. }
  891. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  892. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  893. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  894. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  895. ctx := prom.NewContext(cli)
  896. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  897. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  898. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  899. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  900. resultClusterCores, err := resChClusterCores.Await()
  901. if err != nil {
  902. return nil, err
  903. }
  904. resultClusterRAM, err := resChClusterRAM.Await()
  905. if err != nil {
  906. return nil, err
  907. }
  908. resultStorage, err := resChStorage.Await()
  909. if err != nil {
  910. return nil, err
  911. }
  912. resultTotal, err := resChTotal.Await()
  913. if err != nil {
  914. return nil, err
  915. }
  916. coreTotal, err := resultToTotals(resultClusterCores)
  917. if err != nil {
  918. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  919. return nil, err
  920. }
  921. ramTotal, err := resultToTotals(resultClusterRAM)
  922. if err != nil {
  923. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  924. return nil, err
  925. }
  926. storageTotal, err := resultToTotals(resultStorage)
  927. if err != nil {
  928. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  929. }
  930. clusterTotal, err := resultToTotals(resultTotal)
  931. if err != nil {
  932. // If clusterTotal query failed, it's likely because there are no PVs, which
  933. // causes the qTotal query to return no data. Instead, query only node costs.
  934. // If that fails, return an error because something is actually wrong.
  935. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  936. resultNodes, warnings, err := ctx.QueryRangeSync(qNodes, start, end, window)
  937. for _, warning := range warnings {
  938. log.Warningf(warning)
  939. }
  940. if err != nil {
  941. return nil, err
  942. }
  943. clusterTotal, err = resultToTotals(resultNodes)
  944. if err != nil {
  945. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  946. return nil, err
  947. }
  948. }
  949. return &Totals{
  950. TotalCost: clusterTotal,
  951. CPUCost: coreTotal,
  952. MemCost: ramTotal,
  953. StorageCost: storageTotal,
  954. }, nil
  955. }