aggregation.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package costmodel
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/julienschmidt/httprouter"
  8. "github.com/opencost/opencost/core/pkg/filter/allocation"
  9. "github.com/opencost/opencost/core/pkg/opencost"
  10. "github.com/opencost/opencost/core/pkg/util/httputil"
  11. "github.com/opencost/opencost/pkg/env"
  12. )
  13. const (
  14. // SplitTypeWeighted signals that shared costs should be shared
  15. // proportionally, rather than evenly
  16. SplitTypeWeighted = "weighted"
  17. // UnallocatedSubfield indicates an allocation datum that does not have the
  18. // chosen Aggregator; e.g. during aggregation by some label, there may be
  19. // cost data that do not have the given label.
  20. UnallocatedSubfield = "__unallocated__"
  21. )
  22. // ParseAggregationProperties attempts to parse and return aggregation properties
  23. // encoded under the given key. If none exist, or if parsing fails, an error
  24. // is returned with empty AllocationProperties.
  25. func ParseAggregationProperties(aggregations []string) ([]string, error) {
  26. aggregateBy := []string{}
  27. // In case of no aggregation option, aggregate to the container, with a key Cluster/Node/Namespace/Pod/Container
  28. if len(aggregations) == 0 {
  29. aggregateBy = []string{
  30. opencost.AllocationClusterProp,
  31. opencost.AllocationNodeProp,
  32. opencost.AllocationNamespaceProp,
  33. opencost.AllocationPodProp,
  34. opencost.AllocationContainerProp,
  35. }
  36. } else if len(aggregations) == 1 && aggregations[0] == "all" {
  37. aggregateBy = []string{}
  38. } else {
  39. for _, agg := range aggregations {
  40. aggregate := strings.TrimSpace(agg)
  41. if aggregate != "" {
  42. if prop, err := opencost.ParseProperty(aggregate); err == nil {
  43. aggregateBy = append(aggregateBy, string(prop))
  44. } else if strings.HasPrefix(aggregate, "label:") {
  45. aggregateBy = append(aggregateBy, aggregate)
  46. } else if strings.HasPrefix(aggregate, "annotation:") {
  47. aggregateBy = append(aggregateBy, aggregate)
  48. }
  49. }
  50. }
  51. }
  52. return aggregateBy, nil
  53. }
  54. func resolveAccumulateOption(accumulate opencost.AccumulateOption, accumulateBy string) (opencost.AccumulateOption, error) {
  55. accumulateByRaw := strings.TrimSpace(strings.ToLower(accumulateBy))
  56. if accumulateByRaw == "" {
  57. return accumulate, nil
  58. }
  59. if accumulateByRaw == "all" {
  60. return opencost.AccumulateOptionAll, nil
  61. }
  62. if accumulateByRaw == "none" {
  63. return opencost.AccumulateOptionNone, nil
  64. }
  65. accumulateByOpt := opencost.ParseAccumulate(accumulateByRaw)
  66. if accumulateByOpt == opencost.AccumulateOptionNone {
  67. return opencost.AccumulateOptionNone, fmt.Errorf("invalid accumulateBy option: %s", accumulateBy)
  68. }
  69. return accumulateByOpt, nil
  70. }
  71. func resolveAccumulateFromQuery(qp httputil.QueryParams) opencost.AccumulateOption {
  72. rawAccumulate := strings.TrimSpace(qp.Get("accumulate", ""))
  73. if strings.EqualFold(rawAccumulate, string(opencost.AccumulateOptionAll)) {
  74. return opencost.AccumulateOptionAll
  75. }
  76. accumulate := opencost.ParseAccumulate(rawAccumulate)
  77. if accumulate == opencost.AccumulateOptionNone && qp.GetBool("accumulate", false) {
  78. return opencost.AccumulateOptionAll
  79. }
  80. return accumulate
  81. }
  82. func resolveStepForAccumulate(step time.Duration, accumulateBy opencost.AccumulateOption) time.Duration {
  83. const (
  84. day = 24 * time.Hour
  85. week = 7 * day
  86. )
  87. switch accumulateBy {
  88. case opencost.AccumulateOptionHour:
  89. return time.Hour
  90. case opencost.AccumulateOptionDay:
  91. // day accumulation supports either hourly or already-daily sets
  92. if step == day {
  93. return day
  94. }
  95. return time.Hour
  96. case opencost.AccumulateOptionWeek, opencost.AccumulateOptionMonth, opencost.AccumulateOptionQuarter:
  97. // week accumulation supports either daily or already-weekly sets
  98. if accumulateBy == opencost.AccumulateOptionWeek && step == week {
  99. return week
  100. }
  101. return day
  102. default:
  103. return step
  104. }
  105. }
  106. func resolveDefaultStepFromAccumulate(window opencost.Window, accumulateBy opencost.AccumulateOption) time.Duration {
  107. switch accumulateBy {
  108. case opencost.AccumulateOptionHour:
  109. return time.Hour
  110. case opencost.AccumulateOptionDay:
  111. return 24 * time.Hour
  112. case opencost.AccumulateOptionWeek:
  113. return 7 * 24 * time.Hour
  114. case opencost.AccumulateOptionMonth, opencost.AccumulateOptionQuarter:
  115. // month/quarter accumulation requires daily input sets
  116. return 24 * time.Hour
  117. case opencost.AccumulateOptionAll:
  118. return window.Duration()
  119. default:
  120. return window.Duration()
  121. }
  122. }
  123. func resolveStepFromQuery(qp httputil.QueryParams, window opencost.Window, accumulateBy opencost.AccumulateOption) (time.Duration, error) {
  124. stepRaw := strings.TrimSpace(strings.ToLower(qp.Get("step", "")))
  125. if stepRaw == "" {
  126. step := resolveDefaultStepFromAccumulate(window, accumulateBy)
  127. return resolveStepForAccumulate(step, accumulateBy), nil
  128. }
  129. switch stepRaw {
  130. case "hour":
  131. return resolveStepForAccumulate(time.Hour, accumulateBy), nil
  132. case "day":
  133. return resolveStepForAccumulate(24*time.Hour, accumulateBy), nil
  134. case "week":
  135. return resolveStepForAccumulate(7*24*time.Hour, accumulateBy), nil
  136. case "month":
  137. // month accumulation operates on daily inputs and calendar-rounded query windows
  138. return resolveStepForAccumulate(24*time.Hour, accumulateBy), nil
  139. case "quarter":
  140. // quarter accumulation operates on daily inputs and calendar-rounded query windows
  141. return resolveStepForAccumulate(24*time.Hour, accumulateBy), nil
  142. default:
  143. step, err := time.ParseDuration(stepRaw)
  144. if err != nil {
  145. return 0, fmt.Errorf("invalid step %q: must be a Go duration or one of hour, day, week, month, quarter: %w", stepRaw, err)
  146. }
  147. return resolveStepForAccumulate(step, accumulateBy), nil
  148. }
  149. }
  150. func resolveQueryWindowForAccumulate(window opencost.Window, accumulateBy opencost.AccumulateOption) (opencost.Window, error) {
  151. switch accumulateBy {
  152. case opencost.AccumulateOptionHour, opencost.AccumulateOptionDay, opencost.AccumulateOptionWeek, opencost.AccumulateOptionMonth, opencost.AccumulateOptionQuarter:
  153. windows, err := window.GetAccumulateWindows(accumulateBy)
  154. if err != nil {
  155. return opencost.Window{}, err
  156. }
  157. if len(windows) == 0 {
  158. return opencost.Window{}, fmt.Errorf("no query windows for accumulate option %s", accumulateBy)
  159. }
  160. return opencost.NewClosedWindow(*windows[0].Start(), *windows[len(windows)-1].End()), nil
  161. default:
  162. return window, nil
  163. }
  164. }
  165. func trimAllocationSetRangeToRequestWindow(asr *opencost.AllocationSetRange, requestWindow opencost.Window) *opencost.AllocationSetRange {
  166. if asr == nil {
  167. return nil
  168. }
  169. trimmed := opencost.NewAllocationSetRange()
  170. trimmed.FromStore = asr.FromStore
  171. for _, as := range asr.Allocations {
  172. // Keep only sets that overlap the originally requested window.
  173. if as.Start().Before(*requestWindow.End()) && as.End().After(*requestWindow.Start()) {
  174. trimmed.Append(as)
  175. }
  176. }
  177. return trimmed
  178. }
  179. func (a *Accesses) ComputeAllocationHandlerSummary(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  180. w.Header().Set("Content-Type", "application/json")
  181. qp := httputil.NewQueryParams(r.URL.Query())
  182. // Window is a required field describing the window of time over which to
  183. // compute allocation data.
  184. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  185. if err != nil {
  186. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  187. }
  188. // Step is an optional parameter that defines the duration per-set, i.e.
  189. // the window for an AllocationSet, of the AllocationSetRange to be
  190. // computed. Defaults to the window size, making one set.
  191. // Aggregation is a required comma-separated list of fields by which to
  192. // aggregate results. Some fields allow a sub-field, which is distinguished
  193. // with a colon; e.g. "label:app".
  194. // Examples: "namespace", "namespace,label:app"
  195. aggregations := qp.GetList("aggregate", ",")
  196. aggregateBy, err := ParseAggregationProperties(aggregations)
  197. if err != nil {
  198. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  199. }
  200. // Accumulate is an optional parameter that accepts bool-style values (e.g.
  201. // true/1) or options (e.g. day/week/month) and governs accumulation windowing.
  202. accumulateOpt := resolveAccumulateFromQuery(qp)
  203. accumulateBy, err := resolveAccumulateOption(accumulateOpt, qp.Get("accumulateBy", ""))
  204. if err != nil {
  205. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid 'accumulateBy' parameter: %s", err)))
  206. return
  207. }
  208. step, err := resolveStepFromQuery(qp, window, accumulateBy)
  209. if err != nil {
  210. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid step parameter: %s", err)))
  211. return
  212. }
  213. queryWindow, err := resolveQueryWindowForAccumulate(window, accumulateBy)
  214. if err != nil {
  215. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid accumulation configuration: %s", err)))
  216. return
  217. }
  218. // Get allocation filter if provided
  219. allocationFilter := qp.Get("filter", "")
  220. // Query for AllocationSets in increments of the given step duration,
  221. // appending each to the AllocationSetRange.
  222. asr := opencost.NewAllocationSetRange()
  223. stepStart := *queryWindow.Start()
  224. for queryWindow.End().After(stepStart) {
  225. stepEnd := stepStart.Add(step)
  226. stepWindow := opencost.NewWindow(&stepStart, &stepEnd)
  227. as, err := a.Model.ComputeAllocation(*stepWindow.Start(), *stepWindow.End())
  228. if err != nil {
  229. proto.WriteError(w, proto.InternalServerError(err.Error()))
  230. return
  231. }
  232. asr.Append(as)
  233. stepStart = stepEnd
  234. }
  235. // Apply allocation filter if provided
  236. if allocationFilter != "" {
  237. parser := allocation.NewAllocationFilterParser()
  238. filterNode, err := parser.Parse(allocationFilter)
  239. if err != nil {
  240. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid filter: %s", err)))
  241. return
  242. }
  243. compiler := opencost.NewAllocationMatchCompiler(nil)
  244. matcher, err := compiler.Compile(filterNode)
  245. if err != nil {
  246. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Failed to compile filter: %s", err)))
  247. return
  248. }
  249. filteredASR := opencost.NewAllocationSetRange()
  250. for _, as := range asr.Allocations {
  251. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  252. for _, alloc := range as.Allocations {
  253. if matcher.Matches(alloc) {
  254. filteredAS.Set(alloc)
  255. }
  256. }
  257. if filteredAS.Length() > 0 {
  258. filteredASR.Append(filteredAS)
  259. }
  260. }
  261. asr = filteredASR
  262. }
  263. // Aggregate, if requested
  264. if len(aggregateBy) > 0 {
  265. err = asr.AggregateBy(aggregateBy, nil)
  266. if err != nil {
  267. proto.WriteError(w, proto.InternalServerError(err.Error()))
  268. return
  269. }
  270. }
  271. // Accumulate, if requested
  272. if accumulateBy != opencost.AccumulateOptionNone {
  273. asr, err = asr.Accumulate(accumulateBy)
  274. if err != nil {
  275. proto.WriteError(w, proto.InternalServerError(err.Error()))
  276. return
  277. }
  278. asr = trimAllocationSetRangeToRequestWindow(asr, window)
  279. }
  280. sasl := []*opencost.SummaryAllocationSet{}
  281. for _, as := range asr.Allocations {
  282. sas := opencost.NewSummaryAllocationSet(as, nil, nil, false, false)
  283. sasl = append(sasl, sas)
  284. }
  285. sasr := opencost.NewSummaryAllocationSetRange(sasl...)
  286. WriteData(w, sasr, nil)
  287. }
  288. // ComputeAllocationHandler computes an AllocationSetRange from the CostModel.
  289. func (a *Accesses) ComputeAllocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  290. w.Header().Set("Content-Type", "application/json")
  291. qp := httputil.NewQueryParams(r.URL.Query())
  292. // Window is a required field describing the window of time over which to
  293. // compute allocation data.
  294. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  295. if err != nil {
  296. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  297. }
  298. // Step is an optional parameter that defines the duration per-set, i.e.
  299. // the window for an AllocationSet, of the AllocationSetRange to be
  300. // computed. Defaults to the window size, making one set.
  301. // Aggregation is an optional comma-separated list of fields by which to
  302. // aggregate results. Some fields allow a sub-field, which is distinguished
  303. // with a colon; e.g. "label:app".
  304. // Examples: "namespace", "namespace,label:app"
  305. aggregations := qp.GetList("aggregate", ",")
  306. aggregateBy, err := ParseAggregationProperties(aggregations)
  307. if err != nil {
  308. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  309. }
  310. // IncludeIdle, if true, uses Asset data to incorporate Idle Allocation
  311. includeIdle := qp.GetBool("includeIdle", false)
  312. // Accumulate is an optional parameter that accepts bool-style values (e.g.
  313. // true/1) or options (e.g. day/week/month) and governs accumulation windowing.
  314. accumulateOpt := resolveAccumulateFromQuery(qp)
  315. // AccumulateBy is an optional parameter that overrides accumulate with an
  316. // explicit accumulation option (e.g. all/day/week/month/quarter/none).
  317. accumulateBy, err := resolveAccumulateOption(accumulateOpt, qp.Get("accumulateBy", ""))
  318. if err != nil {
  319. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid 'accumulateBy' parameter: %s", err)))
  320. return
  321. }
  322. step, err := resolveStepFromQuery(qp, window, accumulateBy)
  323. if err != nil {
  324. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid step parameter: %s", err)))
  325. return
  326. }
  327. // IdleByNode, if true, computes idle allocations at the node level.
  328. // Otherwise it is computed at the cluster level. (Not relevant if idle
  329. // is not included.)
  330. idleByNode := qp.GetBool("idleByNode", false)
  331. sharedLoadBalancer := qp.GetBool("sharelb", false)
  332. // IncludeProportionalAssetResourceCosts, if true,
  333. includeProportionalAssetResourceCosts := qp.GetBool("includeProportionalAssetResourceCosts", false)
  334. // include aggregated labels/annotations if true
  335. includeAggregatedMetadata := qp.GetBool("includeAggregatedMetadata", false)
  336. shareIdle := qp.GetBool("shareIdle", false)
  337. // Get allocation filter if provided
  338. allocationFilter := qp.Get("filter", "")
  339. // Query allocations with filtering, aggregation, and accumulation.
  340. // Filtering is done BEFORE aggregation inside QueryAllocation to ensure
  341. // filters can match on all allocation properties (like cluster, node, etc.)
  342. // before they are potentially lost or merged during aggregation.
  343. asr, err := a.Model.QueryAllocation(window, step, aggregateBy, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, accumulateBy, shareIdle, allocationFilter)
  344. if err != nil {
  345. if strings.Contains(strings.ToLower(err.Error()), "bad request") {
  346. proto.WriteError(w, proto.BadRequest(err.Error()))
  347. } else {
  348. proto.WriteError(w, proto.InternalServerError(err.Error()))
  349. }
  350. return
  351. }
  352. WriteData(w, asr, nil)
  353. }