aggregation.go 14 KB

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