aggregation.go 73 KB

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