cluster.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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.ErrorCollector.IsError() {
  143. return nil, ctx.Errors()
  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. }
  316. return diskMap, nil
  317. }
  318. type Node struct {
  319. Cluster string
  320. Name string
  321. ProviderID string
  322. NodeType string
  323. CPUCost float64
  324. CPUCores float64
  325. GPUCost float64
  326. RAMCost float64
  327. RAMBytes float64
  328. Discount float64
  329. Preemptible bool
  330. CPUBreakdown *ClusterCostsBreakdown
  331. RAMBreakdown *ClusterCostsBreakdown
  332. Start time.Time
  333. End time.Time
  334. Minutes float64
  335. }
  336. var partialCPUMap = map[string]float64{
  337. "e2-micro": 0.25,
  338. "e2-small": 0.5,
  339. "e2-medium": 1.0,
  340. }
  341. func ClusterNodes(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*Node, []error) {
  342. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  343. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  344. if offset < time.Minute {
  345. offsetStr = ""
  346. }
  347. // minsPerResolution determines accuracy and resource use for the following
  348. // queries. Smaller values (higher resolution) result in better accuracy,
  349. // but more expensive queries, and vice-a-versa.
  350. minsPerResolution := 1
  351. resolution := time.Duration(minsPerResolution) * time.Minute
  352. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  353. // value, converts it to a cumulative value; i.e.
  354. // [$/hr] * [min/res]*[hr/min] = [$/res]
  355. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  356. requiredCtx := prom.NewContext(client)
  357. optionalCtx := prom.NewContext(client)
  358. 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)
  359. queryNodeCPUCores := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_cpu_cores) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  360. 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)
  361. queryNodeRAMBytes := fmt.Sprintf(`avg_over_time(avg(kube_node_status_capacity_memory_bytes) by (cluster_id, node)[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  362. 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)
  363. queryNodeLabels := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s:%dm]%s)`, durationStr, minsPerResolution, offsetStr)
  364. queryNodeCPUModeTotal := fmt.Sprintf(`sum(rate(node_cpu_seconds_total[%s:%dm]%s)) by (kubernetes_node, cluster_id, mode)`, durationStr, minsPerResolution, offsetStr)
  365. 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)
  366. 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)
  367. queryActiveMins := fmt.Sprintf(`node_total_hourly_cost[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  368. // Return errors if these fail
  369. resChNodeCPUCost := requiredCtx.Query(queryNodeCPUCost)
  370. resChNodeCPUCores := requiredCtx.Query(queryNodeCPUCores)
  371. resChNodeRAMCost := requiredCtx.Query(queryNodeRAMCost)
  372. resChNodeRAMBytes := requiredCtx.Query(queryNodeRAMBytes)
  373. resChNodeGPUCost := requiredCtx.Query(queryNodeGPUCost)
  374. resChNodeLabels := requiredCtx.Query(queryNodeLabels)
  375. resChActiveMins := requiredCtx.Query(queryActiveMins)
  376. // Do not return errors if these fail, but log warnings
  377. resChNodeCPUModeTotal := optionalCtx.Query(queryNodeCPUModeTotal)
  378. resChNodeRAMSystemPct := optionalCtx.Query(queryNodeRAMSystemPct)
  379. resChNodeRAMUserPct := optionalCtx.Query(queryNodeRAMUserPct)
  380. resNodeCPUCost, _ := resChNodeCPUCost.Await()
  381. resNodeCPUCores, _ := resChNodeCPUCores.Await()
  382. resNodeGPUCost, _ := resChNodeGPUCost.Await()
  383. resNodeRAMCost, _ := resChNodeRAMCost.Await()
  384. resNodeRAMBytes, _ := resChNodeRAMBytes.Await()
  385. resNodeLabels, _ := resChNodeLabels.Await()
  386. resNodeCPUModeTotal, _ := resChNodeCPUModeTotal.Await()
  387. resNodeRAMSystemPct, _ := resChNodeRAMSystemPct.Await()
  388. resNodeRAMUserPct, _ := resChNodeRAMUserPct.Await()
  389. resActiveMins, _ := resChActiveMins.Await()
  390. if optionalCtx.ErrorCollector.IsError() {
  391. for _, err := range optionalCtx.Errors() {
  392. log.Warningf("ClusterNodes: %s", err)
  393. }
  394. }
  395. if requiredCtx.ErrorCollector.IsError() {
  396. for _, err := range requiredCtx.Errors() {
  397. log.Errorf("ClusterNodes: %s", err)
  398. }
  399. return nil, requiredCtx.Errors()
  400. }
  401. nodeMap := map[string]*Node{}
  402. for _, result := range resNodeCPUCost {
  403. cluster, err := result.GetString("cluster_id")
  404. if err != nil {
  405. cluster = env.GetClusterID()
  406. }
  407. name, err := result.GetString("node")
  408. if err != nil {
  409. log.Warningf("ClusterNodes: CPU cost data missing node")
  410. continue
  411. }
  412. nodeType, _ := result.GetString("instance_type")
  413. providerID, _ := result.GetString("provider_id")
  414. cpuCost := result.Values[0].Value
  415. key := fmt.Sprintf("%s/%s", cluster, name)
  416. if _, ok := nodeMap[key]; !ok {
  417. nodeMap[key] = &Node{
  418. Cluster: cluster,
  419. Name: name,
  420. NodeType: nodeType,
  421. ProviderID: cp.ParseID(providerID),
  422. CPUBreakdown: &ClusterCostsBreakdown{},
  423. RAMBreakdown: &ClusterCostsBreakdown{},
  424. }
  425. }
  426. nodeMap[key].CPUCost += cpuCost
  427. nodeMap[key].NodeType = nodeType
  428. if nodeMap[key].ProviderID == "" {
  429. nodeMap[key].ProviderID = cp.ParseID(providerID)
  430. }
  431. }
  432. for _, result := range resNodeCPUCores {
  433. cluster, err := result.GetString("cluster_id")
  434. if err != nil {
  435. cluster = env.GetClusterID()
  436. }
  437. name, err := result.GetString("node")
  438. if err != nil {
  439. log.Warningf("ClusterNodes: CPU cores data missing node")
  440. continue
  441. }
  442. cpuCores := result.Values[0].Value
  443. key := fmt.Sprintf("%s/%s", cluster, name)
  444. if _, ok := nodeMap[key]; !ok {
  445. nodeMap[key] = &Node{
  446. Cluster: cluster,
  447. Name: name,
  448. CPUBreakdown: &ClusterCostsBreakdown{},
  449. RAMBreakdown: &ClusterCostsBreakdown{},
  450. }
  451. }
  452. node := nodeMap[key]
  453. if v, ok := partialCPUMap[node.NodeType]; ok {
  454. node.CPUCores = v
  455. if cpuCores > 0 {
  456. adjustmentFactor := v / cpuCores
  457. node.CPUCost = node.CPUCost * adjustmentFactor
  458. }
  459. } else {
  460. nodeMap[key].CPUCores = cpuCores
  461. }
  462. }
  463. for _, result := range resNodeRAMCost {
  464. cluster, err := result.GetString("cluster_id")
  465. if err != nil {
  466. cluster = env.GetClusterID()
  467. }
  468. name, err := result.GetString("node")
  469. if err != nil {
  470. log.Warningf("ClusterNodes: RAM cost data missing node")
  471. continue
  472. }
  473. nodeType, _ := result.GetString("instance_type")
  474. providerID, _ := result.GetString("provider_id")
  475. ramCost := result.Values[0].Value
  476. key := fmt.Sprintf("%s/%s", cluster, name)
  477. if _, ok := nodeMap[key]; !ok {
  478. nodeMap[key] = &Node{
  479. Cluster: cluster,
  480. Name: name,
  481. NodeType: nodeType,
  482. ProviderID: cp.ParseID(providerID),
  483. CPUBreakdown: &ClusterCostsBreakdown{},
  484. RAMBreakdown: &ClusterCostsBreakdown{},
  485. }
  486. }
  487. nodeMap[key].RAMCost += ramCost
  488. nodeMap[key].NodeType = nodeType
  489. if nodeMap[key].ProviderID == "" {
  490. nodeMap[key].ProviderID = cp.ParseID(providerID)
  491. }
  492. }
  493. for _, result := range resNodeRAMBytes {
  494. cluster, err := result.GetString("cluster_id")
  495. if err != nil {
  496. cluster = env.GetClusterID()
  497. }
  498. name, err := result.GetString("node")
  499. if err != nil {
  500. log.Warningf("ClusterNodes: RAM bytes data missing node")
  501. continue
  502. }
  503. ramBytes := result.Values[0].Value
  504. key := fmt.Sprintf("%s/%s", cluster, name)
  505. if _, ok := nodeMap[key]; !ok {
  506. nodeMap[key] = &Node{
  507. Cluster: cluster,
  508. Name: name,
  509. CPUBreakdown: &ClusterCostsBreakdown{},
  510. RAMBreakdown: &ClusterCostsBreakdown{},
  511. }
  512. }
  513. nodeMap[key].RAMBytes = ramBytes
  514. }
  515. for _, result := range resNodeGPUCost {
  516. cluster, err := result.GetString("cluster_id")
  517. if err != nil {
  518. cluster = env.GetClusterID()
  519. }
  520. name, err := result.GetString("node")
  521. if err != nil {
  522. log.Warningf("ClusterNodes: GPU cost data missing node")
  523. continue
  524. }
  525. nodeType, _ := result.GetString("instance_type")
  526. providerID, _ := result.GetString("provider_id")
  527. gpuCost := result.Values[0].Value
  528. key := fmt.Sprintf("%s/%s", cluster, name)
  529. if _, ok := nodeMap[key]; !ok {
  530. nodeMap[key] = &Node{
  531. Cluster: cluster,
  532. Name: name,
  533. NodeType: nodeType,
  534. ProviderID: cp.ParseID(providerID),
  535. CPUBreakdown: &ClusterCostsBreakdown{},
  536. RAMBreakdown: &ClusterCostsBreakdown{},
  537. }
  538. }
  539. nodeMap[key].GPUCost += gpuCost
  540. if nodeMap[key].ProviderID == "" {
  541. nodeMap[key].ProviderID = cp.ParseID(providerID)
  542. }
  543. }
  544. // Mapping of cluster/node=cpu for computing resource efficiency
  545. clusterNodeCPUTotal := map[string]float64{}
  546. // Mapping of cluster/node:mode=cpu for computing resource efficiency
  547. clusterNodeModeCPUTotal := map[string]map[string]float64{}
  548. // Build intermediate structures for CPU usage by (cluster, node) and by
  549. // (cluster, node, mode) for computing resouce efficiency
  550. for _, result := range resNodeCPUModeTotal {
  551. cluster, err := result.GetString("cluster_id")
  552. if err != nil {
  553. cluster = env.GetClusterID()
  554. }
  555. node, err := result.GetString("kubernetes_node")
  556. if err != nil {
  557. log.DedupedWarningf(5, "ClusterNodes: CPU mode data missing node")
  558. continue
  559. }
  560. mode, err := result.GetString("mode")
  561. if err != nil {
  562. log.Warningf("ClusterNodes: unable to read CPU mode: %s", err)
  563. mode = "other"
  564. }
  565. key := fmt.Sprintf("%s/%s", cluster, node)
  566. total := result.Values[0].Value
  567. // Increment total
  568. clusterNodeCPUTotal[key] += total
  569. // Increment mode
  570. if _, ok := clusterNodeModeCPUTotal[key]; !ok {
  571. clusterNodeModeCPUTotal[key] = map[string]float64{}
  572. }
  573. clusterNodeModeCPUTotal[key][mode] += total
  574. }
  575. // Compute resource efficiency from intermediate structures
  576. for key, total := range clusterNodeCPUTotal {
  577. if modeTotals, ok := clusterNodeModeCPUTotal[key]; ok {
  578. for mode, subtotal := range modeTotals {
  579. // Compute percentage for the current cluster, node, mode
  580. pct := subtotal / total
  581. if _, ok := nodeMap[key]; !ok {
  582. log.Warningf("ClusterNodes: CPU mode data for unidentified node")
  583. continue
  584. }
  585. switch mode {
  586. case "idle":
  587. nodeMap[key].CPUBreakdown.Idle += pct
  588. case "system":
  589. nodeMap[key].CPUBreakdown.System += pct
  590. case "user":
  591. nodeMap[key].CPUBreakdown.User += pct
  592. default:
  593. nodeMap[key].CPUBreakdown.Other += pct
  594. }
  595. }
  596. }
  597. }
  598. for _, result := range resNodeRAMSystemPct {
  599. cluster, err := result.GetString("cluster_id")
  600. if err != nil {
  601. cluster = env.GetClusterID()
  602. }
  603. name, err := result.GetString("instance")
  604. if err != nil {
  605. log.Warningf("ClusterNodes: RAM system percent missing node")
  606. continue
  607. }
  608. pct := result.Values[0].Value
  609. key := fmt.Sprintf("%s/%s", cluster, name)
  610. if _, ok := nodeMap[key]; !ok {
  611. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  612. continue
  613. }
  614. nodeMap[key].RAMBreakdown.System += pct
  615. }
  616. for _, result := range resNodeRAMUserPct {
  617. cluster, err := result.GetString("cluster_id")
  618. if err != nil {
  619. cluster = env.GetClusterID()
  620. }
  621. name, err := result.GetString("instance")
  622. if err != nil {
  623. log.Warningf("ClusterNodes: RAM system percent missing node")
  624. continue
  625. }
  626. pct := result.Values[0].Value
  627. key := fmt.Sprintf("%s/%s", cluster, name)
  628. if _, ok := nodeMap[key]; !ok {
  629. log.Warningf("ClusterNodes: RAM system percent for unidentified node")
  630. continue
  631. }
  632. nodeMap[key].RAMBreakdown.User += pct
  633. }
  634. for _, result := range resActiveMins {
  635. cluster, err := result.GetString("cluster_id")
  636. if err != nil {
  637. cluster = env.GetClusterID()
  638. }
  639. name, err := result.GetString("node")
  640. if err != nil {
  641. log.Warningf("ClusterNodes: active mins missing node")
  642. continue
  643. }
  644. key := fmt.Sprintf("%s/%s", cluster, name)
  645. if _, ok := nodeMap[key]; !ok {
  646. log.Warningf("ClusterNodes: active mins for unidentified node")
  647. continue
  648. }
  649. if len(result.Values) == 0 {
  650. continue
  651. }
  652. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  653. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0).Add(resolution)
  654. mins := e.Sub(s).Minutes()
  655. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  656. nodeMap[key].End = e
  657. nodeMap[key].Start = s
  658. nodeMap[key].Minutes = mins
  659. }
  660. // Determine preemptibility with node labels
  661. for _, result := range resNodeLabels {
  662. nodeName, err := result.GetString("node")
  663. if err != nil {
  664. continue
  665. }
  666. // GCP preemptible label
  667. pre := result.Values[0].Value
  668. cluster, err := result.GetString("cluster_id")
  669. if err != nil {
  670. cluster = env.GetClusterID()
  671. }
  672. key := fmt.Sprintf("%s/%s", cluster, nodeName)
  673. if node, ok := nodeMap[key]; pre > 0.0 && ok {
  674. node.Preemptible = true
  675. }
  676. // TODO AWS preemptible
  677. // TODO Azure preemptible
  678. }
  679. c, err := cp.GetConfig()
  680. if err != nil {
  681. return nil, []error{err}
  682. }
  683. discount, err := ParsePercentString(c.Discount)
  684. if err != nil {
  685. return nil, []error{err}
  686. }
  687. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  688. if err != nil {
  689. return nil, []error{err}
  690. }
  691. for _, node := range nodeMap {
  692. // TODO take RI into account
  693. node.Discount = cp.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  694. // Apply all remaining resources to Idle
  695. node.CPUBreakdown.Idle = 1.0 - (node.CPUBreakdown.System + node.CPUBreakdown.Other + node.CPUBreakdown.User)
  696. node.RAMBreakdown.Idle = 1.0 - (node.RAMBreakdown.System + node.RAMBreakdown.Other + node.RAMBreakdown.User)
  697. }
  698. return nodeMap, nil
  699. }
  700. type LoadBalancer struct {
  701. Cluster string
  702. Name string
  703. ProviderID string
  704. Cost float64
  705. Start time.Time
  706. Minutes float64
  707. }
  708. func ClusterLoadBalancers(cp cloud.Provider, client prometheus.Client, duration, offset time.Duration) (map[string]*LoadBalancer, []error) {
  709. durationStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  710. offsetStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  711. if offset < time.Minute {
  712. offsetStr = ""
  713. }
  714. // minsPerResolution determines accuracy and resource use for the following
  715. // queries. Smaller values (higher resolution) result in better accuracy,
  716. // but more expensive queries, and vice-a-versa.
  717. minsPerResolution := 5
  718. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  719. // value, converts it to a cumulative value; i.e.
  720. // [$/hr] * [min/res]*[hr/min] = [$/res]
  721. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  722. ctx := prom.NewContext(client)
  723. 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)
  724. queryActiveMins := fmt.Sprintf(`count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%dm]%s`, durationStr, minsPerResolution, offsetStr)
  725. resChLBCost := ctx.Query(queryLBCost)
  726. resChActiveMins := ctx.Query(queryActiveMins)
  727. resLBCost, _ := resChLBCost.Await()
  728. resActiveMins, _ := resChActiveMins.Await()
  729. if ctx.ErrorCollector.IsError() {
  730. return nil, ctx.Errors()
  731. }
  732. loadBalancerMap := map[string]*LoadBalancer{}
  733. for _, result := range resLBCost {
  734. cluster, err := result.GetString("cluster_id")
  735. if err != nil {
  736. cluster = env.GetClusterID()
  737. }
  738. namespace, err := result.GetString("namespace")
  739. if err != nil {
  740. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  741. continue
  742. }
  743. serviceName, err := result.GetString("service_name")
  744. if err != nil {
  745. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  746. continue
  747. }
  748. providerID := ""
  749. lbCost := result.Values[0].Value
  750. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  751. if _, ok := loadBalancerMap[key]; !ok {
  752. loadBalancerMap[key] = &LoadBalancer{
  753. Cluster: cluster,
  754. Name: namespace + "/" + serviceName,
  755. ProviderID: providerID, // cp.ParseID(providerID) if providerID does get recorded later
  756. }
  757. }
  758. loadBalancerMap[key].Cost += lbCost
  759. }
  760. for _, result := range resActiveMins {
  761. cluster, err := result.GetString("cluster_id")
  762. if err != nil {
  763. cluster = env.GetClusterID()
  764. }
  765. namespace, err := result.GetString("namespace")
  766. if err != nil {
  767. log.Warningf("ClusterLoadBalancers: LB cost data missing namespace")
  768. continue
  769. }
  770. serviceName, err := result.GetString("service_name")
  771. if err != nil {
  772. log.Warningf("ClusterLoadBalancers: LB cost data missing service_name")
  773. continue
  774. }
  775. key := fmt.Sprintf("%s/%s/%s", cluster, namespace, serviceName)
  776. if len(result.Values) == 0 {
  777. continue
  778. }
  779. s := time.Unix(int64(result.Values[0].Timestamp), 0)
  780. e := time.Unix(int64(result.Values[len(result.Values)-1].Timestamp), 0)
  781. mins := e.Sub(s).Minutes()
  782. // TODO niko/assets if mins >= threshold, interpolate for missing data?
  783. loadBalancerMap[key].Start = s
  784. loadBalancerMap[key].Minutes = mins
  785. }
  786. return loadBalancerMap, nil
  787. }
  788. // ComputeClusterCosts gives the cumulative and monthly-rate cluster costs over a window of time for all clusters.
  789. func ComputeClusterCosts(client prometheus.Client, provider cloud.Provider, window, offset string, withBreakdown bool) (map[string]*ClusterCosts, error) {
  790. // Compute number of minutes in the full interval, for use interpolating missed scrapes or scaling missing data
  791. start, end, err := util.ParseTimeRange(window, offset)
  792. if err != nil {
  793. return nil, err
  794. }
  795. mins := end.Sub(*start).Minutes()
  796. // minsPerResolution determines accuracy and resource use for the following
  797. // queries. Smaller values (higher resolution) result in better accuracy,
  798. // but more expensive queries, and vice-a-versa.
  799. minsPerResolution := 5
  800. // hourlyToCumulative is a scaling factor that, when multiplied by an hourly
  801. // value, converts it to a cumulative value; i.e.
  802. // [$/hr] * [min/res]*[hr/min] = [$/res]
  803. hourlyToCumulative := float64(minsPerResolution) * (1.0 / 60.0)
  804. const fmtQueryDataCount = `
  805. count_over_time(sum(kube_node_status_capacity_cpu_cores) by (cluster_id)[%s:%dm]%s) * %d
  806. `
  807. const fmtQueryTotalGPU = `
  808. sum(
  809. sum_over_time(node_gpu_hourly_cost[%s:%dm]%s) * %f
  810. ) by (cluster_id)
  811. `
  812. const fmtQueryTotalCPU = `
  813. sum(
  814. sum_over_time(avg(kube_node_status_capacity_cpu_cores) by (node, cluster_id)[%s:%dm]%s) *
  815. avg(avg_over_time(node_cpu_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  816. ) by (cluster_id)
  817. `
  818. const fmtQueryTotalRAM = `
  819. sum(
  820. sum_over_time(avg(kube_node_status_capacity_memory_bytes) by (node, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  821. avg(avg_over_time(node_ram_hourly_cost[%s:%dm]%s)) by (node, cluster_id) * %f
  822. ) by (cluster_id)
  823. `
  824. const fmtQueryTotalStorage = `
  825. sum(
  826. sum_over_time(avg(kube_persistentvolume_capacity_bytes) by (persistentvolume, cluster_id)[%s:%dm]%s) / 1024 / 1024 / 1024 *
  827. avg(avg_over_time(pv_hourly_cost[%s:%dm]%s)) by (persistentvolume, cluster_id) * %f
  828. ) by (cluster_id)
  829. `
  830. const fmtQueryCPUModePct = `
  831. sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id, mode) / ignoring(mode)
  832. group_left sum(rate(node_cpu_seconds_total[%s]%s)) by (cluster_id)
  833. `
  834. const fmtQueryRAMSystemPct = `
  835. sum(sum_over_time(container_memory_usage_bytes{container_name!="",namespace="kube-system"}[%s:%dm]%s)) by (cluster_id)
  836. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  837. `
  838. const fmtQueryRAMUserPct = `
  839. sum(sum_over_time(kubecost_cluster_memory_working_set_bytes[%s:%dm]%s)) by (cluster_id)
  840. / sum(sum_over_time(kube_node_status_capacity_memory_bytes[%s:%dm]%s)) by (cluster_id)
  841. `
  842. // TODO niko/clustercost metric "kubelet_volume_stats_used_bytes" was deprecated in 1.12, then seems to have come back in 1.17
  843. // const fmtQueryPVStorageUsePct = `(sum(kube_persistentvolumeclaim_info) by (persistentvolumeclaim, storageclass,namespace) + on (persistentvolumeclaim,namespace)
  844. // group_right(storageclass) sum(kubelet_volume_stats_used_bytes) by (persistentvolumeclaim,namespace))`
  845. queryUsedLocalStorage := provider.GetLocalStorageQuery(window, offset, false, true)
  846. queryTotalLocalStorage := provider.GetLocalStorageQuery(window, offset, false, false)
  847. if queryTotalLocalStorage != "" {
  848. queryTotalLocalStorage = fmt.Sprintf(" + %s", queryTotalLocalStorage)
  849. }
  850. fmtOffset := ""
  851. if offset != "" {
  852. fmtOffset = fmt.Sprintf("offset %s", offset)
  853. }
  854. queryDataCount := fmt.Sprintf(fmtQueryDataCount, window, minsPerResolution, fmtOffset, minsPerResolution)
  855. queryTotalGPU := fmt.Sprintf(fmtQueryTotalGPU, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  856. queryTotalCPU := fmt.Sprintf(fmtQueryTotalCPU, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  857. queryTotalRAM := fmt.Sprintf(fmtQueryTotalRAM, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  858. queryTotalStorage := fmt.Sprintf(fmtQueryTotalStorage, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset, hourlyToCumulative)
  859. ctx := prom.NewContext(client)
  860. resChs := ctx.QueryAll(
  861. queryDataCount,
  862. queryTotalGPU,
  863. queryTotalCPU,
  864. queryTotalRAM,
  865. queryTotalStorage,
  866. )
  867. // Only submit the local storage query if it is valid. Otherwise Prometheus
  868. // will return errors. Always append something to resChs, regardless, to
  869. // maintain indexing.
  870. if queryTotalLocalStorage != "" {
  871. resChs = append(resChs, ctx.Query(queryTotalLocalStorage))
  872. } else {
  873. resChs = append(resChs, nil)
  874. }
  875. if withBreakdown {
  876. queryCPUModePct := fmt.Sprintf(fmtQueryCPUModePct, window, fmtOffset, window, fmtOffset)
  877. queryRAMSystemPct := fmt.Sprintf(fmtQueryRAMSystemPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  878. queryRAMUserPct := fmt.Sprintf(fmtQueryRAMUserPct, window, minsPerResolution, fmtOffset, window, minsPerResolution, fmtOffset)
  879. bdResChs := ctx.QueryAll(
  880. queryCPUModePct,
  881. queryRAMSystemPct,
  882. queryRAMUserPct,
  883. )
  884. // Only submit the local storage query if it is valid. Otherwise Prometheus
  885. // will return errors. Always append something to resChs, regardless, to
  886. // maintain indexing.
  887. if queryUsedLocalStorage != "" {
  888. bdResChs = append(bdResChs, ctx.Query(queryUsedLocalStorage))
  889. } else {
  890. bdResChs = append(bdResChs, nil)
  891. }
  892. resChs = append(resChs, bdResChs...)
  893. }
  894. resDataCount, _ := resChs[0].Await()
  895. resTotalGPU, _ := resChs[1].Await()
  896. resTotalCPU, _ := resChs[2].Await()
  897. resTotalRAM, _ := resChs[3].Await()
  898. resTotalStorage, _ := resChs[4].Await()
  899. if ctx.HasErrors() {
  900. return nil, ctx.Errors()[0]
  901. }
  902. defaultClusterID := env.GetClusterID()
  903. dataMinsByCluster := map[string]float64{}
  904. for _, result := range resDataCount {
  905. clusterID, _ := result.GetString("cluster_id")
  906. if clusterID == "" {
  907. clusterID = defaultClusterID
  908. }
  909. dataMins := mins
  910. if len(result.Values) > 0 {
  911. dataMins = result.Values[0].Value
  912. } else {
  913. klog.V(3).Infof("[Warning] cluster cost data count returned no results for cluster %s", clusterID)
  914. }
  915. dataMinsByCluster[clusterID] = dataMins
  916. }
  917. // Determine combined discount
  918. discount, customDiscount := 0.0, 0.0
  919. c, err := A.Cloud.GetConfig()
  920. if err == nil {
  921. discount, err = ParsePercentString(c.Discount)
  922. if err != nil {
  923. discount = 0.0
  924. }
  925. customDiscount, err = ParsePercentString(c.NegotiatedDiscount)
  926. if err != nil {
  927. customDiscount = 0.0
  928. }
  929. }
  930. // Intermediate structure storing mapping of [clusterID][type ∈ {cpu, ram, storage, total}]=cost
  931. costData := make(map[string]map[string]float64)
  932. // Helper function to iterate over Prom query results, parsing the raw values into
  933. // the intermediate costData structure.
  934. setCostsFromResults := func(costData map[string]map[string]float64, results []*prom.QueryResult, name string, discount float64, customDiscount float64) {
  935. for _, result := range results {
  936. clusterID, _ := result.GetString("cluster_id")
  937. if clusterID == "" {
  938. clusterID = defaultClusterID
  939. }
  940. if _, ok := costData[clusterID]; !ok {
  941. costData[clusterID] = map[string]float64{}
  942. }
  943. if len(result.Values) > 0 {
  944. costData[clusterID][name] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  945. costData[clusterID]["total"] += result.Values[0].Value * (1.0 - discount) * (1.0 - customDiscount)
  946. }
  947. }
  948. }
  949. // Apply both sustained use and custom discounts to RAM and CPU
  950. setCostsFromResults(costData, resTotalCPU, "cpu", discount, customDiscount)
  951. setCostsFromResults(costData, resTotalRAM, "ram", discount, customDiscount)
  952. // Apply only custom discount to GPU and storage
  953. setCostsFromResults(costData, resTotalGPU, "gpu", 0.0, customDiscount)
  954. setCostsFromResults(costData, resTotalStorage, "storage", 0.0, customDiscount)
  955. if queryTotalLocalStorage != "" {
  956. resTotalLocalStorage, err := resChs[5].Await()
  957. if err != nil {
  958. return nil, err
  959. }
  960. setCostsFromResults(costData, resTotalLocalStorage, "localstorage", 0.0, customDiscount)
  961. }
  962. cpuBreakdownMap := map[string]*ClusterCostsBreakdown{}
  963. ramBreakdownMap := map[string]*ClusterCostsBreakdown{}
  964. pvUsedCostMap := map[string]float64{}
  965. if withBreakdown {
  966. resCPUModePct, _ := resChs[6].Await()
  967. resRAMSystemPct, _ := resChs[7].Await()
  968. resRAMUserPct, _ := resChs[8].Await()
  969. if ctx.HasErrors() {
  970. return nil, ctx.Errors()[0]
  971. }
  972. for _, result := range resCPUModePct {
  973. clusterID, _ := result.GetString("cluster_id")
  974. if clusterID == "" {
  975. clusterID = defaultClusterID
  976. }
  977. if _, ok := cpuBreakdownMap[clusterID]; !ok {
  978. cpuBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  979. }
  980. cpuBD := cpuBreakdownMap[clusterID]
  981. mode, err := result.GetString("mode")
  982. if err != nil {
  983. klog.V(3).Infof("[Warning] ComputeClusterCosts: unable to read CPU mode: %s", err)
  984. mode = "other"
  985. }
  986. switch mode {
  987. case "idle":
  988. cpuBD.Idle += result.Values[0].Value
  989. case "system":
  990. cpuBD.System += result.Values[0].Value
  991. case "user":
  992. cpuBD.User += result.Values[0].Value
  993. default:
  994. cpuBD.Other += result.Values[0].Value
  995. }
  996. }
  997. for _, result := range resRAMSystemPct {
  998. clusterID, _ := result.GetString("cluster_id")
  999. if clusterID == "" {
  1000. clusterID = defaultClusterID
  1001. }
  1002. if _, ok := ramBreakdownMap[clusterID]; !ok {
  1003. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  1004. }
  1005. ramBD := ramBreakdownMap[clusterID]
  1006. ramBD.System += result.Values[0].Value
  1007. }
  1008. for _, result := range resRAMUserPct {
  1009. clusterID, _ := result.GetString("cluster_id")
  1010. if clusterID == "" {
  1011. clusterID = defaultClusterID
  1012. }
  1013. if _, ok := ramBreakdownMap[clusterID]; !ok {
  1014. ramBreakdownMap[clusterID] = &ClusterCostsBreakdown{}
  1015. }
  1016. ramBD := ramBreakdownMap[clusterID]
  1017. ramBD.User += result.Values[0].Value
  1018. }
  1019. for _, ramBD := range ramBreakdownMap {
  1020. remaining := 1.0
  1021. remaining -= ramBD.Other
  1022. remaining -= ramBD.System
  1023. remaining -= ramBD.User
  1024. ramBD.Idle = remaining
  1025. }
  1026. if queryUsedLocalStorage != "" {
  1027. resUsedLocalStorage, err := resChs[9].Await()
  1028. if err != nil {
  1029. return nil, err
  1030. }
  1031. for _, result := range resUsedLocalStorage {
  1032. clusterID, _ := result.GetString("cluster_id")
  1033. if clusterID == "" {
  1034. clusterID = defaultClusterID
  1035. }
  1036. pvUsedCostMap[clusterID] += result.Values[0].Value
  1037. }
  1038. }
  1039. }
  1040. if ctx.ErrorCollector.IsError() {
  1041. for _, err := range ctx.Errors() {
  1042. log.Errorf("ComputeClusterCosts: %s", err)
  1043. }
  1044. return nil, ctx.Errors()[0]
  1045. }
  1046. // Convert intermediate structure to Costs instances
  1047. costsByCluster := map[string]*ClusterCosts{}
  1048. for id, cd := range costData {
  1049. dataMins, ok := dataMinsByCluster[id]
  1050. if !ok {
  1051. dataMins = mins
  1052. klog.V(3).Infof("[Warning] cluster cost data count not found for cluster %s", id)
  1053. }
  1054. costs, err := NewClusterCostsFromCumulative(cd["cpu"], cd["gpu"], cd["ram"], cd["storage"]+cd["localstorage"], window, offset, dataMins/util.MinsPerHour)
  1055. if err != nil {
  1056. klog.V(3).Infof("[Warning] Failed to parse cluster costs on %s (%s) from cumulative data: %+v", window, offset, cd)
  1057. return nil, err
  1058. }
  1059. if cpuBD, ok := cpuBreakdownMap[id]; ok {
  1060. costs.CPUBreakdown = cpuBD
  1061. }
  1062. if ramBD, ok := ramBreakdownMap[id]; ok {
  1063. costs.RAMBreakdown = ramBD
  1064. }
  1065. costs.StorageBreakdown = &ClusterCostsBreakdown{}
  1066. if pvUC, ok := pvUsedCostMap[id]; ok {
  1067. costs.StorageBreakdown.Idle = (costs.StorageCumulative - pvUC) / costs.StorageCumulative
  1068. costs.StorageBreakdown.User = pvUC / costs.StorageCumulative
  1069. }
  1070. costs.DataMinutes = dataMins
  1071. costsByCluster[id] = costs
  1072. }
  1073. return costsByCluster, nil
  1074. }
  1075. type Totals struct {
  1076. TotalCost [][]string `json:"totalcost"`
  1077. CPUCost [][]string `json:"cpucost"`
  1078. MemCost [][]string `json:"memcost"`
  1079. StorageCost [][]string `json:"storageCost"`
  1080. }
  1081. func resultToTotals(qrs []*prom.QueryResult) ([][]string, error) {
  1082. if len(qrs) == 0 {
  1083. return [][]string{}, fmt.Errorf("Not enough data available in the selected time range")
  1084. }
  1085. result := qrs[0]
  1086. totals := [][]string{}
  1087. for _, value := range result.Values {
  1088. d0 := fmt.Sprintf("%f", value.Timestamp)
  1089. d1 := fmt.Sprintf("%f", value.Value)
  1090. toAppend := []string{
  1091. d0,
  1092. d1,
  1093. }
  1094. totals = append(totals, toAppend)
  1095. }
  1096. return totals, nil
  1097. }
  1098. // ClusterCostsOverTime gives the full cluster costs over time
  1099. func ClusterCostsOverTime(cli prometheus.Client, provider cloud.Provider, startString, endString, windowString, offset string) (*Totals, error) {
  1100. localStorageQuery := provider.GetLocalStorageQuery(windowString, offset, true, false)
  1101. if localStorageQuery != "" {
  1102. localStorageQuery = fmt.Sprintf("+ %s", localStorageQuery)
  1103. }
  1104. layout := "2006-01-02T15:04:05.000Z"
  1105. start, err := time.Parse(layout, startString)
  1106. if err != nil {
  1107. klog.V(1).Infof("Error parsing time " + startString + ". Error: " + err.Error())
  1108. return nil, err
  1109. }
  1110. end, err := time.Parse(layout, endString)
  1111. if err != nil {
  1112. klog.V(1).Infof("Error parsing time " + endString + ". Error: " + err.Error())
  1113. return nil, err
  1114. }
  1115. window, err := time.ParseDuration(windowString)
  1116. if err != nil {
  1117. klog.V(1).Infof("Error parsing time " + windowString + ". Error: " + err.Error())
  1118. return nil, err
  1119. }
  1120. // turn offsets of the format "[0-9+]h" into the format "offset [0-9+]h" for use in query templatess
  1121. if offset != "" {
  1122. offset = fmt.Sprintf("offset %s", offset)
  1123. }
  1124. qCores := fmt.Sprintf(queryClusterCores, windowString, offset, windowString, offset, windowString, offset)
  1125. qRAM := fmt.Sprintf(queryClusterRAM, windowString, offset, windowString, offset)
  1126. qStorage := fmt.Sprintf(queryStorage, windowString, offset, windowString, offset, localStorageQuery)
  1127. qTotal := fmt.Sprintf(queryTotal, localStorageQuery)
  1128. ctx := prom.NewContext(cli)
  1129. resChClusterCores := ctx.QueryRange(qCores, start, end, window)
  1130. resChClusterRAM := ctx.QueryRange(qRAM, start, end, window)
  1131. resChStorage := ctx.QueryRange(qStorage, start, end, window)
  1132. resChTotal := ctx.QueryRange(qTotal, start, end, window)
  1133. resultClusterCores, err := resChClusterCores.Await()
  1134. if err != nil {
  1135. return nil, err
  1136. }
  1137. resultClusterRAM, err := resChClusterRAM.Await()
  1138. if err != nil {
  1139. return nil, err
  1140. }
  1141. resultStorage, err := resChStorage.Await()
  1142. if err != nil {
  1143. return nil, err
  1144. }
  1145. resultTotal, err := resChTotal.Await()
  1146. if err != nil {
  1147. return nil, err
  1148. }
  1149. coreTotal, err := resultToTotals(resultClusterCores)
  1150. if err != nil {
  1151. klog.Infof("[Warning] ClusterCostsOverTime: no cpu data: %s", err)
  1152. return nil, err
  1153. }
  1154. ramTotal, err := resultToTotals(resultClusterRAM)
  1155. if err != nil {
  1156. klog.Infof("[Warning] ClusterCostsOverTime: no ram data: %s", err)
  1157. return nil, err
  1158. }
  1159. storageTotal, err := resultToTotals(resultStorage)
  1160. if err != nil {
  1161. klog.Infof("[Warning] ClusterCostsOverTime: no storage data: %s", err)
  1162. }
  1163. clusterTotal, err := resultToTotals(resultTotal)
  1164. if err != nil {
  1165. // If clusterTotal query failed, it's likely because there are no PVs, which
  1166. // causes the qTotal query to return no data. Instead, query only node costs.
  1167. // If that fails, return an error because something is actually wrong.
  1168. qNodes := fmt.Sprintf(queryNodes, localStorageQuery)
  1169. resultNodes, err := ctx.QueryRangeSync(qNodes, start, end, window)
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. clusterTotal, err = resultToTotals(resultNodes)
  1174. if err != nil {
  1175. klog.Infof("[Warning] ClusterCostsOverTime: no node data: %s", err)
  1176. return nil, err
  1177. }
  1178. }
  1179. return &Totals{
  1180. TotalCost: clusterTotal,
  1181. CPUCost: coreTotal,
  1182. MemCost: ramTotal,
  1183. StorageCost: storageTotal,
  1184. }, nil
  1185. }