aggregation.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. }
  189. // Step is an optional parameter that defines the duration per-set, i.e.
  190. // the window for an AllocationSet, of the AllocationSetRange to be
  191. // computed. Defaults to the window size, making one set.
  192. // Aggregation is a required comma-separated list of fields by which to
  193. // aggregate results. Some fields allow a sub-field, which is distinguished
  194. // with a colon; e.g. "label:app".
  195. // Examples: "namespace", "namespace,label:app"
  196. aggregations := qp.GetList("aggregate", ",")
  197. aggregateBy, err := ParseAggregationProperties(aggregations)
  198. if err != nil {
  199. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  200. }
  201. // Accumulate is an optional parameter that accepts bool-style values (e.g.
  202. // true/1) or options (e.g. day/week/month) and governs accumulation windowing.
  203. accumulateOpt := resolveAccumulateFromQuery(qp)
  204. accumulateBy, err := resolveAccumulateOption(accumulateOpt, qp.Get("accumulateBy", ""))
  205. if err != nil {
  206. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid 'accumulateBy' parameter: %s", err)))
  207. return
  208. }
  209. step, err := resolveStepFromQuery(qp, window, accumulateBy)
  210. if err != nil {
  211. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid step parameter: %s", err)))
  212. return
  213. }
  214. queryWindow, err := resolveQueryWindowForAccumulate(window, accumulateBy)
  215. if err != nil {
  216. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid accumulation configuration: %s", err)))
  217. return
  218. }
  219. // Get allocation filter if provided
  220. allocationFilter := qp.Get("filter", "")
  221. // Query for AllocationSets in increments of the given step duration,
  222. // appending each to the AllocationSetRange.
  223. asr := opencost.NewAllocationSetRange()
  224. stepStart := *queryWindow.Start()
  225. for queryWindow.End().After(stepStart) {
  226. stepEnd := stepStart.Add(step)
  227. stepWindow := opencost.NewWindow(&stepStart, &stepEnd)
  228. as, err := a.Model.ComputeAllocation(*stepWindow.Start(), *stepWindow.End())
  229. if err != nil {
  230. proto.WriteError(w, proto.InternalServerError(err.Error()))
  231. return
  232. }
  233. asr.Append(as)
  234. stepStart = stepEnd
  235. }
  236. // Apply allocation filter if provided
  237. if allocationFilter != "" {
  238. parser := allocation.NewAllocationFilterParser()
  239. filterNode, err := parser.Parse(allocationFilter)
  240. if err != nil {
  241. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid filter: %s", err)))
  242. return
  243. }
  244. compiler := opencost.NewAllocationMatchCompiler(nil)
  245. matcher, err := compiler.Compile(filterNode)
  246. if err != nil {
  247. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Failed to compile filter: %s", err)))
  248. return
  249. }
  250. filteredASR := opencost.NewAllocationSetRange()
  251. for _, as := range asr.Allocations {
  252. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  253. for _, alloc := range as.Allocations {
  254. if matcher.Matches(alloc) {
  255. filteredAS.Set(alloc)
  256. }
  257. }
  258. if filteredAS.Length() > 0 {
  259. filteredASR.Append(filteredAS)
  260. }
  261. }
  262. asr = filteredASR
  263. }
  264. // Aggregate, if requested
  265. if len(aggregateBy) > 0 {
  266. err = asr.AggregateBy(aggregateBy, nil)
  267. if err != nil {
  268. proto.WriteError(w, proto.InternalServerError(err.Error()))
  269. return
  270. }
  271. }
  272. // Accumulate, if requested
  273. if accumulateBy != opencost.AccumulateOptionNone {
  274. asr, err = asr.Accumulate(accumulateBy)
  275. if err != nil {
  276. proto.WriteError(w, proto.InternalServerError(err.Error()))
  277. return
  278. }
  279. asr = trimAllocationSetRangeToRequestWindow(asr, window)
  280. }
  281. sasl := []*opencost.SummaryAllocationSet{}
  282. for _, as := range asr.Allocations {
  283. sas := opencost.NewSummaryAllocationSet(as, nil, nil, false, false)
  284. sasl = append(sasl, sas)
  285. }
  286. sasr := opencost.NewSummaryAllocationSetRange(sasl...)
  287. WriteData(w, sasr, nil)
  288. }
  289. // ComputeAllocationHandler computes an AllocationSetRange from the CostModel.
  290. func (a *Accesses) ComputeAllocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  291. w.Header().Set("Content-Type", "application/json")
  292. qp := httputil.NewQueryParams(r.URL.Query())
  293. // Window is a required field describing the window of time over which to
  294. // compute allocation data.
  295. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  296. if err != nil {
  297. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  298. }
  299. // Step is an optional parameter that defines the duration per-set, i.e.
  300. // the window for an AllocationSet, of the AllocationSetRange to be
  301. // computed. Defaults to the window size, making one set.
  302. // Aggregation is an optional comma-separated list of fields by which to
  303. // aggregate results. Some fields allow a sub-field, which is distinguished
  304. // with a colon; e.g. "label:app".
  305. // Examples: "namespace", "namespace,label:app"
  306. aggregations := qp.GetList("aggregate", ",")
  307. aggregateBy, err := ParseAggregationProperties(aggregations)
  308. if err != nil {
  309. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  310. }
  311. // IncludeIdle, if true, uses Asset data to incorporate Idle Allocation
  312. includeIdle := qp.GetBool("includeIdle", false)
  313. // Accumulate is an optional parameter that accepts bool-style values (e.g.
  314. // true/1) or options (e.g. day/week/month) and governs accumulation windowing.
  315. accumulateOpt := resolveAccumulateFromQuery(qp)
  316. // AccumulateBy is an optional parameter that overrides accumulate with an
  317. // explicit accumulation option (e.g. all/day/week/month/quarter/none).
  318. accumulateBy, err := resolveAccumulateOption(accumulateOpt, qp.Get("accumulateBy", ""))
  319. if err != nil {
  320. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid 'accumulateBy' parameter: %s", err)))
  321. return
  322. }
  323. step, err := resolveStepFromQuery(qp, window, accumulateBy)
  324. if err != nil {
  325. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid step parameter: %s", err)))
  326. return
  327. }
  328. // IdleByNode, if true, computes idle allocations at the node level.
  329. // Otherwise it is computed at the cluster level. (Not relevant if idle
  330. // is not included.)
  331. idleByNode := qp.GetBool("idleByNode", false)
  332. sharedLoadBalancer := qp.GetBool("sharelb", false)
  333. // IncludeProportionalAssetResourceCosts, if true,
  334. includeProportionalAssetResourceCosts := qp.GetBool("includeProportionalAssetResourceCosts", false)
  335. // include aggregated labels/annotations if true
  336. includeAggregatedMetadata := qp.GetBool("includeAggregatedMetadata", false)
  337. shareIdle := qp.GetBool("shareIdle", false)
  338. // Get allocation filter if provided
  339. allocationFilter := qp.Get("filter", "")
  340. // Query allocations with filtering, aggregation, and accumulation.
  341. // Filtering is done BEFORE aggregation inside QueryAllocation to ensure
  342. // filters can match on all allocation properties (like cluster, node, etc.)
  343. // before they are potentially lost or merged during aggregation.
  344. asr, err := a.Model.QueryAllocation(window, step, aggregateBy, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, accumulateBy, shareIdle, allocationFilter)
  345. if err != nil {
  346. if strings.Contains(strings.ToLower(err.Error()), "bad request") {
  347. proto.WriteError(w, proto.BadRequest(err.Error()))
  348. } else {
  349. proto.WriteError(w, proto.InternalServerError(err.Error()))
  350. }
  351. return
  352. }
  353. WriteData(w, asr, nil)
  354. }