aggregation.go 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  1. package costmodel
  2. import (
  3. "fmt"
  4. "math"
  5. "net/http"
  6. "regexp"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/julienschmidt/httprouter"
  12. "github.com/kubecost/cost-model/pkg/cloud"
  13. "github.com/kubecost/cost-model/pkg/kubecost"
  14. "github.com/kubecost/cost-model/pkg/log"
  15. "github.com/kubecost/cost-model/pkg/prom"
  16. "github.com/kubecost/cost-model/pkg/thanos"
  17. "github.com/kubecost/cost-model/pkg/util"
  18. "github.com/patrickmn/go-cache"
  19. prometheusClient "github.com/prometheus/client_golang/api"
  20. "k8s.io/klog"
  21. )
  22. const (
  23. // SplitTypeWeighted signals that shared costs should be shared
  24. // proportionally, rather than evenly
  25. SplitTypeWeighted = "weighted"
  26. // UnallocatedSubfield indicates an allocation datum that does not have the
  27. // chosen Aggregator; e.g. during aggregation by some label, there may be
  28. // cost data that do not have the given label.
  29. UnallocatedSubfield = "__unallocated__"
  30. )
  31. // Aggregation describes aggregated cost data, containing cumulative cost and
  32. // allocation data per resource, vectors of rate data per resource, efficiency
  33. // data, and metadata describing the type of aggregation operation.
  34. type Aggregation struct {
  35. Aggregator string `json:"aggregation"`
  36. Subfields []string `json:"subfields,omitempty"`
  37. Environment string `json:"environment"`
  38. Cluster string `json:"cluster,omitempty"`
  39. Properties *kubecost.Properties `json:"-"`
  40. CPUAllocationHourlyAverage float64 `json:"cpuAllocationAverage"`
  41. CPUAllocationVectors []*util.Vector `json:"-"`
  42. CPUAllocationTotal float64 `json:"-"`
  43. CPUCost float64 `json:"cpuCost"`
  44. CPUCostVector []*util.Vector `json:"cpuCostVector,omitempty"`
  45. CPUEfficiency float64 `json:"cpuEfficiency"`
  46. CPURequestedVectors []*util.Vector `json:"-"`
  47. CPUUsedVectors []*util.Vector `json:"-"`
  48. Efficiency float64 `json:"efficiency"`
  49. GPUAllocationHourlyAverage float64 `json:"gpuAllocationAverage"`
  50. GPUAllocationVectors []*util.Vector `json:"-"`
  51. GPUCost float64 `json:"gpuCost"`
  52. GPUCostVector []*util.Vector `json:"gpuCostVector,omitempty"`
  53. GPUAllocationTotal float64 `json:"-"`
  54. RAMAllocationHourlyAverage float64 `json:"ramAllocationAverage"`
  55. RAMAllocationVectors []*util.Vector `json:"-"`
  56. RAMAllocationTotal float64 `json:"-"`
  57. RAMCost float64 `json:"ramCost"`
  58. RAMCostVector []*util.Vector `json:"ramCostVector,omitempty"`
  59. RAMEfficiency float64 `json:"ramEfficiency"`
  60. RAMRequestedVectors []*util.Vector `json:"-"`
  61. RAMUsedVectors []*util.Vector `json:"-"`
  62. PVAllocationHourlyAverage float64 `json:"pvAllocationAverage"`
  63. PVAllocationVectors []*util.Vector `json:"-"`
  64. PVAllocationTotal float64 `json:"-"`
  65. PVCost float64 `json:"pvCost"`
  66. PVCostVector []*util.Vector `json:"pvCostVector,omitempty"`
  67. NetworkCost float64 `json:"networkCost"`
  68. NetworkCostVector []*util.Vector `json:"networkCostVector,omitempty"`
  69. SharedCost float64 `json:"sharedCost"`
  70. TotalCost float64 `json:"totalCost"`
  71. TotalCostVector []*util.Vector `json:"totalCostVector,omitempty"`
  72. }
  73. // TotalHours determines the amount of hours the Aggregation covers, as a
  74. // function of the cost vectors and the resolution of those vectors' data
  75. func (a *Aggregation) TotalHours(resolutionHours float64) float64 {
  76. length := 1
  77. if length < len(a.CPUCostVector) {
  78. length = len(a.CPUCostVector)
  79. }
  80. if length < len(a.RAMCostVector) {
  81. length = len(a.RAMCostVector)
  82. }
  83. if length < len(a.PVCostVector) {
  84. length = len(a.PVCostVector)
  85. }
  86. if length < len(a.GPUCostVector) {
  87. length = len(a.GPUCostVector)
  88. }
  89. if length < len(a.NetworkCostVector) {
  90. length = len(a.NetworkCostVector)
  91. }
  92. return float64(length) * resolutionHours
  93. }
  94. // RateCoefficient computes the coefficient by which the total cost needs to be
  95. // multiplied in order to convert totals costs into per-rate costs.
  96. func (a *Aggregation) RateCoefficient(rateStr string, resolutionHours float64) float64 {
  97. // monthly rate = (730.0)*(total cost)/(total hours)
  98. // daily rate = (24.0)*(total cost)/(total hours)
  99. // hourly rate = (1.0)*(total cost)/(total hours)
  100. // default to hourly rate
  101. coeff := 1.0
  102. switch rateStr {
  103. case "daily":
  104. coeff = util.HoursPerDay
  105. case "monthly":
  106. coeff = util.HoursPerMonth
  107. }
  108. return coeff / a.TotalHours(resolutionHours)
  109. }
  110. type SharedResourceInfo struct {
  111. ShareResources bool
  112. SharedNamespace map[string]bool
  113. LabelSelectors map[string]map[string]bool
  114. }
  115. type SharedCostInfo struct {
  116. Name string
  117. Cost float64
  118. ShareType string
  119. }
  120. func (s *SharedResourceInfo) IsSharedResource(costDatum *CostData) bool {
  121. // exists in a shared namespace
  122. if _, ok := s.SharedNamespace[costDatum.Namespace]; ok {
  123. return true
  124. }
  125. // has at least one shared label (OR, not AND in the case of multiple labels)
  126. for labelName, labelValues := range s.LabelSelectors {
  127. if val, ok := costDatum.Labels[labelName]; ok && labelValues[val] {
  128. return true
  129. }
  130. }
  131. return false
  132. }
  133. func NewSharedResourceInfo(shareResources bool, sharedNamespaces []string, labelNames []string, labelValues []string) *SharedResourceInfo {
  134. sr := &SharedResourceInfo{
  135. ShareResources: shareResources,
  136. SharedNamespace: make(map[string]bool),
  137. LabelSelectors: make(map[string]map[string]bool),
  138. }
  139. for _, ns := range sharedNamespaces {
  140. sr.SharedNamespace[strings.Trim(ns, " ")] = true
  141. }
  142. // Creating a map of label name to label value, but only if
  143. // the cardinality matches
  144. if len(labelNames) == len(labelValues) {
  145. for i := range labelNames {
  146. cleanedLname := SanitizeLabelName(strings.Trim(labelNames[i], " "))
  147. if values, ok := sr.LabelSelectors[cleanedLname]; ok {
  148. values[strings.Trim(labelValues[i], " ")] = true
  149. } else {
  150. sr.LabelSelectors[cleanedLname] = map[string]bool{strings.Trim(labelValues[i], " "): true}
  151. }
  152. }
  153. }
  154. return sr
  155. }
  156. func GetTotalContainerCost(costData map[string]*CostData, rate string, cp cloud.Provider, discount float64, customDiscount float64, idleCoefficients map[string]float64) float64 {
  157. totalContainerCost := 0.0
  158. for _, costDatum := range costData {
  159. clusterID := costDatum.ClusterID
  160. cpuv, ramv, gpuv, pvvs, netv := getPriceVectors(cp, costDatum, rate, discount, customDiscount, idleCoefficients[clusterID])
  161. totalContainerCost += totalVectors(cpuv)
  162. totalContainerCost += totalVectors(ramv)
  163. totalContainerCost += totalVectors(gpuv)
  164. for _, pv := range pvvs {
  165. totalContainerCost += totalVectors(pv)
  166. }
  167. totalContainerCost += totalVectors(netv)
  168. }
  169. return totalContainerCost
  170. }
  171. func (a *Accesses) ComputeIdleCoefficient(costData map[string]*CostData, cli prometheusClient.Client, cp cloud.Provider, discount float64, customDiscount float64, windowString, offset string) (map[string]float64, error) {
  172. coefficients := make(map[string]float64)
  173. profileName := "ComputeIdleCoefficient: ComputeClusterCosts"
  174. profileStart := time.Now()
  175. var clusterCosts map[string]*ClusterCosts
  176. var err error
  177. key := fmt.Sprintf("%s:%s", windowString, offset)
  178. if data, valid := a.ClusterCostsCache.Get(key); valid {
  179. clusterCosts = data.(map[string]*ClusterCosts)
  180. } else {
  181. clusterCosts, err = a.ComputeClusterCosts(cli, cp, windowString, offset, false)
  182. if err != nil {
  183. return nil, err
  184. }
  185. }
  186. measureTime(profileStart, profileThreshold, profileName)
  187. for cid, costs := range clusterCosts {
  188. if costs.CPUCumulative == 0 && costs.RAMCumulative == 0 && costs.StorageCumulative == 0 {
  189. klog.V(1).Infof("[Warning] No ClusterCosts data for cluster '%s'. Is it emitting data?", cid)
  190. coefficients[cid] = 1.0
  191. continue
  192. }
  193. if costs.TotalCumulative == 0 {
  194. return nil, fmt.Errorf("TotalCumulative cluster cost for cluster '%s' returned 0 over window '%s' offset '%s'", cid, windowString, offset)
  195. }
  196. totalContainerCost := 0.0
  197. for _, costDatum := range costData {
  198. if costDatum.ClusterID == cid {
  199. cpuv, ramv, gpuv, pvvs, _ := getPriceVectors(cp, costDatum, "", discount, customDiscount, 1)
  200. totalContainerCost += totalVectors(cpuv)
  201. totalContainerCost += totalVectors(ramv)
  202. totalContainerCost += totalVectors(gpuv)
  203. for _, pv := range pvvs {
  204. totalContainerCost += totalVectors(pv)
  205. }
  206. }
  207. }
  208. coeff := totalContainerCost / costs.TotalCumulative
  209. coefficients[cid] = coeff
  210. }
  211. return coefficients, nil
  212. }
  213. // AggregationOptions provides optional parameters to AggregateCostData, allowing callers to perform more complex operations
  214. type AggregationOptions struct {
  215. Discount float64 // percent by which to discount CPU, RAM, and GPU cost
  216. CustomDiscount float64 // additional custom discount applied to all prices
  217. IdleCoefficients map[string]float64 // scales costs by amount of idle resources on a per-cluster basis
  218. IncludeEfficiency bool // set to true to receive efficiency/usage data
  219. IncludeTimeSeries bool // set to true to receive time series data
  220. Rate string // set to "hourly", "daily", or "monthly" to receive cost rate, rather than cumulative cost
  221. ResolutionHours float64
  222. SharedResourceInfo *SharedResourceInfo
  223. SharedCosts map[string]*SharedCostInfo
  224. FilteredContainerCount int
  225. FilteredEnvironments map[string]int
  226. SharedSplit string
  227. TotalContainerCost float64
  228. }
  229. // Helper method to test request/usgae values against allocation averages for efficiency scores. Generate a warning log if
  230. // clamp is required
  231. func clampAverage(requestsAvg float64, usedAverage float64, allocationAvg float64, resource string) (float64, float64) {
  232. rAvg := requestsAvg
  233. if rAvg > allocationAvg {
  234. klog.V(4).Infof("[Warning] Average %s Requested (%f) > Average %s Allocated (%f). Clamping.", resource, rAvg, resource, allocationAvg)
  235. rAvg = allocationAvg
  236. }
  237. uAvg := usedAverage
  238. if uAvg > allocationAvg {
  239. klog.V(4).Infof("[Warning]: Average %s Used (%f) > Average %s Allocated (%f). Clamping.", resource, uAvg, resource, allocationAvg)
  240. uAvg = allocationAvg
  241. }
  242. return rAvg, uAvg
  243. }
  244. // AggregateCostData aggregates raw cost data by field; e.g. namespace, cluster, service, or label. In the case of label, callers
  245. // must pass a slice of subfields indicating the labels by which to group. Provider is used to define custom resource pricing.
  246. // See AggregationOptions for optional parameters.
  247. func AggregateCostData(costData map[string]*CostData, field string, subfields []string, cp cloud.Provider, opts *AggregationOptions) map[string]*Aggregation {
  248. discount := opts.Discount
  249. customDiscount := opts.CustomDiscount
  250. idleCoefficients := opts.IdleCoefficients
  251. includeTimeSeries := opts.IncludeTimeSeries
  252. includeEfficiency := opts.IncludeEfficiency
  253. rate := opts.Rate
  254. sr := opts.SharedResourceInfo
  255. resolutionHours := 1.0
  256. if opts.ResolutionHours > 0.0 {
  257. resolutionHours = opts.ResolutionHours
  258. }
  259. if idleCoefficients == nil {
  260. idleCoefficients = make(map[string]float64)
  261. }
  262. // aggregations collects key-value pairs of resource group-to-aggregated data
  263. // e.g. namespace-to-data or label-value-to-data
  264. aggregations := make(map[string]*Aggregation)
  265. // sharedResourceCost is the running total cost of resources that should be reported
  266. // as shared across all other resources, rather than reported as a stand-alone category
  267. sharedResourceCost := 0.0
  268. for _, costDatum := range costData {
  269. idleCoefficient, ok := idleCoefficients[costDatum.ClusterID]
  270. if !ok {
  271. idleCoefficient = 1.0
  272. }
  273. if sr != nil && sr.ShareResources && sr.IsSharedResource(costDatum) {
  274. cpuv, ramv, gpuv, pvvs, netv := getPriceVectors(cp, costDatum, rate, discount, customDiscount, idleCoefficient)
  275. sharedResourceCost += totalVectors(cpuv)
  276. sharedResourceCost += totalVectors(ramv)
  277. sharedResourceCost += totalVectors(gpuv)
  278. sharedResourceCost += totalVectors(netv)
  279. for _, pv := range pvvs {
  280. sharedResourceCost += totalVectors(pv)
  281. }
  282. } else {
  283. if field == "cluster" {
  284. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.ClusterID, discount, customDiscount, idleCoefficient, false)
  285. } else if field == "node" {
  286. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.NodeName, discount, customDiscount, idleCoefficient, false)
  287. } else if field == "namespace" {
  288. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace, discount, customDiscount, idleCoefficient, false)
  289. } else if field == "service" {
  290. if len(costDatum.Services) > 0 {
  291. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace+"/"+costDatum.Services[0], discount, customDiscount, idleCoefficient, false)
  292. } else {
  293. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  294. }
  295. } else if field == "deployment" {
  296. if len(costDatum.Deployments) > 0 {
  297. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace+"/"+costDatum.Deployments[0], discount, customDiscount, idleCoefficient, false)
  298. } else {
  299. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  300. }
  301. } else if field == "statefulset" {
  302. if len(costDatum.Statefulsets) > 0 {
  303. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace+"/"+costDatum.Statefulsets[0], discount, customDiscount, idleCoefficient, false)
  304. } else {
  305. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  306. }
  307. } else if field == "daemonset" {
  308. if len(costDatum.Daemonsets) > 0 {
  309. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace+"/"+costDatum.Daemonsets[0], discount, customDiscount, idleCoefficient, false)
  310. } else {
  311. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  312. }
  313. } else if field == "controller" {
  314. if controller, kind, hasController := costDatum.GetController(); hasController {
  315. key := fmt.Sprintf("%s/%s:%s", costDatum.Namespace, kind, controller)
  316. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, key, discount, customDiscount, idleCoefficient, false)
  317. } else {
  318. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  319. }
  320. } else if field == "label" {
  321. found := false
  322. if costDatum.Labels != nil {
  323. for _, sf := range subfields {
  324. if subfieldName, ok := costDatum.Labels[sf]; ok {
  325. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, subfieldName, discount, customDiscount, idleCoefficient, false)
  326. found = true
  327. break
  328. }
  329. }
  330. }
  331. if !found {
  332. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, UnallocatedSubfield, discount, customDiscount, idleCoefficient, false)
  333. }
  334. } else if field == "pod" {
  335. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, costDatum.Namespace+"/"+costDatum.PodName, discount, customDiscount, idleCoefficient, false)
  336. } else if field == "container" {
  337. key := fmt.Sprintf("%s/%s/%s/%s", costDatum.ClusterID, costDatum.Namespace, costDatum.PodName, costDatum.Name)
  338. aggregateDatum(cp, aggregations, costDatum, field, subfields, rate, key, discount, customDiscount, idleCoefficient, true)
  339. }
  340. }
  341. }
  342. for key, agg := range aggregations {
  343. sharedCoefficient := 1 / float64(len(opts.FilteredEnvironments)+len(aggregations))
  344. agg.CPUCost = totalVectors(agg.CPUCostVector)
  345. agg.RAMCost = totalVectors(agg.RAMCostVector)
  346. agg.GPUCost = totalVectors(agg.GPUCostVector)
  347. agg.PVCost = totalVectors(agg.PVCostVector)
  348. agg.NetworkCost = totalVectors(agg.NetworkCostVector)
  349. if opts.SharedSplit == SplitTypeWeighted {
  350. d := opts.TotalContainerCost - sharedResourceCost
  351. if d == 0 {
  352. klog.V(1).Infof("[Warning] Total container cost '%f' and shared resource cost '%f are the same'. Setting sharedCoefficient to 1", opts.TotalContainerCost, sharedResourceCost)
  353. sharedCoefficient = 1.0
  354. } else {
  355. sharedCoefficient = (agg.CPUCost + agg.RAMCost + agg.GPUCost + agg.PVCost + agg.NetworkCost) / d
  356. }
  357. }
  358. agg.SharedCost = sharedResourceCost * sharedCoefficient
  359. for _, v := range opts.SharedCosts {
  360. agg.SharedCost += v.Cost * sharedCoefficient
  361. }
  362. if rate != "" {
  363. rateCoeff := agg.RateCoefficient(rate, resolutionHours)
  364. agg.CPUCost *= rateCoeff
  365. agg.RAMCost *= rateCoeff
  366. agg.GPUCost *= rateCoeff
  367. agg.PVCost *= rateCoeff
  368. agg.NetworkCost *= rateCoeff
  369. agg.SharedCost *= rateCoeff
  370. }
  371. agg.TotalCost = agg.CPUCost + agg.RAMCost + agg.GPUCost + agg.PVCost + agg.NetworkCost + agg.SharedCost
  372. // Evicted and Completed Pods can still show up here, but have 0 cost.
  373. // Filter these by default. Any reason to keep them?
  374. if agg.TotalCost == 0 {
  375. delete(aggregations, key)
  376. continue
  377. }
  378. // CPU, RAM, and PV allocation are cumulative per-datum, whereas GPU is rate per-datum
  379. agg.CPUAllocationHourlyAverage = totalVectors(agg.CPUAllocationVectors) / agg.TotalHours(resolutionHours)
  380. agg.RAMAllocationHourlyAverage = totalVectors(agg.RAMAllocationVectors) / agg.TotalHours(resolutionHours)
  381. agg.GPUAllocationHourlyAverage = averageVectors(agg.GPUAllocationVectors)
  382. agg.PVAllocationHourlyAverage = totalVectors(agg.PVAllocationVectors) / agg.TotalHours(resolutionHours)
  383. // TODO niko/etl does this check out for GPU data? Do we need to rewrite GPU queries to be
  384. // culumative?
  385. agg.CPUAllocationTotal = totalVectors(agg.CPUAllocationVectors)
  386. agg.GPUAllocationTotal = totalVectors(agg.GPUAllocationVectors)
  387. agg.PVAllocationTotal = totalVectors(agg.PVAllocationVectors)
  388. agg.RAMAllocationTotal = totalVectors(agg.RAMAllocationVectors)
  389. if includeEfficiency {
  390. // Default both RAM and CPU to 0% efficiency so that a 0-requested, 0-allocated, 0-used situation
  391. // returns 0% efficiency, which should be a red-flag.
  392. //
  393. // If non-zero numbers are available, then efficiency is defined as:
  394. // idlePercentage = (requested - used) / allocated
  395. // efficiency = (1.0 - idlePercentage)
  396. //
  397. // It is possible to score > 100% efficiency, which is meant to be interpreted as a red flag.
  398. // It is not possible to score < 0% efficiency.
  399. agg.CPUEfficiency = 0.0
  400. CPUIdle := 0.0
  401. if agg.CPUAllocationHourlyAverage > 0.0 {
  402. avgCPURequested := averageVectors(agg.CPURequestedVectors)
  403. avgCPUUsed := averageVectors(agg.CPUUsedVectors)
  404. // Clamp averages, log range violations
  405. avgCPURequested, avgCPUUsed = clampAverage(avgCPURequested, avgCPUUsed, agg.CPUAllocationHourlyAverage, "CPU")
  406. CPUIdle = ((avgCPURequested - avgCPUUsed) / agg.CPUAllocationHourlyAverage)
  407. agg.CPUEfficiency = 1.0 - CPUIdle
  408. }
  409. agg.RAMEfficiency = 0.0
  410. RAMIdle := 0.0
  411. if agg.RAMAllocationHourlyAverage > 0.0 {
  412. avgRAMRequested := averageVectors(agg.RAMRequestedVectors)
  413. avgRAMUsed := averageVectors(agg.RAMUsedVectors)
  414. // Clamp averages, log range violations
  415. avgRAMRequested, avgRAMUsed = clampAverage(avgRAMRequested, avgRAMUsed, agg.RAMAllocationHourlyAverage, "RAM")
  416. RAMIdle = ((avgRAMRequested - avgRAMUsed) / agg.RAMAllocationHourlyAverage)
  417. agg.RAMEfficiency = 1.0 - RAMIdle
  418. }
  419. // Score total efficiency by the sum of CPU and RAM efficiency, weighted by their
  420. // respective total costs.
  421. agg.Efficiency = 0.0
  422. if (agg.CPUCost + agg.RAMCost) > 0 {
  423. agg.Efficiency = ((agg.CPUCost * agg.CPUEfficiency) + (agg.RAMCost * agg.RAMEfficiency)) / (agg.CPUCost + agg.RAMCost)
  424. }
  425. }
  426. // convert RAM from bytes to GiB
  427. agg.RAMAllocationHourlyAverage = agg.RAMAllocationHourlyAverage / 1024 / 1024 / 1024
  428. // convert storage from bytes to GiB
  429. agg.PVAllocationHourlyAverage = agg.PVAllocationHourlyAverage / 1024 / 1024 / 1024
  430. // remove time series data if it is not explicitly requested
  431. if !includeTimeSeries {
  432. agg.CPUCostVector = nil
  433. agg.RAMCostVector = nil
  434. agg.GPUCostVector = nil
  435. agg.PVCostVector = nil
  436. agg.NetworkCostVector = nil
  437. agg.TotalCostVector = nil
  438. } else { // otherwise compute a totalcostvector
  439. v1 := addVectors(agg.CPUCostVector, agg.RAMCostVector)
  440. v2 := addVectors(v1, agg.GPUCostVector)
  441. v3 := addVectors(v2, agg.PVCostVector)
  442. v4 := addVectors(v3, agg.NetworkCostVector)
  443. agg.TotalCostVector = v4
  444. }
  445. // Typesafety checks
  446. if math.IsNaN(agg.CPUAllocationHourlyAverage) || math.IsInf(agg.CPUAllocationHourlyAverage, 0) {
  447. klog.V(1).Infof("[Warning] CPUAllocationHourlyAverage is %f for '%s: %s/%s'", agg.CPUAllocationHourlyAverage, agg.Cluster, agg.Aggregator, agg.Environment)
  448. agg.CPUAllocationHourlyAverage = 0
  449. }
  450. if math.IsNaN(agg.CPUCost) || math.IsInf(agg.CPUCost, 0) {
  451. klog.V(1).Infof("[Warning] CPUCost is %f for '%s: %s/%s'", agg.CPUCost, agg.Cluster, agg.Aggregator, agg.Environment)
  452. agg.CPUCost = 0
  453. }
  454. if math.IsNaN(agg.CPUEfficiency) || math.IsInf(agg.CPUEfficiency, 0) {
  455. klog.V(1).Infof("[Warning] CPUEfficiency is %f for '%s: %s/%s'", agg.CPUEfficiency, agg.Cluster, agg.Aggregator, agg.Environment)
  456. agg.CPUEfficiency = 0
  457. }
  458. if math.IsNaN(agg.Efficiency) || math.IsInf(agg.Efficiency, 0) {
  459. klog.V(1).Infof("[Warning] Efficiency is %f for '%s: %s/%s'", agg.Efficiency, agg.Cluster, agg.Aggregator, agg.Environment)
  460. agg.Efficiency = 0
  461. }
  462. if math.IsNaN(agg.GPUAllocationHourlyAverage) || math.IsInf(agg.GPUAllocationHourlyAverage, 0) {
  463. klog.V(1).Infof("[Warning] GPUAllocationHourlyAverage is %f for '%s: %s/%s'", agg.GPUAllocationHourlyAverage, agg.Cluster, agg.Aggregator, agg.Environment)
  464. agg.GPUAllocationHourlyAverage = 0
  465. }
  466. if math.IsNaN(agg.GPUCost) || math.IsInf(agg.GPUCost, 0) {
  467. klog.V(1).Infof("[Warning] GPUCost is %f for '%s: %s/%s'", agg.GPUCost, agg.Cluster, agg.Aggregator, agg.Environment)
  468. agg.GPUCost = 0
  469. }
  470. if math.IsNaN(agg.RAMAllocationHourlyAverage) || math.IsInf(agg.RAMAllocationHourlyAverage, 0) {
  471. klog.V(1).Infof("[Warning] RAMAllocationHourlyAverage is %f for '%s: %s/%s'", agg.RAMAllocationHourlyAverage, agg.Cluster, agg.Aggregator, agg.Environment)
  472. agg.RAMAllocationHourlyAverage = 0
  473. }
  474. if math.IsNaN(agg.RAMCost) || math.IsInf(agg.RAMCost, 0) {
  475. klog.V(1).Infof("[Warning] RAMCost is %f for '%s: %s/%s'", agg.RAMCost, agg.Cluster, agg.Aggregator, agg.Environment)
  476. agg.RAMCost = 0
  477. }
  478. if math.IsNaN(agg.RAMEfficiency) || math.IsInf(agg.RAMEfficiency, 0) {
  479. klog.V(1).Infof("[Warning] RAMEfficiency is %f for '%s: %s/%s'", agg.RAMEfficiency, agg.Cluster, agg.Aggregator, agg.Environment)
  480. agg.RAMEfficiency = 0
  481. }
  482. if math.IsNaN(agg.PVAllocationHourlyAverage) || math.IsInf(agg.PVAllocationHourlyAverage, 0) {
  483. klog.V(1).Infof("[Warning] PVAllocationHourlyAverage is %f for '%s: %s/%s'", agg.PVAllocationHourlyAverage, agg.Cluster, agg.Aggregator, agg.Environment)
  484. agg.PVAllocationHourlyAverage = 0
  485. }
  486. if math.IsNaN(agg.PVCost) || math.IsInf(agg.PVCost, 0) {
  487. klog.V(1).Infof("[Warning] PVCost is %f for '%s: %s/%s'", agg.PVCost, agg.Cluster, agg.Aggregator, agg.Environment)
  488. agg.PVCost = 0
  489. }
  490. if math.IsNaN(agg.NetworkCost) || math.IsInf(agg.NetworkCost, 0) {
  491. klog.V(1).Infof("[Warning] NetworkCost is %f for '%s: %s/%s'", agg.NetworkCost, agg.Cluster, agg.Aggregator, agg.Environment)
  492. agg.NetworkCost = 0
  493. }
  494. if math.IsNaN(agg.SharedCost) || math.IsInf(agg.SharedCost, 0) {
  495. klog.V(1).Infof("[Warning] SharedCost is %f for '%s: %s/%s'", agg.SharedCost, agg.Cluster, agg.Aggregator, agg.Environment)
  496. agg.SharedCost = 0
  497. }
  498. if math.IsNaN(agg.TotalCost) || math.IsInf(agg.TotalCost, 0) {
  499. klog.V(1).Infof("[Warning] TotalCost is %f for '%s: %s/%s'", agg.TotalCost, agg.Cluster, agg.Aggregator, agg.Environment)
  500. agg.TotalCost = 0
  501. }
  502. }
  503. return aggregations
  504. }
  505. func aggregateDatum(cp cloud.Provider, aggregations map[string]*Aggregation, costDatum *CostData, field string, subfields []string, rate string, key string, discount float64, customDiscount float64, idleCoefficient float64, includeProperties bool) {
  506. // add new entry to aggregation results if a new key is encountered
  507. if _, ok := aggregations[key]; !ok {
  508. agg := &Aggregation{
  509. Aggregator: field,
  510. Environment: key,
  511. }
  512. if len(subfields) > 0 {
  513. agg.Subfields = subfields
  514. }
  515. if includeProperties {
  516. props := &kubecost.Properties{}
  517. props.SetCluster(costDatum.ClusterID)
  518. props.SetNode(costDatum.NodeName)
  519. if controller, kind, hasController := costDatum.GetController(); hasController {
  520. props.SetController(controller)
  521. props.SetControllerKind(kind)
  522. }
  523. props.SetLabels(costDatum.Labels)
  524. props.SetNamespace(costDatum.Namespace)
  525. props.SetPod(costDatum.PodName)
  526. props.SetServices(costDatum.Services)
  527. props.SetContainer(costDatum.Name)
  528. agg.Properties = props
  529. }
  530. aggregations[key] = agg
  531. }
  532. mergeVectors(cp, costDatum, aggregations[key], rate, discount, customDiscount, idleCoefficient)
  533. }
  534. func mergeVectors(cp cloud.Provider, costDatum *CostData, aggregation *Aggregation, rate string, discount float64, customDiscount float64, idleCoefficient float64) {
  535. aggregation.CPUAllocationVectors = addVectors(costDatum.CPUAllocation, aggregation.CPUAllocationVectors)
  536. aggregation.CPURequestedVectors = addVectors(costDatum.CPUReq, aggregation.CPURequestedVectors)
  537. aggregation.CPUUsedVectors = addVectors(costDatum.CPUUsed, aggregation.CPUUsedVectors)
  538. aggregation.RAMAllocationVectors = addVectors(costDatum.RAMAllocation, aggregation.RAMAllocationVectors)
  539. aggregation.RAMRequestedVectors = addVectors(costDatum.RAMReq, aggregation.RAMRequestedVectors)
  540. aggregation.RAMUsedVectors = addVectors(costDatum.RAMUsed, aggregation.RAMUsedVectors)
  541. aggregation.GPUAllocationVectors = addVectors(costDatum.GPUReq, aggregation.GPUAllocationVectors)
  542. for _, pvcd := range costDatum.PVCData {
  543. aggregation.PVAllocationVectors = addVectors(pvcd.Values, aggregation.PVAllocationVectors)
  544. }
  545. cpuv, ramv, gpuv, pvvs, netv := getPriceVectors(cp, costDatum, rate, discount, customDiscount, idleCoefficient)
  546. aggregation.CPUCostVector = addVectors(cpuv, aggregation.CPUCostVector)
  547. aggregation.RAMCostVector = addVectors(ramv, aggregation.RAMCostVector)
  548. aggregation.GPUCostVector = addVectors(gpuv, aggregation.GPUCostVector)
  549. aggregation.NetworkCostVector = addVectors(netv, aggregation.NetworkCostVector)
  550. for _, vectorList := range pvvs {
  551. aggregation.PVCostVector = addVectors(aggregation.PVCostVector, vectorList)
  552. }
  553. }
  554. // Returns the blended discounts applied to the node as a result of global discounts and reserved instance
  555. // discounts
  556. func getDiscounts(costDatum *CostData, cpuCost float64, ramCost float64, discount float64) (float64, float64) {
  557. if costDatum.NodeData == nil {
  558. return discount, discount
  559. }
  560. if costDatum.NodeData.IsSpot() {
  561. return 0, 0
  562. }
  563. reserved := costDatum.NodeData.Reserved
  564. // blended discounts
  565. blendedCPUDiscount := discount
  566. blendedRAMDiscount := discount
  567. if reserved != nil && reserved.CPUCost > 0 && reserved.RAMCost > 0 {
  568. reservedCPUDiscount := 0.0
  569. if cpuCost == 0 {
  570. klog.V(1).Infof("[Warning] No cpu cost found for cluster '%s' node '%s'", costDatum.ClusterID, costDatum.NodeName)
  571. } else {
  572. reservedCPUDiscount = 1.0 - (reserved.CPUCost / cpuCost)
  573. }
  574. reservedRAMDiscount := 0.0
  575. if ramCost == 0 {
  576. klog.V(1).Infof("[Warning] No ram cost found for cluster '%s' node '%s'", costDatum.ClusterID, costDatum.NodeName)
  577. } else {
  578. reservedRAMDiscount = 1.0 - (reserved.RAMCost / ramCost)
  579. }
  580. // AWS passes the # of reserved CPU and RAM as -1 to represent "All"
  581. if reserved.ReservedCPU < 0 && reserved.ReservedRAM < 0 {
  582. blendedCPUDiscount = reservedCPUDiscount
  583. blendedRAMDiscount = reservedRAMDiscount
  584. } else {
  585. nodeCPU, ierr := strconv.ParseInt(costDatum.NodeData.VCPU, 10, 64)
  586. nodeRAM, ferr := strconv.ParseFloat(costDatum.NodeData.RAMBytes, 64)
  587. if ierr == nil && ferr == nil {
  588. nodeRAMGB := nodeRAM / 1024 / 1024 / 1024
  589. reservedRAMGB := float64(reserved.ReservedRAM) / 1024 / 1024 / 1024
  590. nonReservedCPU := nodeCPU - reserved.ReservedCPU
  591. nonReservedRAM := nodeRAMGB - reservedRAMGB
  592. if nonReservedCPU == 0 {
  593. blendedCPUDiscount = reservedCPUDiscount
  594. } else {
  595. if nodeCPU == 0 {
  596. klog.V(1).Infof("[Warning] No ram found for cluster '%s' node '%s'", costDatum.ClusterID, costDatum.NodeName)
  597. } else {
  598. blendedCPUDiscount = (float64(reserved.ReservedCPU) * reservedCPUDiscount) + (float64(nonReservedCPU)*discount)/float64(nodeCPU)
  599. }
  600. }
  601. if nonReservedRAM == 0 {
  602. blendedRAMDiscount = reservedRAMDiscount
  603. } else {
  604. if nodeRAMGB == 0 {
  605. klog.V(1).Infof("[Warning] No ram found for cluster '%s' node '%s'", costDatum.ClusterID, costDatum.NodeName)
  606. } else {
  607. blendedRAMDiscount = (reservedRAMGB * reservedRAMDiscount) + (nonReservedRAM*discount)/nodeRAMGB
  608. }
  609. }
  610. }
  611. }
  612. }
  613. return blendedCPUDiscount, blendedRAMDiscount
  614. }
  615. func parseVectorPricing(cfg *cloud.CustomPricing, costDatum *CostData, cpuCostStr, ramCostStr, gpuCostStr, pvCostStr string) (float64, float64, float64, float64, bool) {
  616. usesCustom := false
  617. cpuCost, err := strconv.ParseFloat(cpuCostStr, 64)
  618. if err != nil || math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) || cpuCost == 0 {
  619. cpuCost, err = strconv.ParseFloat(cfg.CPU, 64)
  620. usesCustom = true
  621. if err != nil || math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  622. cpuCost = 0
  623. }
  624. }
  625. ramCost, err := strconv.ParseFloat(ramCostStr, 64)
  626. if err != nil || math.IsNaN(ramCost) || math.IsInf(ramCost, 0) || ramCost == 0 {
  627. ramCost, err = strconv.ParseFloat(cfg.RAM, 64)
  628. usesCustom = true
  629. if err != nil || math.IsNaN(ramCost) || math.IsInf(ramCost, 0) {
  630. ramCost = 0
  631. }
  632. }
  633. gpuCost, err := strconv.ParseFloat(gpuCostStr, 64)
  634. if err != nil || math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  635. gpuCost, err = strconv.ParseFloat(cfg.GPU, 64)
  636. if err != nil || math.IsNaN(gpuCost) || math.IsInf(gpuCost, 0) {
  637. gpuCost = 0
  638. }
  639. }
  640. pvCost, err := strconv.ParseFloat(pvCostStr, 64)
  641. if err != nil || math.IsNaN(cpuCost) || math.IsInf(cpuCost, 0) {
  642. pvCost, err = strconv.ParseFloat(cfg.Storage, 64)
  643. if err != nil || math.IsNaN(pvCost) || math.IsInf(pvCost, 0) {
  644. pvCost = 0
  645. }
  646. }
  647. return cpuCost, ramCost, gpuCost, pvCost, usesCustom
  648. }
  649. func getPriceVectors(cp cloud.Provider, costDatum *CostData, rate string, discount float64, customDiscount float64, idleCoefficient float64) ([]*util.Vector, []*util.Vector, []*util.Vector, [][]*util.Vector, []*util.Vector) {
  650. var cpuCost float64
  651. var ramCost float64
  652. var gpuCost float64
  653. var pvCost float64
  654. var usesCustom bool
  655. // If custom pricing is enabled and can be retrieved, replace
  656. // default cost values with custom values
  657. customPricing, err := cp.GetConfig()
  658. if err != nil {
  659. klog.Errorf("failed to load custom pricing: %s", err)
  660. }
  661. if cloud.CustomPricesEnabled(cp) && err == nil {
  662. var cpuCostStr string
  663. var ramCostStr string
  664. var gpuCostStr string
  665. var pvCostStr string
  666. if costDatum.NodeData.IsSpot() {
  667. cpuCostStr = customPricing.SpotCPU
  668. ramCostStr = customPricing.SpotRAM
  669. gpuCostStr = customPricing.SpotGPU
  670. } else {
  671. cpuCostStr = customPricing.CPU
  672. ramCostStr = customPricing.RAM
  673. gpuCostStr = customPricing.GPU
  674. }
  675. pvCostStr = customPricing.Storage
  676. cpuCost, ramCost, gpuCost, pvCost, usesCustom = parseVectorPricing(customPricing, costDatum, cpuCostStr, ramCostStr, gpuCostStr, pvCostStr)
  677. } else if costDatum.NodeData == nil && err == nil {
  678. cpuCostStr := customPricing.CPU
  679. ramCostStr := customPricing.RAM
  680. gpuCostStr := customPricing.GPU
  681. pvCostStr := customPricing.Storage
  682. cpuCost, ramCost, gpuCost, pvCost, usesCustom = parseVectorPricing(customPricing, costDatum, cpuCostStr, ramCostStr, gpuCostStr, pvCostStr)
  683. } else {
  684. cpuCostStr := costDatum.NodeData.VCPUCost
  685. ramCostStr := costDatum.NodeData.RAMCost
  686. gpuCostStr := costDatum.NodeData.GPUCost
  687. pvCostStr := costDatum.NodeData.StorageCost
  688. cpuCost, ramCost, gpuCost, pvCost, usesCustom = parseVectorPricing(customPricing, costDatum, cpuCostStr, ramCostStr, gpuCostStr, pvCostStr)
  689. }
  690. if usesCustom {
  691. log.DedupedWarningf(5, "No pricing data found for node `%s` , using custom pricing", costDatum.NodeName)
  692. }
  693. cpuDiscount, ramDiscount := getDiscounts(costDatum, cpuCost, ramCost, discount)
  694. klog.V(4).Infof("Node Name: %s", costDatum.NodeName)
  695. klog.V(4).Infof("Blended CPU Discount: %f", cpuDiscount)
  696. klog.V(4).Infof("Blended RAM Discount: %f", ramDiscount)
  697. // TODO should we try to apply the rate coefficient here or leave it as a totals-only metric?
  698. rateCoeff := 1.0
  699. if idleCoefficient == 0 {
  700. idleCoefficient = 1.0
  701. }
  702. cpuv := make([]*util.Vector, 0, len(costDatum.CPUAllocation))
  703. for _, val := range costDatum.CPUAllocation {
  704. cpuv = append(cpuv, &util.Vector{
  705. Timestamp: math.Round(val.Timestamp/10) * 10,
  706. Value: (val.Value * cpuCost * (1 - cpuDiscount) * (1 - customDiscount) / idleCoefficient) * rateCoeff,
  707. })
  708. }
  709. ramv := make([]*util.Vector, 0, len(costDatum.RAMAllocation))
  710. for _, val := range costDatum.RAMAllocation {
  711. ramv = append(ramv, &util.Vector{
  712. Timestamp: math.Round(val.Timestamp/10) * 10,
  713. Value: ((val.Value / 1024 / 1024 / 1024) * ramCost * (1 - ramDiscount) * (1 - customDiscount) / idleCoefficient) * rateCoeff,
  714. })
  715. }
  716. gpuv := make([]*util.Vector, 0, len(costDatum.GPUReq))
  717. for _, val := range costDatum.GPUReq {
  718. gpuv = append(gpuv, &util.Vector{
  719. Timestamp: math.Round(val.Timestamp/10) * 10,
  720. Value: (val.Value * gpuCost * (1 - discount) * (1 - customDiscount) / idleCoefficient) * rateCoeff,
  721. })
  722. }
  723. pvvs := make([][]*util.Vector, 0, len(costDatum.PVCData))
  724. for _, pvcData := range costDatum.PVCData {
  725. pvv := make([]*util.Vector, 0, len(pvcData.Values))
  726. if pvcData.Volume != nil {
  727. cost, _ := strconv.ParseFloat(pvcData.Volume.Cost, 64)
  728. // override with custom pricing if enabled
  729. if cloud.CustomPricesEnabled(cp) {
  730. cost = pvCost
  731. }
  732. for _, val := range pvcData.Values {
  733. pvv = append(pvv, &util.Vector{
  734. Timestamp: math.Round(val.Timestamp/10) * 10,
  735. Value: ((val.Value / 1024 / 1024 / 1024) * cost * (1 - customDiscount) / idleCoefficient) * rateCoeff,
  736. })
  737. }
  738. pvvs = append(pvvs, pvv)
  739. }
  740. }
  741. netv := make([]*util.Vector, 0, len(costDatum.NetworkData))
  742. for _, val := range costDatum.NetworkData {
  743. netv = append(netv, &util.Vector{
  744. Timestamp: math.Round(val.Timestamp/10) * 10,
  745. Value: val.Value,
  746. })
  747. }
  748. return cpuv, ramv, gpuv, pvvs, netv
  749. }
  750. func averageVectors(vectors []*util.Vector) float64 {
  751. if len(vectors) == 0 {
  752. return 0.0
  753. }
  754. return totalVectors(vectors) / float64(len(vectors))
  755. }
  756. func totalVectors(vectors []*util.Vector) float64 {
  757. total := 0.0
  758. for _, vector := range vectors {
  759. total += vector.Value
  760. }
  761. return total
  762. }
  763. // addVectors adds two slices of Vectors. Vector timestamps are rounded to the
  764. // nearest ten seconds to allow matching of Vectors within a delta allowance.
  765. // Matching Vectors are summed, while unmatched Vectors are passed through.
  766. // e.g. [(t=1, 1), (t=2, 2)] + [(t=2, 2), (t=3, 3)] = [(t=1, 1), (t=2, 4), (t=3, 3)]
  767. func addVectors(xvs []*util.Vector, yvs []*util.Vector) []*util.Vector {
  768. sumOp := func(result *util.Vector, x *float64, y *float64) bool {
  769. if x != nil && y != nil {
  770. result.Value = *x + *y
  771. } else if y != nil {
  772. result.Value = *y
  773. } else if x != nil {
  774. result.Value = *x
  775. }
  776. return true
  777. }
  778. return util.ApplyVectorOp(xvs, yvs, sumOp)
  779. }
  780. // minCostDataLength sets the minimum number of time series data required to
  781. // cache both raw and aggregated cost data
  782. const minCostDataLength = 2
  783. // EmptyDataError describes an error caused by empty cost data for some
  784. // defined interval
  785. type EmptyDataError struct {
  786. err error
  787. duration string
  788. offset string
  789. }
  790. // Error implements the error interface
  791. func (ede *EmptyDataError) Error() string {
  792. err := fmt.Sprintf("empty data for range: %s", ede.duration)
  793. if ede.offset != "" {
  794. err += fmt.Sprintf(" offset %s", ede.offset)
  795. }
  796. if ede.err != nil {
  797. err += fmt.Sprintf(": %s", ede.err)
  798. }
  799. return err
  800. }
  801. func costDataTimeSeriesLength(costData map[string]*CostData) int {
  802. l := 0
  803. for _, cd := range costData {
  804. if l < len(cd.RAMAllocation) {
  805. l = len(cd.RAMAllocation)
  806. }
  807. if l < len(cd.CPUAllocation) {
  808. l = len(cd.CPUAllocation)
  809. }
  810. }
  811. return l
  812. }
  813. // ScaleHourlyCostData converts per-hour cost data to per-resolution data. If the target resolution is higher (i.e. < 1.0h)
  814. // then we can do simple multiplication by the fraction-of-an-hour and retain accuracy. If the target resolution is
  815. // lower (i.e. > 1.0h) then we sum groups of hourly data by resolution to maintain fidelity.
  816. // e.g. (100 hours of per-hour hourly data, resolutionHours=10) => 10 data points, grouped and summed by 10-hour window
  817. // e.g. (20 minutes of per-minute hourly data, resolutionHours=1/60) => 20 data points, scaled down by a factor of 60
  818. func ScaleHourlyCostData(data map[string]*CostData, resolutionHours float64) map[string]*CostData {
  819. scaled := map[string]*CostData{}
  820. for key, datum := range data {
  821. datum.RAMReq = scaleVectorSeries(datum.RAMReq, resolutionHours)
  822. datum.RAMUsed = scaleVectorSeries(datum.RAMUsed, resolutionHours)
  823. datum.RAMAllocation = scaleVectorSeries(datum.RAMAllocation, resolutionHours)
  824. datum.CPUReq = scaleVectorSeries(datum.CPUReq, resolutionHours)
  825. datum.CPUUsed = scaleVectorSeries(datum.CPUUsed, resolutionHours)
  826. datum.CPUAllocation = scaleVectorSeries(datum.CPUAllocation, resolutionHours)
  827. datum.GPUReq = scaleVectorSeries(datum.GPUReq, resolutionHours)
  828. datum.NetworkData = scaleVectorSeries(datum.NetworkData, resolutionHours)
  829. for _, pvcDatum := range datum.PVCData {
  830. pvcDatum.Values = scaleVectorSeries(pvcDatum.Values, resolutionHours)
  831. }
  832. scaled[key] = datum
  833. }
  834. return scaled
  835. }
  836. func scaleVectorSeries(vs []*util.Vector, resolutionHours float64) []*util.Vector {
  837. // if scaling to a lower resolution, compress the hourly data for maximum accuracy
  838. if resolutionHours > 1.0 {
  839. return compressVectorSeries(vs, resolutionHours)
  840. }
  841. // if scaling to a higher resolution, simply scale each value down by the fraction of an hour
  842. for _, v := range vs {
  843. v.Value *= resolutionHours
  844. }
  845. return vs
  846. }
  847. func compressVectorSeries(vs []*util.Vector, resolutionHours float64) []*util.Vector {
  848. if len(vs) == 0 {
  849. return vs
  850. }
  851. compressed := []*util.Vector{}
  852. threshold := float64(60 * 60 * resolutionHours)
  853. var acc *util.Vector
  854. for i, v := range vs {
  855. if acc == nil {
  856. // start a new accumulation from current datum
  857. acc = &util.Vector{
  858. Value: vs[i].Value,
  859. Timestamp: vs[i].Timestamp,
  860. }
  861. continue
  862. }
  863. if v.Timestamp-acc.Timestamp < threshold {
  864. // v should be accumulated in current datum
  865. acc.Value += v.Value
  866. } else {
  867. // v falls outside current datum's threshold; append and start a new one
  868. compressed = append(compressed, acc)
  869. acc = &util.Vector{
  870. Value: vs[i].Value,
  871. Timestamp: vs[i].Timestamp,
  872. }
  873. }
  874. }
  875. // append any remaining, incomplete accumulation
  876. if acc != nil {
  877. compressed = append(compressed, acc)
  878. }
  879. return compressed
  880. }
  881. // ComputeAggregateCostModel computes cost data for the given window, then aggregates it by the given fields.
  882. // Data is cached on two levels: the aggregation is cached as well as the underlying cost data.
  883. func (a *Accesses) ComputeAggregateCostModel(promClient prometheusClient.Client, duration, offset, field string, subfields []string, rate string, filters map[string]string,
  884. sri *SharedResourceInfo, shared string, allocateIdle, includeTimeSeries, includeEfficiency, disableCache, clearCache, noCache, noExpireCache, remoteEnabled, disableSharedOverhead bool) (map[string]*Aggregation, string, error) {
  885. profileBaseName := fmt.Sprintf("ComputeAggregateCostModel(duration=%s, offet=%s, field=%s)", duration, offset, field)
  886. defer measureTime(time.Now(), profileThreshold, profileBaseName)
  887. // parse cost data filters into FilterFuncs
  888. filterFuncs := []FilterFunc{}
  889. retainFuncs := []FilterFunc{}
  890. retainFuncs = append(retainFuncs, func(cd *CostData) (bool, string) {
  891. if sri != nil {
  892. return sri.IsSharedResource(cd), ""
  893. }
  894. return false, ""
  895. })
  896. aggregateEnvironment := func(costDatum *CostData) string {
  897. if field == "cluster" {
  898. return costDatum.ClusterID
  899. } else if field == "node" {
  900. return costDatum.NodeName
  901. } else if field == "namespace" {
  902. return costDatum.Namespace
  903. } else if field == "service" {
  904. if len(costDatum.Services) > 0 {
  905. return costDatum.Namespace + "/" + costDatum.Services[0]
  906. }
  907. } else if field == "deployment" {
  908. if len(costDatum.Deployments) > 0 {
  909. return costDatum.Namespace + "/" + costDatum.Deployments[0]
  910. }
  911. } else if field == "daemonset" {
  912. if len(costDatum.Daemonsets) > 0 {
  913. return costDatum.Namespace + "/" + costDatum.Daemonsets[0]
  914. }
  915. } else if field == "statefulset" {
  916. if len(costDatum.Statefulsets) > 0 {
  917. return costDatum.Namespace + "/" + costDatum.Statefulsets[0]
  918. }
  919. } else if field == "label" {
  920. if costDatum.Labels != nil {
  921. for _, sf := range subfields {
  922. if subfieldName, ok := costDatum.Labels[sf]; ok {
  923. return fmt.Sprintf("%s=%s", sf, subfieldName)
  924. }
  925. }
  926. }
  927. } else if field == "pod" {
  928. return costDatum.Namespace + "/" + costDatum.PodName
  929. } else if field == "container" {
  930. return costDatum.Namespace + "/" + costDatum.PodName + "/" + costDatum.Name
  931. }
  932. return ""
  933. }
  934. if filters["podprefix"] != "" {
  935. pps := []string{}
  936. for _, fp := range strings.Split(filters["podprefix"], ",") {
  937. if fp != "" {
  938. cleanedFilter := strings.TrimSpace(fp)
  939. pps = append(pps, cleanedFilter)
  940. }
  941. }
  942. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  943. aggEnv := aggregateEnvironment(cd)
  944. for _, pp := range pps {
  945. cleanedFilter := strings.TrimSpace(pp)
  946. if strings.HasPrefix(cd.PodName, cleanedFilter) {
  947. return true, aggEnv
  948. }
  949. }
  950. return false, aggEnv
  951. })
  952. }
  953. if filters["namespace"] != "" {
  954. // namespaces may be comma-separated, e.g. kubecost,default
  955. // multiple namespaces are evaluated as an OR relationship
  956. nss := strings.Split(filters["namespace"], ",")
  957. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  958. aggEnv := aggregateEnvironment(cd)
  959. for _, ns := range nss {
  960. nsTrim := strings.TrimSpace(ns)
  961. if cd.Namespace == nsTrim {
  962. return true, aggEnv
  963. } else if strings.HasSuffix(nsTrim, "*") { // trigger wildcard prefix filtering
  964. nsTrimAsterisk := strings.TrimSuffix(nsTrim, "*")
  965. if strings.HasPrefix(cd.Namespace, nsTrimAsterisk) {
  966. return true, aggEnv
  967. }
  968. }
  969. }
  970. return false, aggEnv
  971. })
  972. }
  973. if filters["node"] != "" {
  974. // nodes may be comma-separated, e.g. aws-node-1,aws-node-2
  975. // multiple nodes are evaluated as an OR relationship
  976. nodes := strings.Split(filters["node"], ",")
  977. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  978. aggEnv := aggregateEnvironment(cd)
  979. for _, node := range nodes {
  980. nodeTrim := strings.TrimSpace(node)
  981. if cd.NodeName == nodeTrim {
  982. return true, aggEnv
  983. } else if strings.HasSuffix(nodeTrim, "*") { // trigger wildcard prefix filtering
  984. nodeTrimAsterisk := strings.TrimSuffix(nodeTrim, "*")
  985. if strings.HasPrefix(cd.NodeName, nodeTrimAsterisk) {
  986. return true, aggEnv
  987. }
  988. }
  989. }
  990. return false, aggEnv
  991. })
  992. }
  993. if filters["cluster"] != "" {
  994. // clusters may be comma-separated, e.g. cluster-one,cluster-two
  995. // multiple clusters are evaluated as an OR relationship
  996. cs := strings.Split(filters["cluster"], ",")
  997. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  998. aggEnv := aggregateEnvironment(cd)
  999. for _, c := range cs {
  1000. cTrim := strings.TrimSpace(c)
  1001. id, name := cd.ClusterID, cd.ClusterName
  1002. if id == cTrim || name == cTrim {
  1003. return true, aggEnv
  1004. } else if strings.HasSuffix(cTrim, "*") { // trigger wildcard prefix filtering
  1005. cTrimAsterisk := strings.TrimSuffix(cTrim, "*")
  1006. if strings.HasPrefix(id, cTrimAsterisk) || strings.HasPrefix(name, cTrimAsterisk) {
  1007. return true, aggEnv
  1008. }
  1009. }
  1010. }
  1011. return false, aggEnv
  1012. })
  1013. }
  1014. if filters["labels"] != "" {
  1015. // labels are expected to be comma-separated and to take the form key=value
  1016. // e.g. app=cost-analyzer,app.kubernetes.io/instance=kubecost
  1017. // each different label will be applied as an AND
  1018. // multiple values for a single label will be evaluated as an OR
  1019. labelValues := map[string][]string{}
  1020. ls := strings.Split(filters["labels"], ",")
  1021. for _, l := range ls {
  1022. lTrim := strings.TrimSpace(l)
  1023. label := strings.Split(lTrim, "=")
  1024. if len(label) == 2 {
  1025. ln := SanitizeLabelName(strings.TrimSpace(label[0]))
  1026. lv := strings.TrimSpace(label[1])
  1027. labelValues[ln] = append(labelValues[ln], lv)
  1028. } else {
  1029. // label is not of the form name=value, so log it and move on
  1030. klog.V(2).Infof("[Warning] aggregate cost model: skipping illegal label filter: %s", l)
  1031. }
  1032. }
  1033. // Generate FilterFunc for each set of label filters by invoking a function instead of accessing
  1034. // values by closure to prevent reference-type looping bug.
  1035. // (see https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable)
  1036. for label, values := range labelValues {
  1037. ff := (func(l string, vs []string) FilterFunc {
  1038. return func(cd *CostData) (bool, string) {
  1039. ae := aggregateEnvironment(cd)
  1040. for _, v := range vs {
  1041. if v == "__unallocated__" { // Special case. __unallocated__ means return all pods without the attached label
  1042. if _, ok := cd.Labels[label]; !ok {
  1043. return true, ae
  1044. }
  1045. }
  1046. if cd.Labels[label] == v {
  1047. return true, ae
  1048. } else if strings.HasSuffix(v, "*") { // trigger wildcard prefix filtering
  1049. vTrim := strings.TrimSuffix(v, "*")
  1050. if strings.HasPrefix(cd.Labels[label], vTrim) {
  1051. return true, ae
  1052. }
  1053. }
  1054. }
  1055. return false, ae
  1056. }
  1057. })(label, values)
  1058. filterFuncs = append(filterFuncs, ff)
  1059. }
  1060. }
  1061. // clear cache prior to checking the cache so that a clearCache=true
  1062. // request always returns a freshly computed value
  1063. if clearCache {
  1064. a.AggregateCache.Flush()
  1065. a.CostDataCache.Flush()
  1066. }
  1067. cacheExpiry := a.GetCacheExpiration(duration)
  1068. if noExpireCache {
  1069. cacheExpiry = cache.NoExpiration
  1070. }
  1071. // parametrize cache key by all request parameters
  1072. aggKey := GenerateAggKey(aggKeyParams{
  1073. duration: duration,
  1074. offset: offset,
  1075. filters: filters,
  1076. field: field,
  1077. subfields: subfields,
  1078. rate: rate,
  1079. sri: sri,
  1080. shareType: shared,
  1081. idle: allocateIdle,
  1082. timeSeries: includeTimeSeries,
  1083. efficiency: includeEfficiency,
  1084. })
  1085. // convert duration and offset to start and end times
  1086. startTime, endTime, err := ParseTimeRange(duration, offset)
  1087. if err != nil {
  1088. return nil, "", fmt.Errorf("Error parsing duration (%s) and offset (%s): %s", duration, offset, err)
  1089. }
  1090. durationHours := endTime.Sub(*startTime).Hours()
  1091. thanosOffset := time.Now().Add(-thanos.OffsetDuration())
  1092. if a.ThanosClient != nil && endTime.After(thanosOffset) {
  1093. klog.V(4).Infof("Setting end time backwards to first present data")
  1094. // Apply offsets to both end and start times to maintain correct time range
  1095. deltaDuration := endTime.Sub(thanosOffset)
  1096. *startTime = startTime.Add(-1 * deltaDuration)
  1097. *endTime = time.Now().Add(-thanos.OffsetDuration())
  1098. }
  1099. // determine resolution by size of duration
  1100. resolutionHours := durationHours
  1101. if durationHours >= 2160 {
  1102. // 90 days
  1103. resolutionHours = 72.0
  1104. } else if durationHours >= 720 {
  1105. // 30 days
  1106. resolutionHours = 24.0
  1107. } else if durationHours >= 168 {
  1108. // 7 days
  1109. resolutionHours = 24.0
  1110. } else if durationHours >= 48 {
  1111. // 2 days
  1112. resolutionHours = 2.0
  1113. } else if durationHours >= 1 {
  1114. resolutionHours = 1.0
  1115. }
  1116. key := fmt.Sprintf(`%s:%s:%fh:%t`, duration, offset, resolutionHours, remoteEnabled)
  1117. // report message about which of the two caches hit. by default report a miss
  1118. cacheMessage := fmt.Sprintf("L1 cache miss: %s L2 cache miss: %s", aggKey, key)
  1119. // check the cache for aggregated response; if cache is hit and not disabled, return response
  1120. if value, found := a.AggregateCache.Get(aggKey); found && !disableCache && !noCache {
  1121. result, ok := value.(map[string]*Aggregation)
  1122. if !ok {
  1123. // disable cache and recompute if type cast fails
  1124. klog.Errorf("caching error: failed to cast aggregate data to struct: %s", aggKey)
  1125. return a.ComputeAggregateCostModel(promClient, duration, offset, field, subfields, rate, filters,
  1126. sri, shared, allocateIdle, includeTimeSeries, includeEfficiency, true, false, noExpireCache, noCache, remoteEnabled, disableSharedOverhead)
  1127. }
  1128. return result, fmt.Sprintf("aggregate cache hit: %s", aggKey), nil
  1129. }
  1130. profileStart := time.Now()
  1131. profileName := profileBaseName + ": "
  1132. window := duration
  1133. if durationHours >= 1 {
  1134. window = fmt.Sprintf("%dh", int(resolutionHours))
  1135. // exclude the last window of the time frame to match Prometheus definitions of range, offset, and resolution
  1136. *startTime = startTime.Add(time.Duration(resolutionHours) * time.Hour)
  1137. } else {
  1138. // don't cache requests for durations of less than one hour
  1139. klog.Infof("key %s has durationhours %f", key, durationHours)
  1140. disableCache = true
  1141. }
  1142. profileBaseName = fmt.Sprintf("ComputeAggregateCostModel(duration=%s, offset=%s, field=%s, window=%s)", duration, offset, field, window)
  1143. // attempt to retrieve cost data from cache
  1144. var costData map[string]*CostData
  1145. cacheData, found := a.CostDataCache.Get(key)
  1146. if found && !disableCache && !noCache {
  1147. profileName += "get cost data from cache"
  1148. ok := false
  1149. costData, ok = cacheData.(map[string]*CostData)
  1150. cacheMessage = fmt.Sprintf("L1 cache miss: %s, L2 cost data cache hit: %s", aggKey, key)
  1151. if !ok {
  1152. klog.Errorf("caching error: failed to cast cost data to struct: %s", key)
  1153. }
  1154. } else {
  1155. klog.Infof("key %s missed cache. found %t, disableCache %t, noCache %t ", key, found, disableCache, noCache)
  1156. cv := a.CostDataCache.Items()
  1157. klog.V(3).Infof("Logging cache items...")
  1158. for k := range cv {
  1159. klog.V(3).Infof("Cache item: %s", k)
  1160. }
  1161. profileName += "compute cost data"
  1162. start := startTime.Format(RFC3339Milli)
  1163. end := endTime.Format(RFC3339Milli)
  1164. costData, err = a.Model.ComputeCostDataRange(promClient, a.KubeClientSet, a.CloudProvider, start, end, window, resolutionHours, "", "", remoteEnabled, offset)
  1165. if err != nil {
  1166. if pce, ok := err.(prom.CommError); ok {
  1167. return nil, "", pce
  1168. }
  1169. if strings.Contains(err.Error(), "data is empty") {
  1170. return nil, "", &EmptyDataError{err: err, duration: duration, offset: offset}
  1171. }
  1172. return nil, "", err
  1173. }
  1174. // compute length of the time series in the cost data and only compute
  1175. // aggregates and cache if the length is sufficiently high
  1176. costDataLen := costDataTimeSeriesLength(costData)
  1177. if durationHours < 1.0 {
  1178. // scale hourly cost data down to fractional hour
  1179. costData = ScaleHourlyCostData(costData, resolutionHours)
  1180. }
  1181. if costDataLen == 0 {
  1182. return nil, "", &EmptyDataError{duration: duration, offset: offset}
  1183. }
  1184. if costDataLen >= minCostDataLength && !noCache {
  1185. klog.Infof("Setting L2 cache: %s", key)
  1186. a.CostDataCache.Set(key, costData, cacheExpiry)
  1187. }
  1188. }
  1189. measureTime(profileStart, profileThreshold, profileName)
  1190. c, err := a.CloudProvider.GetConfig()
  1191. if err != nil {
  1192. return nil, "", err
  1193. }
  1194. discount, err := ParsePercentString(c.Discount)
  1195. if err != nil {
  1196. return nil, "", err
  1197. }
  1198. customDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1199. if err != nil {
  1200. return nil, "", err
  1201. }
  1202. sc := make(map[string]*SharedCostInfo)
  1203. if !disableSharedOverhead {
  1204. for key, val := range c.SharedCosts {
  1205. cost, err := strconv.ParseFloat(val, 64)
  1206. durationCoefficient := durationHours / util.HoursPerMonth
  1207. if err != nil {
  1208. return nil, "", fmt.Errorf("Unable to parse shared cost %s: %s", val, err.Error())
  1209. }
  1210. sc[key] = &SharedCostInfo{
  1211. Name: key,
  1212. Cost: cost * durationCoefficient,
  1213. }
  1214. }
  1215. }
  1216. profileStart = time.Now()
  1217. profileName = profileBaseName + ": compute idle coefficient"
  1218. idleCoefficients := make(map[string]float64)
  1219. if allocateIdle {
  1220. idleDurationCalcHours := durationHours
  1221. if durationHours < 1 {
  1222. idleDurationCalcHours = 1
  1223. }
  1224. windowStr := fmt.Sprintf("%dh", int(idleDurationCalcHours))
  1225. if a.ThanosClient != nil {
  1226. offset = thanos.Offset()
  1227. klog.Infof("Setting offset to %s", offset)
  1228. }
  1229. idleCoefficients, err = a.ComputeIdleCoefficient(costData, promClient, a.CloudProvider, discount, customDiscount, windowStr, offset)
  1230. if err != nil {
  1231. klog.Errorf("error computing idle coefficient: windowString=%s, offset=%s, err=%s", windowStr, offset, err)
  1232. return nil, "", err
  1233. }
  1234. }
  1235. for cid, idleCoefficient := range idleCoefficients {
  1236. klog.Infof("Idle Coeff: %s: %f", cid, idleCoefficient)
  1237. }
  1238. totalContainerCost := 0.0
  1239. if shared == SplitTypeWeighted {
  1240. totalContainerCost = GetTotalContainerCost(costData, rate, a.CloudProvider, discount, customDiscount, idleCoefficients)
  1241. }
  1242. measureTime(profileStart, profileThreshold, profileName)
  1243. profileStart = time.Now()
  1244. profileName = profileBaseName + ": filter cost data"
  1245. // filter cost data by namespace and cluster after caching for maximal cache hits
  1246. costData, filteredContainerCount, filteredEnvironments := FilterCostData(costData, retainFuncs, filterFuncs)
  1247. measureTime(profileStart, profileThreshold, profileName)
  1248. profileStart = time.Now()
  1249. profileName = profileBaseName + ": aggregate cost data"
  1250. // aggregate cost model data by given fields and cache the result for the default expiration
  1251. opts := &AggregationOptions{
  1252. Discount: discount,
  1253. CustomDiscount: customDiscount,
  1254. IdleCoefficients: idleCoefficients,
  1255. IncludeEfficiency: includeEfficiency,
  1256. IncludeTimeSeries: includeTimeSeries,
  1257. Rate: rate,
  1258. ResolutionHours: resolutionHours,
  1259. SharedResourceInfo: sri,
  1260. SharedCosts: sc,
  1261. FilteredContainerCount: filteredContainerCount,
  1262. FilteredEnvironments: filteredEnvironments,
  1263. TotalContainerCost: totalContainerCost,
  1264. SharedSplit: shared,
  1265. }
  1266. result := AggregateCostData(costData, field, subfields, a.CloudProvider, opts)
  1267. // If sending time series data back, switch scale back to hourly data. At this point,
  1268. // resolutionHours may have converted our hourly data to more- or less-than hourly data.
  1269. if includeTimeSeries {
  1270. for _, aggs := range result {
  1271. ScaleAggregationTimeSeries(aggs, resolutionHours)
  1272. }
  1273. }
  1274. // compute length of the time series in the cost data and only cache
  1275. // aggregation results if the length is sufficiently high
  1276. costDataLen := costDataTimeSeriesLength(costData)
  1277. if costDataLen >= minCostDataLength && durationHours > 1 && !noCache {
  1278. // Set the result map (rather than a pointer to it) because map is a reference type
  1279. klog.Infof("Caching key in aggregate cache: %s", key)
  1280. a.AggregateCache.Set(aggKey, result, cacheExpiry)
  1281. } else {
  1282. klog.Infof("Not caching for key %s. Not enough data: %t, Duration less than 1h: %t, noCache: %t", key, costDataLen < minCostDataLength, durationHours < 1, noCache)
  1283. }
  1284. measureTime(profileStart, profileThreshold, profileName)
  1285. return result, cacheMessage, nil
  1286. }
  1287. // ScaleAggregationTimeSeries reverses the scaling done by ScaleHourlyCostData, returning
  1288. // the aggregation's time series to hourly data.
  1289. func ScaleAggregationTimeSeries(aggregation *Aggregation, resolutionHours float64) {
  1290. for _, v := range aggregation.CPUCostVector {
  1291. v.Value /= resolutionHours
  1292. }
  1293. for _, v := range aggregation.GPUCostVector {
  1294. v.Value /= resolutionHours
  1295. }
  1296. for _, v := range aggregation.RAMCostVector {
  1297. v.Value /= resolutionHours
  1298. }
  1299. for _, v := range aggregation.PVCostVector {
  1300. v.Value /= resolutionHours
  1301. }
  1302. for _, v := range aggregation.NetworkCostVector {
  1303. v.Value /= resolutionHours
  1304. }
  1305. for _, v := range aggregation.TotalCostVector {
  1306. v.Value /= resolutionHours
  1307. }
  1308. return
  1309. }
  1310. // String returns a string representation of the encapsulated shared resources, which
  1311. // can be used to uniquely identify a set of shared resources. Sorting sets of shared
  1312. // resources ensures that strings representing permutations of the same combination match.
  1313. func (s *SharedResourceInfo) String() string {
  1314. if s == nil {
  1315. return ""
  1316. }
  1317. nss := []string{}
  1318. for ns := range s.SharedNamespace {
  1319. nss = append(nss, ns)
  1320. }
  1321. sort.Strings(nss)
  1322. nsStr := strings.Join(nss, ",")
  1323. labels := []string{}
  1324. for lbl, vals := range s.LabelSelectors {
  1325. for val := range vals {
  1326. if lbl != "" && val != "" {
  1327. labels = append(labels, fmt.Sprintf("%s=%s", lbl, val))
  1328. }
  1329. }
  1330. }
  1331. sort.Strings(labels)
  1332. labelStr := strings.Join(labels, ",")
  1333. return fmt.Sprintf("%s:%s", nsStr, labelStr)
  1334. }
  1335. type aggKeyParams struct {
  1336. duration string
  1337. offset string
  1338. filters map[string]string
  1339. field string
  1340. subfields []string
  1341. rate string
  1342. sri *SharedResourceInfo
  1343. shareType string
  1344. idle bool
  1345. timeSeries bool
  1346. efficiency bool
  1347. }
  1348. // GenerateAggKey generates a parameter-unique key for caching the aggregate cost model
  1349. func GenerateAggKey(ps aggKeyParams) string {
  1350. // parse, trim, and sort podprefix filters
  1351. podPrefixFilters := []string{}
  1352. if ppfs, ok := ps.filters["podprefix"]; ok && ppfs != "" {
  1353. for _, psf := range strings.Split(ppfs, ",") {
  1354. podPrefixFilters = append(podPrefixFilters, strings.TrimSpace(psf))
  1355. }
  1356. }
  1357. sort.Strings(podPrefixFilters)
  1358. podPrefixFiltersStr := strings.Join(podPrefixFilters, ",")
  1359. // parse, trim, and sort namespace filters
  1360. nsFilters := []string{}
  1361. if nsfs, ok := ps.filters["namespace"]; ok && nsfs != "" {
  1362. for _, nsf := range strings.Split(nsfs, ",") {
  1363. nsFilters = append(nsFilters, strings.TrimSpace(nsf))
  1364. }
  1365. }
  1366. sort.Strings(nsFilters)
  1367. nsFilterStr := strings.Join(nsFilters, ",")
  1368. // parse, trim, and sort node filters
  1369. nodeFilters := []string{}
  1370. if nodefs, ok := ps.filters["node"]; ok && nodefs != "" {
  1371. for _, nodef := range strings.Split(nodefs, ",") {
  1372. nodeFilters = append(nodeFilters, strings.TrimSpace(nodef))
  1373. }
  1374. }
  1375. sort.Strings(nodeFilters)
  1376. nodeFilterStr := strings.Join(nodeFilters, ",")
  1377. // parse, trim, and sort cluster filters
  1378. cFilters := []string{}
  1379. if cfs, ok := ps.filters["cluster"]; ok && cfs != "" {
  1380. for _, cf := range strings.Split(cfs, ",") {
  1381. cFilters = append(cFilters, strings.TrimSpace(cf))
  1382. }
  1383. }
  1384. sort.Strings(cFilters)
  1385. cFilterStr := strings.Join(cFilters, ",")
  1386. // parse, trim, and sort label filters
  1387. lFilters := []string{}
  1388. if lfs, ok := ps.filters["labels"]; ok && lfs != "" {
  1389. for _, lf := range strings.Split(lfs, ",") {
  1390. // trim whitespace from the label name and the label value
  1391. // of each label name/value pair, then reconstruct
  1392. // e.g. "tier = frontend, app = kubecost" == "app=kubecost,tier=frontend"
  1393. lfa := strings.Split(lf, "=")
  1394. if len(lfa) == 2 {
  1395. lfn := strings.TrimSpace(lfa[0])
  1396. lfv := strings.TrimSpace(lfa[1])
  1397. lFilters = append(lFilters, fmt.Sprintf("%s=%s", lfn, lfv))
  1398. } else {
  1399. // label is not of the form name=value, so log it and move on
  1400. klog.V(2).Infof("[Warning] GenerateAggKey: skipping illegal label filter: %s", lf)
  1401. }
  1402. }
  1403. }
  1404. sort.Strings(lFilters)
  1405. lFilterStr := strings.Join(lFilters, ",")
  1406. filterStr := fmt.Sprintf("%s:%s:%s:%s:%s", nsFilterStr, nodeFilterStr, cFilterStr, lFilterStr, podPrefixFiltersStr)
  1407. sort.Strings(ps.subfields)
  1408. fieldStr := fmt.Sprintf("%s:%s", ps.field, strings.Join(ps.subfields, ","))
  1409. return fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s:%t:%t:%t", ps.duration, ps.offset, filterStr, fieldStr, ps.rate,
  1410. ps.sri, ps.shareType, ps.idle, ps.timeSeries, ps.efficiency)
  1411. }
  1412. // AggregateCostModelHandler handles requests to the aggregated cost model API. See
  1413. // ComputeAggregateCostModel for details.
  1414. func (a *Accesses) AggregateCostModelHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1415. w.Header().Set("Content-Type", "application/json")
  1416. windowStr := r.URL.Query().Get("window")
  1417. // Convert UTC-RFC3339 pairs to configured UTC offset
  1418. // e.g. with UTC offset of -0600, 2020-07-01T00:00:00Z becomes
  1419. // 2020-07-01T06:00:00Z == 2020-07-01T00:00:00-0600
  1420. // TODO niko/etl fix the frontend because this is confusing if you're
  1421. // actually asking for UTC time (...Z) and we swap that "Z" out for the
  1422. // configured UTC offset without asking
  1423. rfc3339 := `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  1424. regex := regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  1425. match := regex.FindStringSubmatch(windowStr)
  1426. if match != nil {
  1427. start, _ := time.Parse(time.RFC3339, match[1])
  1428. start = start.Add(-env.GetParsedUTCOffset()).In(time.UTC)
  1429. end, _ := time.Parse(time.RFC3339, match[2])
  1430. end = end.Add(-env.GetParsedUTCOffset()).In(time.UTC)
  1431. windowStr = fmt.Sprintf("%sZ,%sZ", start.Format("2006-01-02T15:04:05"), end.Format("2006-01-02T15:04:05Z"))
  1432. }
  1433. // determine duration and offset from query parameters
  1434. window, err := kubecost.ParseWindowWithOffset(windowStr, env.GetParsedUTCOffset())
  1435. if err != nil || window.Start() == nil {
  1436. WriteError(w, BadRequest(fmt.Sprintf("invalid window: %s", err)))
  1437. return
  1438. }
  1439. duration, offset := window.ToDurationOffset()
  1440. durRegex := regexp.MustCompile(`^(\d+)(m|h|d|s)$`)
  1441. isDurationStr := durRegex.MatchString(windowStr)
  1442. // legacy offset option should override window offset
  1443. if r.URL.Query().Get("offset") != "" {
  1444. offset = r.URL.Query().Get("offset")
  1445. // Shift window by offset, but only when manually set with separate
  1446. // parameter and window was provided as a duration string. Otherwise,
  1447. // do not alter the (duration, offset) from ParseWindowWithOffset.
  1448. if offset != "1m" && isDurationStr {
  1449. match := durRegex.FindStringSubmatch(offset)
  1450. if match != nil && len(match) == 3 {
  1451. dur := time.Minute
  1452. if match[2] == "h" {
  1453. dur = time.Hour
  1454. }
  1455. if match[2] == "d" {
  1456. dur = 24 * time.Hour
  1457. }
  1458. if match[2] == "s" {
  1459. dur = time.Second
  1460. }
  1461. num, _ := strconv.ParseInt(match[1], 10, 64)
  1462. window = window.Shift(-time.Duration(num) * dur)
  1463. }
  1464. }
  1465. }
  1466. // redirect requests with no offset to a 1m offset to improve cache hits
  1467. if offset == "" {
  1468. offset = "1m"
  1469. }
  1470. // parse remaining query parameters
  1471. namespace := r.URL.Query().Get("namespace")
  1472. cluster := r.URL.Query().Get("cluster")
  1473. labels := r.URL.Query().Get("labels")
  1474. podprefix := r.URL.Query().Get("podprefix")
  1475. labelArray := strings.Split(labels, "=")
  1476. labelArray[0] = strings.ReplaceAll(labelArray[0], "-", "_")
  1477. labels = strings.Join(labelArray, "=")
  1478. field := r.URL.Query().Get("aggregation")
  1479. subfieldStr := r.URL.Query().Get("aggregationSubfield")
  1480. rate := r.URL.Query().Get("rate")
  1481. idleFlag := r.URL.Query().Get("allocateIdle")
  1482. sharedNamespaces := r.URL.Query().Get("sharedNamespaces")
  1483. sharedLabelNames := r.URL.Query().Get("sharedLabelNames")
  1484. sharedLabelValues := r.URL.Query().Get("sharedLabelValues")
  1485. remote := r.URL.Query().Get("remote") != "false"
  1486. shared := r.URL.Query().Get("sharedSplit")
  1487. subfields := []string{}
  1488. if len(subfieldStr) > 0 {
  1489. s := strings.Split(r.URL.Query().Get("aggregationSubfield"), ",")
  1490. for _, rawLabel := range s {
  1491. subfields = append(subfields, SanitizeLabelName(rawLabel))
  1492. }
  1493. }
  1494. var allocateIdle bool
  1495. if idleFlag == "default" {
  1496. c, _ := a.CloudProvider.GetConfig()
  1497. allocateIdle = (c.DefaultIdle == "true")
  1498. } else {
  1499. allocateIdle = (idleFlag == "true")
  1500. }
  1501. // timeSeries == true maintains the time series dimension of the data,
  1502. // which by default gets summed over the entire interval
  1503. includeTimeSeries := r.URL.Query().Get("timeSeries") == "true"
  1504. // efficiency == true aggregates and returns usage and efficiency data
  1505. // includeEfficiency := r.URL.Query().Get("efficiency") == "true"
  1506. // efficiency has been deprecated in favor of a default to always send efficiency
  1507. includeEfficiency := true
  1508. // TODO niko/caching rename "recomputeCache"
  1509. // disableCache, if set to "true", tells this function to recompute and
  1510. // cache the requested data
  1511. disableCache := r.URL.Query().Get("disableCache") == "true"
  1512. // clearCache, if set to "true", tells this function to flush the cache,
  1513. // then recompute and cache the requested data
  1514. clearCache := r.URL.Query().Get("clearCache") == "true"
  1515. // noCache avoids the cache altogether, both reading from and writing to
  1516. noCache := r.URL.Query().Get("noCache") == "true"
  1517. // noExpireCache should only be used by cache warming to set non-expiring caches
  1518. noExpireCache := false
  1519. // aggregation field is required
  1520. if field == "" {
  1521. WriteError(w, BadRequest("Missing aggregation field parameter"))
  1522. return
  1523. }
  1524. // aggregation subfield is required when aggregation field is "label"
  1525. if field == "label" && len(subfields) == 0 {
  1526. WriteError(w, BadRequest("Missing aggregation subfield parameter for aggregation by label"))
  1527. return
  1528. }
  1529. // enforce one of four available rate options
  1530. if rate != "" && rate != "hourly" && rate != "daily" && rate != "monthly" {
  1531. WriteError(w, BadRequest("If set, rate parameter must be one of: 'hourly', 'daily', 'monthly'"))
  1532. return
  1533. }
  1534. // parse cost data filters
  1535. // namespace and cluster are exact-string-matches
  1536. // labels are expected to be comma-separated and to take the form key=value
  1537. // e.g. app=cost-analyzer,app.kubernetes.io/instance=kubecost
  1538. filters := map[string]string{
  1539. "namespace": namespace,
  1540. "cluster": cluster,
  1541. "labels": labels,
  1542. "podprefix": podprefix,
  1543. }
  1544. // parse shared resources
  1545. sn := []string{}
  1546. sln := []string{}
  1547. slv := []string{}
  1548. if sharedNamespaces != "" {
  1549. sn = strings.Split(sharedNamespaces, ",")
  1550. }
  1551. if sharedLabelNames != "" {
  1552. sln = strings.Split(sharedLabelNames, ",")
  1553. slv = strings.Split(sharedLabelValues, ",")
  1554. if len(sln) != len(slv) || slv[0] == "" {
  1555. WriteError(w, BadRequest("Supply exacly one shared label value per shared label name"))
  1556. return
  1557. }
  1558. }
  1559. var sr *SharedResourceInfo
  1560. if len(sn) > 0 || len(sln) > 0 {
  1561. sr = NewSharedResourceInfo(true, sn, sln, slv)
  1562. }
  1563. // enable remote if it is available and not disabled
  1564. remoteEnabled := remote && env.IsRemoteEnabled()
  1565. // if custom pricing has changed, then clear the cache and recompute data
  1566. if a.CustomPricingHasChanged() {
  1567. clearCache = true
  1568. }
  1569. promClient := a.GetPrometheusClient(remote)
  1570. var data map[string]*Aggregation
  1571. var message string
  1572. etlEnabled := env.IsETLEnabled()
  1573. useETLAdapter := r.URL.Query().Get("etl") == "true"
  1574. if etlEnabled && useETLAdapter {
  1575. data, message, err = a.AdaptETLAggregateCostModel(window, field, subfields, rate, filters, sr, shared, allocateIdle, includeTimeSeries)
  1576. } else {
  1577. data, message, err = a.ComputeAggregateCostModel(promClient, duration, offset, field, subfields, rate, filters,
  1578. sr, shared, allocateIdle, includeTimeSeries, includeEfficiency, disableCache, clearCache, noCache, noExpireCache, remoteEnabled, false)
  1579. }
  1580. // Find any warnings in http request context
  1581. warning, _ := product.GetWarning(r)
  1582. if err != nil {
  1583. if emptyErr, ok := err.(*EmptyDataError); ok {
  1584. if warning == "" {
  1585. WriteDataWithMessage(w, map[string]interface{}{}, emptyErr.Error())
  1586. } else {
  1587. WriteDataWithMessageAndWarning(w, map[string]interface{}{}, emptyErr.Error(), warning)
  1588. }
  1589. return
  1590. }
  1591. if boundaryErr, ok := err.(*kubecost.BoundaryError); ok {
  1592. if window.Start() != nil && window.Start().After(time.Now().Add(-90*24*time.Hour)) {
  1593. // Asking for data within a 90 day period: it will be available
  1594. // after the pipeline builds
  1595. msg := "Data will be available after ETL is built"
  1596. rex := regexp.MustCompile(`(\d+\.*\d*)%`)
  1597. match := rex.FindStringSubmatch(boundaryErr.Message)
  1598. if len(match) > 1 {
  1599. completionPct, err := strconv.ParseFloat(match[1], 64)
  1600. if err == nil {
  1601. msg = fmt.Sprintf("%s (%.1f%% complete)", msg, completionPct)
  1602. }
  1603. }
  1604. WriteError(w, InternalServerError(msg))
  1605. } else {
  1606. // Boundary error outside of 90 day period; may not be available
  1607. WriteError(w, InternalServerError(boundaryErr.Error()))
  1608. }
  1609. return
  1610. }
  1611. errStr := fmt.Sprintf("error computing aggregate cost model: %s", err)
  1612. WriteError(w, InternalServerError(errStr))
  1613. return
  1614. }
  1615. if warning == "" {
  1616. WriteDataWithMessage(w, data, message)
  1617. } else {
  1618. WriteDataWithMessageAndWarning(w, data, message, warning)
  1619. }
  1620. }