aggregation.go 9.4 KB

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