aggregation.go 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  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. duration string
  791. offset string
  792. }
  793. // Error implements the error interface
  794. func (ede *EmptyDataError) Error() string {
  795. err := fmt.Sprintf("empty data for range: %s", ede.duration)
  796. if ede.offset != "" {
  797. err += fmt.Sprintf(" offset %s", ede.offset)
  798. }
  799. if ede.err != nil {
  800. err += fmt.Sprintf(": %s", ede.err)
  801. }
  802. return err
  803. }
  804. func costDataTimeSeriesLength(costData map[string]*CostData) int {
  805. l := 0
  806. for _, cd := range costData {
  807. if l < len(cd.RAMAllocation) {
  808. l = len(cd.RAMAllocation)
  809. }
  810. if l < len(cd.CPUAllocation) {
  811. l = len(cd.CPUAllocation)
  812. }
  813. }
  814. return l
  815. }
  816. // ScaleHourlyCostData converts per-hour cost data to per-resolution data. If the target resolution is higher (i.e. < 1.0h)
  817. // then we can do simple multiplication by the fraction-of-an-hour and retain accuracy. If the target resolution is
  818. // lower (i.e. > 1.0h) then we sum groups of hourly data by resolution to maintain fidelity.
  819. // e.g. (100 hours of per-hour hourly data, resolutionHours=10) => 10 data points, grouped and summed by 10-hour window
  820. // e.g. (20 minutes of per-minute hourly data, resolutionHours=1/60) => 20 data points, scaled down by a factor of 60
  821. func ScaleHourlyCostData(data map[string]*CostData, resolutionHours float64) map[string]*CostData {
  822. scaled := map[string]*CostData{}
  823. for key, datum := range data {
  824. datum.RAMReq = scaleVectorSeries(datum.RAMReq, resolutionHours)
  825. datum.RAMUsed = scaleVectorSeries(datum.RAMUsed, resolutionHours)
  826. datum.RAMAllocation = scaleVectorSeries(datum.RAMAllocation, resolutionHours)
  827. datum.CPUReq = scaleVectorSeries(datum.CPUReq, resolutionHours)
  828. datum.CPUUsed = scaleVectorSeries(datum.CPUUsed, resolutionHours)
  829. datum.CPUAllocation = scaleVectorSeries(datum.CPUAllocation, resolutionHours)
  830. datum.GPUReq = scaleVectorSeries(datum.GPUReq, resolutionHours)
  831. datum.NetworkData = scaleVectorSeries(datum.NetworkData, resolutionHours)
  832. for _, pvcDatum := range datum.PVCData {
  833. pvcDatum.Values = scaleVectorSeries(pvcDatum.Values, resolutionHours)
  834. }
  835. scaled[key] = datum
  836. }
  837. return scaled
  838. }
  839. func scaleVectorSeries(vs []*util.Vector, resolutionHours float64) []*util.Vector {
  840. // if scaling to a lower resolution, compress the hourly data for maximum accuracy
  841. if resolutionHours > 1.0 {
  842. return compressVectorSeries(vs, resolutionHours)
  843. }
  844. // if scaling to a higher resolution, simply scale each value down by the fraction of an hour
  845. for _, v := range vs {
  846. v.Value *= resolutionHours
  847. }
  848. return vs
  849. }
  850. func compressVectorSeries(vs []*util.Vector, resolutionHours float64) []*util.Vector {
  851. if len(vs) == 0 {
  852. return vs
  853. }
  854. compressed := []*util.Vector{}
  855. threshold := float64(60 * 60 * resolutionHours)
  856. var acc *util.Vector
  857. for i, v := range vs {
  858. if acc == nil {
  859. // start a new accumulation from current datum
  860. acc = &util.Vector{
  861. Value: vs[i].Value,
  862. Timestamp: vs[i].Timestamp,
  863. }
  864. continue
  865. }
  866. if v.Timestamp-acc.Timestamp < threshold {
  867. // v should be accumulated in current datum
  868. acc.Value += v.Value
  869. } else {
  870. // v falls outside current datum's threshold; append and start a new one
  871. compressed = append(compressed, acc)
  872. acc = &util.Vector{
  873. Value: vs[i].Value,
  874. Timestamp: vs[i].Timestamp,
  875. }
  876. }
  877. }
  878. // append any remaining, incomplete accumulation
  879. if acc != nil {
  880. compressed = append(compressed, acc)
  881. }
  882. return compressed
  883. }
  884. // ComputeAggregateCostModel computes cost data for the given window, then aggregates it by the given fields.
  885. // Data is cached on two levels: the aggregation is cached as well as the underlying cost data.
  886. func (a *Accesses) ComputeAggregateCostModel(promClient prometheusClient.Client, duration, offset, field string, subfields []string, rate string, filters map[string]string, sri *SharedResourceInfo, shared string, allocateIdle, includeTimeSeries, includeEfficiency, disableCache, clearCache, noCache, noExpireCache, remoteEnabled, disableSharedOverhead, useETLAdapter bool) (map[string]*Aggregation, string, error) {
  887. profileBaseName := fmt.Sprintf("ComputeAggregateCostModel(duration=%s, offet=%s, field=%s)", duration, offset, field)
  888. defer measureTime(time.Now(), profileThreshold, profileBaseName)
  889. // parse cost data filters into FilterFuncs
  890. filterFuncs := []FilterFunc{}
  891. retainFuncs := []FilterFunc{}
  892. retainFuncs = append(retainFuncs, func(cd *CostData) (bool, string) {
  893. if sri != nil {
  894. return sri.IsSharedResource(cd), ""
  895. }
  896. return false, ""
  897. })
  898. aggregateEnvironment := func(costDatum *CostData) string {
  899. if field == "cluster" {
  900. return costDatum.ClusterID
  901. } else if field == "node" {
  902. return costDatum.NodeName
  903. } else if field == "namespace" {
  904. return costDatum.Namespace
  905. } else if field == "service" {
  906. if len(costDatum.Services) > 0 {
  907. return costDatum.Namespace + "/" + costDatum.Services[0]
  908. }
  909. } else if field == "deployment" {
  910. if len(costDatum.Deployments) > 0 {
  911. return costDatum.Namespace + "/" + costDatum.Deployments[0]
  912. }
  913. } else if field == "daemonset" {
  914. if len(costDatum.Daemonsets) > 0 {
  915. return costDatum.Namespace + "/" + costDatum.Daemonsets[0]
  916. }
  917. } else if field == "statefulset" {
  918. if len(costDatum.Statefulsets) > 0 {
  919. return costDatum.Namespace + "/" + costDatum.Statefulsets[0]
  920. }
  921. } else if field == "label" {
  922. if costDatum.Labels != nil {
  923. for _, sf := range subfields {
  924. if subfieldName, ok := costDatum.Labels[sf]; ok {
  925. return fmt.Sprintf("%s=%s", sf, subfieldName)
  926. }
  927. }
  928. }
  929. } else if field == "pod" {
  930. return costDatum.Namespace + "/" + costDatum.PodName
  931. } else if field == "container" {
  932. return costDatum.Namespace + "/" + costDatum.PodName + "/" + costDatum.Name
  933. }
  934. return ""
  935. }
  936. if filters["podprefix"] != "" {
  937. pps := []string{}
  938. for _, fp := range strings.Split(filters["podprefix"], ",") {
  939. if fp != "" {
  940. cleanedFilter := strings.TrimSpace(fp)
  941. pps = append(pps, cleanedFilter)
  942. }
  943. }
  944. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  945. aggEnv := aggregateEnvironment(cd)
  946. for _, pp := range pps {
  947. cleanedFilter := strings.TrimSpace(pp)
  948. if strings.HasPrefix(cd.PodName, cleanedFilter) {
  949. return true, aggEnv
  950. }
  951. }
  952. return false, aggEnv
  953. })
  954. }
  955. if filters["namespace"] != "" {
  956. // namespaces may be comma-separated, e.g. kubecost,default
  957. // multiple namespaces are evaluated as an OR relationship
  958. nss := strings.Split(filters["namespace"], ",")
  959. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  960. aggEnv := aggregateEnvironment(cd)
  961. for _, ns := range nss {
  962. nsTrim := strings.TrimSpace(ns)
  963. if cd.Namespace == nsTrim {
  964. return true, aggEnv
  965. } else if strings.HasSuffix(nsTrim, "*") { // trigger wildcard prefix filtering
  966. nsTrimAsterisk := strings.TrimSuffix(nsTrim, "*")
  967. if strings.HasPrefix(cd.Namespace, nsTrimAsterisk) {
  968. return true, aggEnv
  969. }
  970. }
  971. }
  972. return false, aggEnv
  973. })
  974. }
  975. if filters["node"] != "" {
  976. // nodes may be comma-separated, e.g. aws-node-1,aws-node-2
  977. // multiple nodes are evaluated as an OR relationship
  978. nodes := strings.Split(filters["node"], ",")
  979. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  980. aggEnv := aggregateEnvironment(cd)
  981. for _, node := range nodes {
  982. nodeTrim := strings.TrimSpace(node)
  983. if cd.NodeName == nodeTrim {
  984. return true, aggEnv
  985. } else if strings.HasSuffix(nodeTrim, "*") { // trigger wildcard prefix filtering
  986. nodeTrimAsterisk := strings.TrimSuffix(nodeTrim, "*")
  987. if strings.HasPrefix(cd.NodeName, nodeTrimAsterisk) {
  988. return true, aggEnv
  989. }
  990. }
  991. }
  992. return false, aggEnv
  993. })
  994. }
  995. if filters["cluster"] != "" {
  996. // clusters may be comma-separated, e.g. cluster-one,cluster-two
  997. // multiple clusters are evaluated as an OR relationship
  998. cs := strings.Split(filters["cluster"], ",")
  999. filterFuncs = append(filterFuncs, func(cd *CostData) (bool, string) {
  1000. aggEnv := aggregateEnvironment(cd)
  1001. for _, c := range cs {
  1002. cTrim := strings.TrimSpace(c)
  1003. id, name := cd.ClusterID, cd.ClusterName
  1004. if id == cTrim || name == cTrim {
  1005. return true, aggEnv
  1006. } else if strings.HasSuffix(cTrim, "*") { // trigger wildcard prefix filtering
  1007. cTrimAsterisk := strings.TrimSuffix(cTrim, "*")
  1008. if strings.HasPrefix(id, cTrimAsterisk) || strings.HasPrefix(name, cTrimAsterisk) {
  1009. return true, aggEnv
  1010. }
  1011. }
  1012. }
  1013. return false, aggEnv
  1014. })
  1015. }
  1016. if filters["labels"] != "" {
  1017. // labels are expected to be comma-separated and to take the form key=value
  1018. // e.g. app=cost-analyzer,app.kubernetes.io/instance=kubecost
  1019. // each different label will be applied as an AND
  1020. // multiple values for a single label will be evaluated as an OR
  1021. labelValues := map[string][]string{}
  1022. ls := strings.Split(filters["labels"], ",")
  1023. for _, l := range ls {
  1024. lTrim := strings.TrimSpace(l)
  1025. label := strings.Split(lTrim, "=")
  1026. if len(label) == 2 {
  1027. ln := prom.SanitizeLabelName(strings.TrimSpace(label[0]))
  1028. lv := strings.TrimSpace(label[1])
  1029. labelValues[ln] = append(labelValues[ln], lv)
  1030. } else {
  1031. // label is not of the form name=value, so log it and move on
  1032. klog.V(2).Infof("[Warning] aggregate cost model: skipping illegal label filter: %s", l)
  1033. }
  1034. }
  1035. // Generate FilterFunc for each set of label filters by invoking a function instead of accessing
  1036. // values by closure to prevent reference-type looping bug.
  1037. // (see https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable)
  1038. for label, values := range labelValues {
  1039. ff := (func(l string, vs []string) FilterFunc {
  1040. return func(cd *CostData) (bool, string) {
  1041. ae := aggregateEnvironment(cd)
  1042. for _, v := range vs {
  1043. if v == "__unallocated__" { // Special case. __unallocated__ means return all pods without the attached label
  1044. if _, ok := cd.Labels[label]; !ok {
  1045. return true, ae
  1046. }
  1047. }
  1048. if cd.Labels[label] == v {
  1049. return true, ae
  1050. } else if strings.HasSuffix(v, "*") { // trigger wildcard prefix filtering
  1051. vTrim := strings.TrimSuffix(v, "*")
  1052. if strings.HasPrefix(cd.Labels[label], vTrim) {
  1053. return true, ae
  1054. }
  1055. }
  1056. }
  1057. return false, ae
  1058. }
  1059. })(label, values)
  1060. filterFuncs = append(filterFuncs, ff)
  1061. }
  1062. }
  1063. // clear cache prior to checking the cache so that a clearCache=true
  1064. // request always returns a freshly computed value
  1065. if clearCache {
  1066. a.AggregateCache.Flush()
  1067. a.CostDataCache.Flush()
  1068. }
  1069. cacheExpiry := a.GetCacheExpiration(duration)
  1070. if noExpireCache {
  1071. cacheExpiry = cache.NoExpiration
  1072. }
  1073. // parametrize cache key by all request parameters
  1074. aggKey := GenerateAggKey(aggKeyParams{
  1075. duration: duration,
  1076. offset: offset,
  1077. filters: filters,
  1078. field: field,
  1079. subfields: subfields,
  1080. rate: rate,
  1081. sri: sri,
  1082. shareType: shared,
  1083. idle: allocateIdle,
  1084. timeSeries: includeTimeSeries,
  1085. efficiency: includeEfficiency,
  1086. })
  1087. // convert duration and offset to start and end times
  1088. startTime, endTime, err := ParseTimeRange(duration, offset)
  1089. if err != nil {
  1090. return nil, "", fmt.Errorf("Error parsing duration (%s) and offset (%s): %s", duration, offset, err)
  1091. }
  1092. durationHours := endTime.Sub(*startTime).Hours()
  1093. thanosOffset := time.Now().Add(-thanos.OffsetDuration())
  1094. if a.ThanosClient != nil && endTime.After(thanosOffset) {
  1095. klog.V(4).Infof("Setting end time backwards to first present data")
  1096. // Apply offsets to both end and start times to maintain correct time range
  1097. deltaDuration := endTime.Sub(thanosOffset)
  1098. *startTime = startTime.Add(-1 * deltaDuration)
  1099. *endTime = time.Now().Add(-thanos.OffsetDuration())
  1100. }
  1101. // determine resolution by size of duration
  1102. resolutionHours := durationHours
  1103. if durationHours >= 2160 {
  1104. // 90 days
  1105. resolutionHours = 72.0
  1106. } else if durationHours >= 720 {
  1107. // 30 days
  1108. resolutionHours = 24.0
  1109. } else if durationHours >= 168 {
  1110. // 7 days
  1111. resolutionHours = 24.0
  1112. } else if durationHours >= 48 {
  1113. // 2 days
  1114. resolutionHours = 2.0
  1115. } else if durationHours >= 1 {
  1116. resolutionHours = 1.0
  1117. }
  1118. key := fmt.Sprintf(`%s:%s:%fh:%t`, duration, offset, resolutionHours, remoteEnabled)
  1119. // report message about which of the two caches hit. by default report a miss
  1120. cacheMessage := fmt.Sprintf("L1 cache miss: %s L2 cache miss: %s", aggKey, key)
  1121. // check the cache for aggregated response; if cache is hit and not disabled, return response
  1122. if value, found := a.AggregateCache.Get(aggKey); found && !disableCache && !noCache {
  1123. result, ok := value.(map[string]*Aggregation)
  1124. if !ok {
  1125. // disable cache and recompute if type cast fails
  1126. klog.Errorf("caching error: failed to cast aggregate data to struct: %s", aggKey)
  1127. return a.ComputeAggregateCostModel(promClient, duration, offset, field, subfields, rate, filters, sri, shared, allocateIdle, includeTimeSeries, includeEfficiency, true, false, noExpireCache, noCache, remoteEnabled, disableSharedOverhead, useETLAdapter)
  1128. }
  1129. return result, fmt.Sprintf("aggregate cache hit: %s", aggKey), nil
  1130. }
  1131. profileStart := time.Now()
  1132. profileName := profileBaseName + ": "
  1133. window := duration
  1134. if durationHours >= 1 {
  1135. window = fmt.Sprintf("%dh", int(resolutionHours))
  1136. // exclude the last window of the time frame to match Prometheus definitions of range, offset, and resolution
  1137. *startTime = startTime.Add(time.Duration(resolutionHours) * time.Hour)
  1138. } else {
  1139. // don't cache requests for durations of less than one hour
  1140. klog.Infof("key %s has durationhours %f", key, durationHours)
  1141. disableCache = true
  1142. }
  1143. profileBaseName = fmt.Sprintf("ComputeAggregateCostModel(duration=%s, offset=%s, field=%s, window=%s)", duration, offset, field, window)
  1144. // attempt to retrieve cost data from cache
  1145. var costData map[string]*CostData
  1146. cacheData, found := a.CostDataCache.Get(key)
  1147. if found && !disableCache && !noCache {
  1148. profileName += "get cost data from cache"
  1149. ok := false
  1150. costData, ok = cacheData.(map[string]*CostData)
  1151. cacheMessage = fmt.Sprintf("L1 cache miss: %s, L2 cost data cache hit: %s", aggKey, key)
  1152. if !ok {
  1153. klog.Errorf("caching error: failed to cast cost data to struct: %s", key)
  1154. }
  1155. } else {
  1156. klog.Infof("key %s missed cache. found %t, disableCache %t, noCache %t ", key, found, disableCache, noCache)
  1157. cv := a.CostDataCache.Items()
  1158. klog.V(3).Infof("Logging cache items...")
  1159. for k := range cv {
  1160. klog.V(3).Infof("Cache item: %s", k)
  1161. }
  1162. profileName += "compute cost data"
  1163. start := startTime.Format(RFC3339Milli)
  1164. end := endTime.Format(RFC3339Milli)
  1165. costData, err = a.Model.ComputeCostDataRange(promClient, a.CloudProvider, start, end, window, resolutionHours, "", "", remoteEnabled, offset)
  1166. if err != nil {
  1167. if prom.IsErrorCollection(err) {
  1168. return nil, "", err
  1169. }
  1170. if pce, ok := err.(prom.CommError); ok {
  1171. return nil, "", pce
  1172. }
  1173. if strings.Contains(err.Error(), "data is empty") {
  1174. return nil, "", &EmptyDataError{err: err, duration: duration, offset: offset}
  1175. }
  1176. return nil, "", err
  1177. }
  1178. // compute length of the time series in the cost data and only compute
  1179. // aggregates and cache if the length is sufficiently high
  1180. costDataLen := costDataTimeSeriesLength(costData)
  1181. if durationHours < 1.0 {
  1182. // scale hourly cost data down to fractional hour
  1183. costData = ScaleHourlyCostData(costData, resolutionHours)
  1184. }
  1185. if costDataLen == 0 {
  1186. return nil, "", &EmptyDataError{duration: duration, offset: offset}
  1187. }
  1188. if costDataLen >= minCostDataLength && !noCache {
  1189. klog.Infof("Setting L2 cache: %s", key)
  1190. a.CostDataCache.Set(key, costData, cacheExpiry)
  1191. }
  1192. }
  1193. measureTime(profileStart, profileThreshold, profileName)
  1194. c, err := a.CloudProvider.GetConfig()
  1195. if err != nil {
  1196. return nil, "", err
  1197. }
  1198. discount, err := ParsePercentString(c.Discount)
  1199. if err != nil {
  1200. return nil, "", err
  1201. }
  1202. customDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1203. if err != nil {
  1204. return nil, "", err
  1205. }
  1206. sc := make(map[string]*SharedCostInfo)
  1207. if !disableSharedOverhead {
  1208. for key, val := range c.SharedCosts {
  1209. cost, err := strconv.ParseFloat(val, 64)
  1210. durationCoefficient := durationHours / util.HoursPerMonth
  1211. if err != nil {
  1212. return nil, "", fmt.Errorf("Unable to parse shared cost %s: %s", val, err.Error())
  1213. }
  1214. sc[key] = &SharedCostInfo{
  1215. Name: key,
  1216. Cost: cost * durationCoefficient,
  1217. }
  1218. }
  1219. }
  1220. profileStart = time.Now()
  1221. profileName = profileBaseName + ": compute idle coefficient"
  1222. idleCoefficients := make(map[string]float64)
  1223. if allocateIdle {
  1224. idleDurationCalcHours := durationHours
  1225. if durationHours < 1 {
  1226. idleDurationCalcHours = 1
  1227. }
  1228. windowStr := fmt.Sprintf("%dh", int(idleDurationCalcHours))
  1229. if a.ThanosClient != nil {
  1230. offset = thanos.Offset()
  1231. klog.Infof("Setting offset to %s", offset)
  1232. }
  1233. idleCoefficients, err = a.ComputeIdleCoefficient(costData, promClient, a.CloudProvider, discount, customDiscount, windowStr, offset)
  1234. if err != nil {
  1235. klog.Errorf("error computing idle coefficient: windowString=%s, offset=%s, err=%s", windowStr, offset, err)
  1236. return nil, "", err
  1237. }
  1238. }
  1239. for cid, idleCoefficient := range idleCoefficients {
  1240. klog.Infof("Idle Coeff: %s: %f", cid, idleCoefficient)
  1241. }
  1242. totalContainerCost := 0.0
  1243. if shared == SplitTypeWeighted {
  1244. totalContainerCost = GetTotalContainerCost(costData, rate, a.CloudProvider, discount, customDiscount, idleCoefficients)
  1245. }
  1246. measureTime(profileStart, profileThreshold, profileName)
  1247. profileStart = time.Now()
  1248. profileName = profileBaseName + ": filter cost data"
  1249. // filter cost data by namespace and cluster after caching for maximal cache hits
  1250. costData, filteredContainerCount, filteredEnvironments := FilterCostData(costData, retainFuncs, filterFuncs)
  1251. measureTime(profileStart, profileThreshold, profileName)
  1252. profileStart = time.Now()
  1253. profileName = profileBaseName + ": aggregate cost data"
  1254. // aggregate cost model data by given fields and cache the result for the default expiration
  1255. opts := &AggregationOptions{
  1256. Discount: discount,
  1257. CustomDiscount: customDiscount,
  1258. IdleCoefficients: idleCoefficients,
  1259. IncludeEfficiency: includeEfficiency,
  1260. IncludeTimeSeries: includeTimeSeries,
  1261. Rate: rate,
  1262. ResolutionHours: resolutionHours,
  1263. SharedResourceInfo: sri,
  1264. SharedCosts: sc,
  1265. FilteredContainerCount: filteredContainerCount,
  1266. FilteredEnvironments: filteredEnvironments,
  1267. TotalContainerCost: totalContainerCost,
  1268. SharedSplit: shared,
  1269. }
  1270. result := AggregateCostData(costData, field, subfields, a.CloudProvider, opts)
  1271. // If sending time series data back, switch scale back to hourly data. At this point,
  1272. // resolutionHours may have converted our hourly data to more- or less-than hourly data.
  1273. if includeTimeSeries {
  1274. for _, aggs := range result {
  1275. ScaleAggregationTimeSeries(aggs, resolutionHours)
  1276. }
  1277. }
  1278. // compute length of the time series in the cost data and only cache
  1279. // aggregation results if the length is sufficiently high
  1280. costDataLen := costDataTimeSeriesLength(costData)
  1281. if costDataLen >= minCostDataLength && durationHours > 1 && !noCache {
  1282. // Set the result map (rather than a pointer to it) because map is a reference type
  1283. klog.Infof("Caching key in aggregate cache: %s", key)
  1284. a.AggregateCache.Set(aggKey, result, cacheExpiry)
  1285. } else {
  1286. klog.Infof("Not caching for key %s. Not enough data: %t, Duration less than 1h: %t, noCache: %t", key, costDataLen < minCostDataLength, durationHours < 1, noCache)
  1287. }
  1288. measureTime(profileStart, profileThreshold, profileName)
  1289. return result, cacheMessage, nil
  1290. }
  1291. // ScaleAggregationTimeSeries reverses the scaling done by ScaleHourlyCostData, returning
  1292. // the aggregation's time series to hourly data.
  1293. func ScaleAggregationTimeSeries(aggregation *Aggregation, resolutionHours float64) {
  1294. for _, v := range aggregation.CPUCostVector {
  1295. v.Value /= resolutionHours
  1296. }
  1297. for _, v := range aggregation.GPUCostVector {
  1298. v.Value /= resolutionHours
  1299. }
  1300. for _, v := range aggregation.RAMCostVector {
  1301. v.Value /= resolutionHours
  1302. }
  1303. for _, v := range aggregation.PVCostVector {
  1304. v.Value /= resolutionHours
  1305. }
  1306. for _, v := range aggregation.NetworkCostVector {
  1307. v.Value /= resolutionHours
  1308. }
  1309. for _, v := range aggregation.TotalCostVector {
  1310. v.Value /= resolutionHours
  1311. }
  1312. return
  1313. }
  1314. // String returns a string representation of the encapsulated shared resources, which
  1315. // can be used to uniquely identify a set of shared resources. Sorting sets of shared
  1316. // resources ensures that strings representing permutations of the same combination match.
  1317. func (s *SharedResourceInfo) String() string {
  1318. if s == nil {
  1319. return ""
  1320. }
  1321. nss := []string{}
  1322. for ns := range s.SharedNamespace {
  1323. nss = append(nss, ns)
  1324. }
  1325. sort.Strings(nss)
  1326. nsStr := strings.Join(nss, ",")
  1327. labels := []string{}
  1328. for lbl, vals := range s.LabelSelectors {
  1329. for val := range vals {
  1330. if lbl != "" && val != "" {
  1331. labels = append(labels, fmt.Sprintf("%s=%s", lbl, val))
  1332. }
  1333. }
  1334. }
  1335. sort.Strings(labels)
  1336. labelStr := strings.Join(labels, ",")
  1337. return fmt.Sprintf("%s:%s", nsStr, labelStr)
  1338. }
  1339. type aggKeyParams struct {
  1340. duration string
  1341. offset string
  1342. filters map[string]string
  1343. field string
  1344. subfields []string
  1345. rate string
  1346. sri *SharedResourceInfo
  1347. shareType string
  1348. idle bool
  1349. timeSeries bool
  1350. efficiency bool
  1351. }
  1352. // GenerateAggKey generates a parameter-unique key for caching the aggregate cost model
  1353. func GenerateAggKey(ps aggKeyParams) string {
  1354. // parse, trim, and sort podprefix filters
  1355. podPrefixFilters := []string{}
  1356. if ppfs, ok := ps.filters["podprefix"]; ok && ppfs != "" {
  1357. for _, psf := range strings.Split(ppfs, ",") {
  1358. podPrefixFilters = append(podPrefixFilters, strings.TrimSpace(psf))
  1359. }
  1360. }
  1361. sort.Strings(podPrefixFilters)
  1362. podPrefixFiltersStr := strings.Join(podPrefixFilters, ",")
  1363. // parse, trim, and sort namespace filters
  1364. nsFilters := []string{}
  1365. if nsfs, ok := ps.filters["namespace"]; ok && nsfs != "" {
  1366. for _, nsf := range strings.Split(nsfs, ",") {
  1367. nsFilters = append(nsFilters, strings.TrimSpace(nsf))
  1368. }
  1369. }
  1370. sort.Strings(nsFilters)
  1371. nsFilterStr := strings.Join(nsFilters, ",")
  1372. // parse, trim, and sort node filters
  1373. nodeFilters := []string{}
  1374. if nodefs, ok := ps.filters["node"]; ok && nodefs != "" {
  1375. for _, nodef := range strings.Split(nodefs, ",") {
  1376. nodeFilters = append(nodeFilters, strings.TrimSpace(nodef))
  1377. }
  1378. }
  1379. sort.Strings(nodeFilters)
  1380. nodeFilterStr := strings.Join(nodeFilters, ",")
  1381. // parse, trim, and sort cluster filters
  1382. cFilters := []string{}
  1383. if cfs, ok := ps.filters["cluster"]; ok && cfs != "" {
  1384. for _, cf := range strings.Split(cfs, ",") {
  1385. cFilters = append(cFilters, strings.TrimSpace(cf))
  1386. }
  1387. }
  1388. sort.Strings(cFilters)
  1389. cFilterStr := strings.Join(cFilters, ",")
  1390. // parse, trim, and sort label filters
  1391. lFilters := []string{}
  1392. if lfs, ok := ps.filters["labels"]; ok && lfs != "" {
  1393. for _, lf := range strings.Split(lfs, ",") {
  1394. // trim whitespace from the label name and the label value
  1395. // of each label name/value pair, then reconstruct
  1396. // e.g. "tier = frontend, app = kubecost" == "app=kubecost,tier=frontend"
  1397. lfa := strings.Split(lf, "=")
  1398. if len(lfa) == 2 {
  1399. lfn := strings.TrimSpace(lfa[0])
  1400. lfv := strings.TrimSpace(lfa[1])
  1401. lFilters = append(lFilters, fmt.Sprintf("%s=%s", lfn, lfv))
  1402. } else {
  1403. // label is not of the form name=value, so log it and move on
  1404. klog.V(2).Infof("[Warning] GenerateAggKey: skipping illegal label filter: %s", lf)
  1405. }
  1406. }
  1407. }
  1408. sort.Strings(lFilters)
  1409. lFilterStr := strings.Join(lFilters, ",")
  1410. filterStr := fmt.Sprintf("%s:%s:%s:%s:%s", nsFilterStr, nodeFilterStr, cFilterStr, lFilterStr, podPrefixFiltersStr)
  1411. sort.Strings(ps.subfields)
  1412. fieldStr := fmt.Sprintf("%s:%s", ps.field, strings.Join(ps.subfields, ","))
  1413. return fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s:%t:%t:%t", ps.duration, ps.offset, filterStr, fieldStr, ps.rate,
  1414. ps.sri, ps.shareType, ps.idle, ps.timeSeries, ps.efficiency)
  1415. }
  1416. // Aggregator is capable of computing the aggregated cost model. This is
  1417. // a brutal interface, which should be cleaned up, but it's necessary for
  1418. // being able to swap in an ETL-backed implementation.
  1419. // TODO clean up, simplify
  1420. type Aggregator interface {
  1421. ComputeAggregateCostModel(promClient prometheusClient.Client, duration, offset, field string, subfields []string, rate string, filters map[string]string, sri *SharedResourceInfo, shared string, allocateIdle, includeTimeSeries, includeEfficiency, disableCache, clearCache, noCache, noExpireCache, remoteEnabled, disableSharedOverhead, useETLAdapter bool) (map[string]*Aggregation, string, error)
  1422. }
  1423. func (a *Accesses) warmAggregateCostModelCache() {
  1424. // Only allow one concurrent cache-warming operation
  1425. sem := util.NewSemaphore(1)
  1426. // Set default values, pulling them from application settings where applicable, and warm the cache
  1427. // for the given duration. Cache is intentionally set to expire (i.e. noExpireCache=false) so that
  1428. // if the default parameters change, the old cached defaults with eventually expire. Thus, the
  1429. // timing of the cache expiry/refresh is the only mechanism ensuring 100% cache warmth.
  1430. warmFunc := func(duration, durationHrs, offset string, cacheEfficiencyData bool) (error, error) {
  1431. field := "namespace"
  1432. subfields := []string{}
  1433. rate := ""
  1434. filters := map[string]string{}
  1435. includeTimeSeries := false
  1436. includeEfficiency := true
  1437. disableCache := true
  1438. clearCache := false
  1439. noCache := false
  1440. noExpireCache := false
  1441. remote := true
  1442. shareSplit := "weighted"
  1443. remoteAvailable := env.IsRemoteEnabled()
  1444. remoteEnabled := remote && remoteAvailable
  1445. promClient := a.GetPrometheusClient(remote)
  1446. allocateIdle := cloud.AllocateIdleByDefault(a.CloudProvider)
  1447. sharedNamespaces := cloud.SharedNamespaces(a.CloudProvider)
  1448. sharedLabelNames, sharedLabelValues := cloud.SharedLabels(a.CloudProvider)
  1449. var sri *SharedResourceInfo
  1450. if len(sharedNamespaces) > 0 || len(sharedLabelNames) > 0 {
  1451. sri = NewSharedResourceInfo(true, sharedNamespaces, sharedLabelNames, sharedLabelValues)
  1452. }
  1453. aggKey := GenerateAggKey(aggKeyParams{
  1454. duration: duration,
  1455. offset: offset,
  1456. filters: filters,
  1457. field: field,
  1458. subfields: subfields,
  1459. rate: rate,
  1460. sri: sri,
  1461. shareType: shareSplit,
  1462. idle: allocateIdle,
  1463. timeSeries: includeTimeSeries,
  1464. efficiency: includeEfficiency,
  1465. })
  1466. log.Infof("aggregation: cache warming defaults: %s", aggKey)
  1467. key := fmt.Sprintf("%s:%s", durationHrs, offset)
  1468. _, _, aggErr := a.ComputeAggregateCostModel(promClient, duration, offset, field, subfields, rate, filters,
  1469. sri, shareSplit, allocateIdle, includeTimeSeries, includeEfficiency, disableCache,
  1470. clearCache, noCache, noExpireCache, remoteEnabled, false, false)
  1471. if aggErr != nil {
  1472. log.Infof("Error building cache %s: %s", key, aggErr)
  1473. }
  1474. if a.ThanosClient != nil {
  1475. offset = thanos.Offset()
  1476. log.Infof("Setting offset to %s", offset)
  1477. }
  1478. totals, err := a.ComputeClusterCosts(promClient, a.CloudProvider, durationHrs, offset, cacheEfficiencyData)
  1479. if err != nil {
  1480. log.Infof("Error building cluster costs cache %s", key)
  1481. }
  1482. maxMinutesWithData := 0.0
  1483. for _, cluster := range totals {
  1484. if cluster.DataMinutes > maxMinutesWithData {
  1485. maxMinutesWithData = cluster.DataMinutes
  1486. }
  1487. }
  1488. if len(totals) > 0 && maxMinutesWithData > clusterCostsCacheMinutes {
  1489. a.ClusterCostsCache.Set(key, totals, a.GetCacheExpiration(duration))
  1490. log.Infof("caching %s cluster costs for %s", duration, a.GetCacheExpiration(duration))
  1491. } else {
  1492. log.Warningf("not caching %s cluster costs: no data or less than %f minutes data ", duration, clusterCostsCacheMinutes)
  1493. }
  1494. return aggErr, err
  1495. }
  1496. // 1 day
  1497. go func(sem *util.Semaphore) {
  1498. defer errors.HandlePanic()
  1499. for {
  1500. duration := "1d"
  1501. offset := "1m"
  1502. durHrs := "24h"
  1503. sem.Acquire()
  1504. warmFunc(duration, durHrs, offset, true)
  1505. sem.Return()
  1506. log.Infof("aggregation: warm cache: %s", duration)
  1507. time.Sleep(a.GetCacheRefresh(duration))
  1508. }
  1509. }(sem)
  1510. // 2 day
  1511. go func(sem *util.Semaphore) {
  1512. defer errors.HandlePanic()
  1513. for {
  1514. duration := "2d"
  1515. offset := "1m"
  1516. durHrs := "48h"
  1517. sem.Acquire()
  1518. warmFunc(duration, durHrs, offset, false)
  1519. sem.Return()
  1520. log.Infof("aggregation: warm cache: %s", duration)
  1521. time.Sleep(a.GetCacheRefresh(duration))
  1522. }
  1523. }(sem)
  1524. if !env.IsETLEnabled() {
  1525. // 7 day
  1526. go func(sem *util.Semaphore) {
  1527. defer errors.HandlePanic()
  1528. for {
  1529. duration := "7d"
  1530. offset := "1m"
  1531. durHrs := "168h"
  1532. sem.Acquire()
  1533. aggErr, err := warmFunc(duration, durHrs, offset, false)
  1534. sem.Return()
  1535. log.Infof("aggregation: warm cache: %s", duration)
  1536. if aggErr == nil && err == nil {
  1537. time.Sleep(a.GetCacheRefresh(duration))
  1538. } else {
  1539. time.Sleep(5 * time.Minute)
  1540. }
  1541. }
  1542. }(sem)
  1543. // 30 day
  1544. go func(sem *util.Semaphore) {
  1545. defer errors.HandlePanic()
  1546. for {
  1547. duration := "30d"
  1548. offset := "1m"
  1549. durHrs := "720h"
  1550. sem.Acquire()
  1551. aggErr, err := warmFunc(duration, durHrs, offset, false)
  1552. sem.Return()
  1553. if aggErr == nil && err == nil {
  1554. time.Sleep(a.GetCacheRefresh(duration))
  1555. } else {
  1556. time.Sleep(5 * time.Minute)
  1557. }
  1558. }
  1559. }(sem)
  1560. }
  1561. }
  1562. // AggregateCostModelHandler handles requests to the aggregated cost model API. See
  1563. // ComputeAggregateCostModel for details.
  1564. func (a *Accesses) AggregateCostModelHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  1565. w.Header().Set("Content-Type", "application/json")
  1566. windowStr := r.URL.Query().Get("window")
  1567. // Convert UTC-RFC3339 pairs to configured UTC offset
  1568. // e.g. with UTC offset of -0600, 2020-07-01T00:00:00Z becomes
  1569. // 2020-07-01T06:00:00Z == 2020-07-01T00:00:00-0600
  1570. // TODO niko/etl fix the frontend because this is confusing if you're
  1571. // actually asking for UTC time (...Z) and we swap that "Z" out for the
  1572. // configured UTC offset without asking
  1573. rfc3339 := `\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ`
  1574. regex := regexp.MustCompile(fmt.Sprintf(`(%s),(%s)`, rfc3339, rfc3339))
  1575. match := regex.FindStringSubmatch(windowStr)
  1576. if match != nil {
  1577. start, _ := time.Parse(time.RFC3339, match[1])
  1578. start = start.Add(-env.GetParsedUTCOffset()).In(time.UTC)
  1579. end, _ := time.Parse(time.RFC3339, match[2])
  1580. end = end.Add(-env.GetParsedUTCOffset()).In(time.UTC)
  1581. windowStr = fmt.Sprintf("%sZ,%sZ", start.Format("2006-01-02T15:04:05"), end.Format("2006-01-02T15:04:05Z"))
  1582. }
  1583. // determine duration and offset from query parameters
  1584. window, err := kubecost.ParseWindowWithOffset(windowStr, env.GetParsedUTCOffset())
  1585. if err != nil || window.Start() == nil {
  1586. http.Error(w, fmt.Sprintf("invalid window: %s", err), http.StatusBadRequest)
  1587. return
  1588. }
  1589. duration, offset := window.ToDurationOffset()
  1590. durRegex := regexp.MustCompile(`^(\d+)(m|h|d|s)$`)
  1591. isDurationStr := durRegex.MatchString(windowStr)
  1592. // legacy offset option should override window offset
  1593. if r.URL.Query().Get("offset") != "" {
  1594. offset = r.URL.Query().Get("offset")
  1595. // Shift window by offset, but only when manually set with separate
  1596. // parameter and window was provided as a duration string. Otherwise,
  1597. // do not alter the (duration, offset) from ParseWindowWithOffset.
  1598. if offset != "1m" && isDurationStr {
  1599. match := durRegex.FindStringSubmatch(offset)
  1600. if match != nil && len(match) == 3 {
  1601. dur := time.Minute
  1602. if match[2] == "h" {
  1603. dur = time.Hour
  1604. }
  1605. if match[2] == "d" {
  1606. dur = 24 * time.Hour
  1607. }
  1608. if match[2] == "s" {
  1609. dur = time.Second
  1610. }
  1611. num, _ := strconv.ParseInt(match[1], 10, 64)
  1612. window = window.Shift(-time.Duration(num) * dur)
  1613. }
  1614. }
  1615. }
  1616. // redirect requests with no offset to a 1m offset to improve cache hits
  1617. if offset == "" {
  1618. offset = "1m"
  1619. }
  1620. // parse remaining query parameters
  1621. namespace := r.URL.Query().Get("namespace")
  1622. cluster := r.URL.Query().Get("cluster")
  1623. labels := r.URL.Query().Get("labels")
  1624. podprefix := r.URL.Query().Get("podprefix")
  1625. labelArray := strings.Split(labels, "=")
  1626. labelArray[0] = strings.ReplaceAll(labelArray[0], "-", "_")
  1627. labels = strings.Join(labelArray, "=")
  1628. field := r.URL.Query().Get("aggregation")
  1629. subfieldStr := r.URL.Query().Get("aggregationSubfield")
  1630. rate := r.URL.Query().Get("rate")
  1631. idleFlag := r.URL.Query().Get("allocateIdle")
  1632. sharedNamespaces := r.URL.Query().Get("sharedNamespaces")
  1633. sharedLabelNames := r.URL.Query().Get("sharedLabelNames")
  1634. sharedLabelValues := r.URL.Query().Get("sharedLabelValues")
  1635. remote := r.URL.Query().Get("remote") != "false"
  1636. shared := r.URL.Query().Get("sharedSplit")
  1637. subfields := []string{}
  1638. if len(subfieldStr) > 0 {
  1639. s := strings.Split(r.URL.Query().Get("aggregationSubfield"), ",")
  1640. for _, rawLabel := range s {
  1641. subfields = append(subfields, prom.SanitizeLabelName(rawLabel))
  1642. }
  1643. }
  1644. var allocateIdle bool
  1645. if idleFlag == "default" {
  1646. c, _ := a.CloudProvider.GetConfig()
  1647. allocateIdle = (c.DefaultIdle == "true")
  1648. } else {
  1649. allocateIdle = (idleFlag == "true")
  1650. }
  1651. // timeSeries == true maintains the time series dimension of the data,
  1652. // which by default gets summed over the entire interval
  1653. includeTimeSeries := r.URL.Query().Get("timeSeries") == "true"
  1654. // efficiency == true aggregates and returns usage and efficiency data
  1655. // includeEfficiency := r.URL.Query().Get("efficiency") == "true"
  1656. // efficiency has been deprecated in favor of a default to always send efficiency
  1657. includeEfficiency := true
  1658. // TODO niko/caching rename "recomputeCache"
  1659. // disableCache, if set to "true", tells this function to recompute and
  1660. // cache the requested data
  1661. disableCache := r.URL.Query().Get("disableCache") == "true"
  1662. // clearCache, if set to "true", tells this function to flush the cache,
  1663. // then recompute and cache the requested data
  1664. clearCache := r.URL.Query().Get("clearCache") == "true"
  1665. // noCache avoids the cache altogether, both reading from and writing to
  1666. noCache := r.URL.Query().Get("noCache") == "true"
  1667. // noExpireCache should only be used by cache warming to set non-expiring caches
  1668. noExpireCache := false
  1669. // aggregation field is required
  1670. if field == "" {
  1671. http.Error(w, "Missing aggregation field parameter", http.StatusBadRequest)
  1672. return
  1673. }
  1674. // aggregation subfield is required when aggregation field is "label"
  1675. if field == "label" && len(subfields) == 0 {
  1676. http.Error(w, "Missing aggregation subfield parameter for aggregation by label", http.StatusBadRequest)
  1677. return
  1678. }
  1679. // enforce one of four available rate options
  1680. if rate != "" && rate != "hourly" && rate != "daily" && rate != "monthly" {
  1681. http.Error(w, "If set, rate parameter must be one of: 'hourly', 'daily', 'monthly'", http.StatusBadRequest)
  1682. return
  1683. }
  1684. // parse cost data filters
  1685. // namespace and cluster are exact-string-matches
  1686. // labels are expected to be comma-separated and to take the form key=value
  1687. // e.g. app=cost-analyzer,app.kubernetes.io/instance=kubecost
  1688. filters := map[string]string{
  1689. "namespace": namespace,
  1690. "cluster": cluster,
  1691. "labels": labels,
  1692. "podprefix": podprefix,
  1693. }
  1694. // parse shared resources
  1695. sn := []string{}
  1696. sln := []string{}
  1697. slv := []string{}
  1698. if sharedNamespaces != "" {
  1699. sn = strings.Split(sharedNamespaces, ",")
  1700. }
  1701. if sharedLabelNames != "" {
  1702. sln = strings.Split(sharedLabelNames, ",")
  1703. slv = strings.Split(sharedLabelValues, ",")
  1704. if len(sln) != len(slv) || slv[0] == "" {
  1705. http.Error(w, "Supply exacly one shared label value per shared label name", http.StatusBadRequest)
  1706. return
  1707. }
  1708. }
  1709. var sr *SharedResourceInfo
  1710. if len(sn) > 0 || len(sln) > 0 {
  1711. sr = NewSharedResourceInfo(true, sn, sln, slv)
  1712. }
  1713. // enable remote if it is available and not disabled
  1714. remoteEnabled := remote && env.IsRemoteEnabled()
  1715. promClient := a.GetPrometheusClient(remote)
  1716. useETLAdapter := r.URL.Query().Get("etl") == "true"
  1717. var data map[string]*Aggregation
  1718. var message string
  1719. data, message, err = a.AggAPI.ComputeAggregateCostModel(promClient, duration, offset, field, subfields, rate, filters, sr, shared, allocateIdle, includeTimeSeries, includeEfficiency, disableCache, clearCache, noCache, noExpireCache, remoteEnabled, false, useETLAdapter)
  1720. // Find any warnings in http request context
  1721. warning, _ := util.GetWarning(r)
  1722. if err != nil {
  1723. if emptyErr, ok := err.(*EmptyDataError); ok {
  1724. if warning == "" {
  1725. w.Write(WrapData(map[string]interface{}{}, emptyErr))
  1726. } else {
  1727. w.Write(WrapDataWithWarning(map[string]interface{}{}, emptyErr, warning))
  1728. }
  1729. return
  1730. }
  1731. if boundaryErr, ok := err.(*kubecost.BoundaryError); ok {
  1732. if window.Start() != nil && window.Start().After(time.Now().Add(-90*24*time.Hour)) {
  1733. // Asking for data within a 90 day period: it will be available
  1734. // after the pipeline builds
  1735. msg := "Data will be available after ETL is built"
  1736. rex := regexp.MustCompile(`(\d+\.*\d*)%`)
  1737. match := rex.FindStringSubmatch(boundaryErr.Message)
  1738. if len(match) > 1 {
  1739. completionPct, err := strconv.ParseFloat(match[1], 64)
  1740. if err == nil {
  1741. msg = fmt.Sprintf("%s (%.1f%% complete)", msg, completionPct)
  1742. }
  1743. }
  1744. http.Error(w, msg, http.StatusInternalServerError)
  1745. } else {
  1746. // Boundary error outside of 90 day period; may not be available
  1747. http.Error(w, boundaryErr.Error(), http.StatusInternalServerError)
  1748. }
  1749. return
  1750. }
  1751. errStr := fmt.Sprintf("error computing aggregate cost model: %s", err)
  1752. http.Error(w, errStr, http.StatusInternalServerError)
  1753. return
  1754. }
  1755. if warning == "" {
  1756. w.Write(WrapDataWithMessage(data, nil, message))
  1757. } else {
  1758. w.Write(WrapDataWithMessageAndWarning(data, nil, message, warning))
  1759. }
  1760. }