cluster.go 43 KB

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