aggregation.go 74 KB

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