aggregation.go 11 KB

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