aggregation.go 68 KB

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