aggregation.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package costmodel
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/julienschmidt/httprouter"
  7. "github.com/opencost/opencost/core/pkg/filter/allocation"
  8. "github.com/opencost/opencost/core/pkg/log"
  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 (a *Accesses) ComputeAllocationHandlerSummary(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  55. w.Header().Set("Content-Type", "application/json")
  56. qp := httputil.NewQueryParams(r.URL.Query())
  57. // Window is a required field describing the window of time over which to
  58. // compute allocation data.
  59. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  60. if err != nil {
  61. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  62. }
  63. // Step is an optional parameter that defines the duration per-set, i.e.
  64. // the window for an AllocationSet, of the AllocationSetRange to be
  65. // computed. Defaults to the window size, making one set.
  66. step := qp.GetDuration("step", window.Duration())
  67. // Aggregation is a required comma-separated list of fields by which to
  68. // aggregate results. Some fields allow a sub-field, which is distinguished
  69. // with a colon; e.g. "label:app".
  70. // Examples: "namespace", "namespace,label:app"
  71. aggregations := qp.GetList("aggregate", ",")
  72. aggregateBy, err := ParseAggregationProperties(aggregations)
  73. if err != nil {
  74. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  75. }
  76. // Accumulate is an optional parameter, defaulting to false, which if true
  77. // sums each Set in the Range, producing one Set.
  78. accumulate := qp.GetBool("accumulate", false)
  79. // Get allocation filter if provided
  80. allocationFilter := qp.Get("filter", "")
  81. // Query for AllocationSets in increments of the given step duration,
  82. // appending each to the AllocationSetRange.
  83. asr := opencost.NewAllocationSetRange()
  84. stepStart := *window.Start()
  85. for window.End().After(stepStart) {
  86. stepEnd := stepStart.Add(step)
  87. stepWindow := opencost.NewWindow(&stepStart, &stepEnd)
  88. as, err := a.Model.ComputeAllocation(*stepWindow.Start(), *stepWindow.End())
  89. if err != nil {
  90. proto.WriteError(w, proto.InternalServerError(err.Error()))
  91. return
  92. }
  93. asr.Append(as)
  94. stepStart = stepEnd
  95. }
  96. // Apply allocation filter if provided
  97. if allocationFilter != "" {
  98. parser := allocation.NewAllocationFilterParser()
  99. filterNode, err := parser.Parse(allocationFilter)
  100. if err != nil {
  101. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid filter: %s", err)))
  102. return
  103. }
  104. compiler := opencost.NewAllocationMatchCompiler(nil)
  105. matcher, err := compiler.Compile(filterNode)
  106. if err != nil {
  107. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Failed to compile filter: %s", err)))
  108. return
  109. }
  110. filteredASR := opencost.NewAllocationSetRange()
  111. for _, as := range asr.Slice() {
  112. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  113. for _, alloc := range as.Allocations {
  114. if matcher.Matches(alloc) {
  115. filteredAS.Set(alloc)
  116. }
  117. }
  118. if filteredAS.Length() > 0 {
  119. filteredASR.Append(filteredAS)
  120. }
  121. }
  122. asr = filteredASR
  123. }
  124. // Aggregate, if requested
  125. if len(aggregateBy) > 0 {
  126. err = asr.AggregateBy(aggregateBy, nil)
  127. if err != nil {
  128. proto.WriteError(w, proto.InternalServerError(err.Error()))
  129. return
  130. }
  131. }
  132. // Accumulate, if requested
  133. if accumulate {
  134. asr, err = asr.Accumulate(opencost.AccumulateOptionAll)
  135. if err != nil {
  136. proto.WriteError(w, proto.InternalServerError(err.Error()))
  137. return
  138. }
  139. }
  140. // Convert the underlying AllocationSetRange *before* building the
  141. // summary so we don't pay for two summary constructions on non-USD
  142. // requests. The helper returns a non-nil error only on the upfront
  143. // rate-lookup failure, which happens before any mutation, so on
  144. // error we proceed with untouched USD data.
  145. currency := strings.ToUpper(strings.TrimSpace(qp.Get("currency", "USD")))
  146. if currency != "USD" && a.CurrencyConverter != nil {
  147. if err = ConvertAllocationSetRange(asr, a.CurrencyConverter, currency); err != nil {
  148. log.Warnf("Currency conversion failed for currency %s: %v", currency, err)
  149. }
  150. }
  151. sasl := []*opencost.SummaryAllocationSet{}
  152. for _, as := range asr.Slice() {
  153. sas := opencost.NewSummaryAllocationSet(as, nil, nil, false, false)
  154. sasl = append(sasl, sas)
  155. }
  156. sasr := opencost.NewSummaryAllocationSetRange(sasl...)
  157. WriteData(w, sasr, nil)
  158. }
  159. // ComputeAllocationHandler computes an AllocationSetRange from the CostModel.
  160. func (a *Accesses) ComputeAllocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  161. w.Header().Set("Content-Type", "application/json")
  162. qp := httputil.NewQueryParams(r.URL.Query())
  163. // Window is a required field describing the window of time over which to
  164. // compute allocation data.
  165. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  166. if err != nil {
  167. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  168. }
  169. // Step is an optional parameter that defines the duration per-set, i.e.
  170. // the window for an AllocationSet, of the AllocationSetRange to be
  171. // computed. Defaults to the window size, making one set.
  172. step := qp.GetDuration("step", window.Duration())
  173. // Aggregation is an optional comma-separated list of fields by which to
  174. // aggregate results. Some fields allow a sub-field, which is distinguished
  175. // with a colon; e.g. "label:app".
  176. // Examples: "namespace", "namespace,label:app"
  177. aggregations := qp.GetList("aggregate", ",")
  178. aggregateBy, err := ParseAggregationProperties(aggregations)
  179. if err != nil {
  180. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  181. }
  182. // IncludeIdle, if true, uses Asset data to incorporate Idle Allocation
  183. includeIdle := qp.GetBool("includeIdle", false)
  184. // Accumulate is an optional parameter, defaulting to false, which if true
  185. // sums each Set in the Range, producing one Set.
  186. accumulate := qp.GetBool("accumulate", false)
  187. // Accumulate is an optional parameter that accumulates an AllocationSetRange
  188. // by the resolution of the given time duration.
  189. // Defaults to 0. If a value is not passed then the parameter is not used.
  190. accumulateBy := opencost.AccumulateOption(qp.Get("accumulateBy", ""))
  191. // if accumulateBy is not explicitly set, and accumulate is true, ensure result is accumulated
  192. if accumulateBy == opencost.AccumulateOptionNone && accumulate {
  193. accumulateBy = opencost.AccumulateOptionAll
  194. }
  195. // IdleByNode, if true, computes idle allocations at the node level.
  196. // Otherwise it is computed at the cluster level. (Not relevant if idle
  197. // is not included.)
  198. idleByNode := qp.GetBool("idleByNode", false)
  199. sharedLoadBalancer := qp.GetBool("sharelb", false)
  200. // IncludeProportionalAssetResourceCosts, if true,
  201. includeProportionalAssetResourceCosts := qp.GetBool("includeProportionalAssetResourceCosts", false)
  202. // include aggregated labels/annotations if true
  203. includeAggregatedMetadata := qp.GetBool("includeAggregatedMetadata", false)
  204. shareIdle := qp.GetBool("shareIdle", false)
  205. // Get allocation filter if provided
  206. allocationFilter := qp.Get("filter", "")
  207. // Query allocations with filtering, aggregation, and accumulation.
  208. // Filtering is done BEFORE aggregation inside QueryAllocation to ensure
  209. // filters can match on all allocation properties (like cluster, node, etc.)
  210. // before they are potentially lost or merged during aggregation.
  211. asr, err := a.Model.QueryAllocation(window, step, aggregateBy, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, accumulateBy, shareIdle, allocationFilter)
  212. if err != nil {
  213. if strings.Contains(strings.ToLower(err.Error()), "bad request") {
  214. proto.WriteError(w, proto.BadRequest(err.Error()))
  215. } else {
  216. proto.WriteError(w, proto.InternalServerError(err.Error()))
  217. }
  218. return
  219. }
  220. // Extract currency parameter and convert if needed
  221. currency := strings.ToUpper(strings.TrimSpace(qp.Get("currency", "USD")))
  222. if currency != "USD" && a.CurrencyConverter != nil {
  223. err = ConvertAllocationSetRange(asr, a.CurrencyConverter, currency)
  224. if err != nil {
  225. log.Warnf("Currency conversion failed for currency %s: %v", currency, err)
  226. // Continue with USD values if conversion fails
  227. }
  228. }
  229. WriteData(w, asr, nil)
  230. }