aggregation.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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/opencost"
  9. "github.com/opencost/opencost/core/pkg/util/httputil"
  10. "github.com/opencost/opencost/pkg/env"
  11. )
  12. const (
  13. // SplitTypeWeighted signals that shared costs should be shared
  14. // proportionally, rather than evenly
  15. SplitTypeWeighted = "weighted"
  16. // UnallocatedSubfield indicates an allocation datum that does not have the
  17. // chosen Aggregator; e.g. during aggregation by some label, there may be
  18. // cost data that do not have the given label.
  19. UnallocatedSubfield = "__unallocated__"
  20. )
  21. // ParseAggregationProperties attempts to parse and return aggregation properties
  22. // encoded under the given key. If none exist, or if parsing fails, an error
  23. // is returned with empty AllocationProperties.
  24. func ParseAggregationProperties(aggregations []string) ([]string, error) {
  25. aggregateBy := []string{}
  26. // In case of no aggregation option, aggregate to the container, with a key Cluster/Node/Namespace/Pod/Container
  27. if len(aggregations) == 0 {
  28. aggregateBy = []string{
  29. opencost.AllocationClusterProp,
  30. opencost.AllocationNodeProp,
  31. opencost.AllocationNamespaceProp,
  32. opencost.AllocationPodProp,
  33. opencost.AllocationContainerProp,
  34. }
  35. } else if len(aggregations) == 1 && aggregations[0] == "all" {
  36. aggregateBy = []string{}
  37. } else {
  38. for _, agg := range aggregations {
  39. aggregate := strings.TrimSpace(agg)
  40. if aggregate != "" {
  41. if prop, err := opencost.ParseProperty(aggregate); err == nil {
  42. aggregateBy = append(aggregateBy, string(prop))
  43. } else if strings.HasPrefix(aggregate, "label:") {
  44. aggregateBy = append(aggregateBy, aggregate)
  45. } else if strings.HasPrefix(aggregate, "annotation:") {
  46. aggregateBy = append(aggregateBy, aggregate)
  47. }
  48. }
  49. }
  50. }
  51. return aggregateBy, nil
  52. }
  53. func (a *Accesses) ComputeAllocationHandlerSummary(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  54. w.Header().Set("Content-Type", "application/json")
  55. qp := httputil.NewQueryParams(r.URL.Query())
  56. // Window is a required field describing the window of time over which to
  57. // compute allocation data.
  58. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  59. if err != nil {
  60. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  61. }
  62. // Step is an optional parameter that defines the duration per-set, i.e.
  63. // the window for an AllocationSet, of the AllocationSetRange to be
  64. // computed. Defaults to the window size, making one set.
  65. step := qp.GetDuration("step", window.Duration())
  66. // Resolution is an optional parameter, defaulting to the configured ETL
  67. // resolution.
  68. resolution := qp.GetDuration("resolution", env.GetETLResolution())
  69. // Aggregation is a required comma-separated list of fields by which to
  70. // aggregate results. Some fields allow a sub-field, which is distinguished
  71. // with a colon; e.g. "label:app".
  72. // Examples: "namespace", "namespace,label:app"
  73. aggregations := qp.GetList("aggregate", ",")
  74. aggregateBy, err := ParseAggregationProperties(aggregations)
  75. if err != nil {
  76. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  77. }
  78. // Accumulate is an optional parameter, defaulting to false, which if true
  79. // sums each Set in the Range, producing one Set.
  80. accumulate := qp.GetBool("accumulate", false)
  81. // Get allocation filter if provided
  82. allocationFilter := qp.Get("filter", "")
  83. // Query for AllocationSets in increments of the given step duration,
  84. // appending each to the AllocationSetRange.
  85. asr := opencost.NewAllocationSetRange()
  86. stepStart := *window.Start()
  87. for window.End().After(stepStart) {
  88. stepEnd := stepStart.Add(step)
  89. stepWindow := opencost.NewWindow(&stepStart, &stepEnd)
  90. as, err := a.Model.ComputeAllocation(*stepWindow.Start(), *stepWindow.End(), resolution)
  91. if err != nil {
  92. proto.WriteError(w, proto.InternalServerError(err.Error()))
  93. return
  94. }
  95. asr.Append(as)
  96. stepStart = stepEnd
  97. }
  98. // Apply allocation filter if provided
  99. if allocationFilter != "" {
  100. parser := allocation.NewAllocationFilterParser()
  101. filterNode, err := parser.Parse(allocationFilter)
  102. if err != nil {
  103. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid filter: %s", err)))
  104. return
  105. }
  106. compiler := opencost.NewAllocationMatchCompiler(nil)
  107. matcher, err := compiler.Compile(filterNode)
  108. if err != nil {
  109. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Failed to compile filter: %s", err)))
  110. return
  111. }
  112. filteredASR := opencost.NewAllocationSetRange()
  113. for _, as := range asr.Slice() {
  114. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  115. for _, alloc := range as.Allocations {
  116. if matcher.Matches(alloc) {
  117. filteredAS.Set(alloc)
  118. }
  119. }
  120. if filteredAS.Length() > 0 {
  121. filteredASR.Append(filteredAS)
  122. }
  123. }
  124. asr = filteredASR
  125. }
  126. // Aggregate, if requested
  127. if len(aggregateBy) > 0 {
  128. err = asr.AggregateBy(aggregateBy, nil)
  129. if err != nil {
  130. proto.WriteError(w, proto.InternalServerError(err.Error()))
  131. return
  132. }
  133. }
  134. // Accumulate, if requested
  135. if accumulate {
  136. asr, err = asr.Accumulate(opencost.AccumulateOptionAll)
  137. if err != nil {
  138. proto.WriteError(w, proto.InternalServerError(err.Error()))
  139. return
  140. }
  141. }
  142. sasl := []*opencost.SummaryAllocationSet{}
  143. for _, as := range asr.Slice() {
  144. sas := opencost.NewSummaryAllocationSet(as, nil, nil, false, false)
  145. sasl = append(sasl, sas)
  146. }
  147. sasr := opencost.NewSummaryAllocationSetRange(sasl...)
  148. WriteData(w, sasr, nil)
  149. }
  150. // ComputeAllocationHandler computes an AllocationSetRange from the CostModel.
  151. func (a *Accesses) ComputeAllocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  152. w.Header().Set("Content-Type", "application/json")
  153. qp := httputil.NewQueryParams(r.URL.Query())
  154. // Window is a required field describing the window of time over which to
  155. // compute allocation data.
  156. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  157. if err != nil {
  158. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  159. }
  160. // Resolution is an optional parameter, defaulting to the configured ETL
  161. // resolution.
  162. resolution := qp.GetDuration("resolution", env.GetETLResolution())
  163. // Step is an optional parameter that defines the duration per-set, i.e.
  164. // the window for an AllocationSet, of the AllocationSetRange to be
  165. // computed. Defaults to the window size, making one set.
  166. step := qp.GetDuration("step", window.Duration())
  167. // Aggregation is an optional comma-separated list of fields by which to
  168. // aggregate results. Some fields allow a sub-field, which is distinguished
  169. // with a colon; e.g. "label:app".
  170. // Examples: "namespace", "namespace,label:app"
  171. aggregations := qp.GetList("aggregate", ",")
  172. aggregateBy, err := ParseAggregationProperties(aggregations)
  173. if err != nil {
  174. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  175. }
  176. // IncludeIdle, if true, uses Asset data to incorporate Idle Allocation
  177. includeIdle := qp.GetBool("includeIdle", false)
  178. // Accumulate is an optional parameter, defaulting to false, which if true
  179. // sums each Set in the Range, producing one Set.
  180. accumulate := qp.GetBool("accumulate", false)
  181. // Accumulate is an optional parameter that accumulates an AllocationSetRange
  182. // by the resolution of the given time duration.
  183. // Defaults to 0. If a value is not passed then the parameter is not used.
  184. accumulateBy := opencost.AccumulateOption(qp.Get("accumulateBy", ""))
  185. // if accumulateBy is not explicitly set, and accumulate is true, ensure result is accumulated
  186. if accumulateBy == opencost.AccumulateOptionNone && accumulate {
  187. accumulateBy = opencost.AccumulateOptionAll
  188. }
  189. // IdleByNode, if true, computes idle allocations at the node level.
  190. // Otherwise it is computed at the cluster level. (Not relevant if idle
  191. // is not included.)
  192. idleByNode := qp.GetBool("idleByNode", false)
  193. sharedLoadBalancer := qp.GetBool("sharelb", false)
  194. // IncludeProportionalAssetResourceCosts, if true,
  195. includeProportionalAssetResourceCosts := qp.GetBool("includeProportionalAssetResourceCosts", false)
  196. // include aggregated labels/annotations if true
  197. includeAggregatedMetadata := qp.GetBool("includeAggregatedMetadata", false)
  198. shareIdle := qp.GetBool("shareIdle", false)
  199. // Get allocation filter if provided
  200. allocationFilter := qp.Get("filter", "")
  201. asr, err := a.Model.QueryAllocation(window, resolution, step, aggregateBy, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, accumulateBy, shareIdle)
  202. if err != nil {
  203. if strings.Contains(strings.ToLower(err.Error()), "bad request") {
  204. proto.WriteError(w, proto.BadRequest(err.Error()))
  205. } else {
  206. proto.WriteError(w, proto.InternalServerError(err.Error()))
  207. }
  208. return
  209. }
  210. // Apply allocation filter if provided
  211. if allocationFilter != "" {
  212. parser := allocation.NewAllocationFilterParser()
  213. filterNode, err := parser.Parse(allocationFilter)
  214. if err != nil {
  215. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Invalid filter: %s", err)))
  216. return
  217. }
  218. compiler := opencost.NewAllocationMatchCompiler(nil)
  219. matcher, err := compiler.Compile(filterNode)
  220. if err != nil {
  221. proto.WriteError(w, proto.BadRequest(fmt.Sprintf("Failed to compile filter: %s", err)))
  222. return
  223. }
  224. filteredASR := opencost.NewAllocationSetRange()
  225. for _, as := range asr.Slice() {
  226. filteredAS := opencost.NewAllocationSet(as.Start(), as.End())
  227. for _, alloc := range as.Allocations {
  228. if matcher.Matches(alloc) {
  229. filteredAS.Set(alloc)
  230. }
  231. }
  232. if filteredAS.Length() > 0 {
  233. filteredASR.Append(filteredAS)
  234. }
  235. }
  236. asr = filteredASR
  237. }
  238. WriteData(w, asr, nil)
  239. }