aggregation.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package costmodel
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "github.com/julienschmidt/httprouter"
  7. "github.com/opencost/opencost/core/pkg/opencost"
  8. "github.com/opencost/opencost/core/pkg/util/httputil"
  9. "github.com/opencost/opencost/core/pkg/util/json"
  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. // 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(), resolution)
  89. if err != nil {
  90. WriteError(w, InternalServerError(err.Error()))
  91. return
  92. }
  93. asr.Append(as)
  94. stepStart = stepEnd
  95. }
  96. // Aggregate, if requested
  97. if len(aggregateBy) > 0 {
  98. err = asr.AggregateBy(aggregateBy, nil)
  99. if err != nil {
  100. WriteError(w, InternalServerError(err.Error()))
  101. return
  102. }
  103. }
  104. // Accumulate, if requested
  105. if accumulate {
  106. asr, err = asr.Accumulate(opencost.AccumulateOptionAll)
  107. if err != nil {
  108. WriteError(w, InternalServerError(err.Error()))
  109. return
  110. }
  111. }
  112. sasl := []*opencost.SummaryAllocationSet{}
  113. for _, as := range asr.Slice() {
  114. sas := opencost.NewSummaryAllocationSet(as, nil, nil, false, false)
  115. sasl = append(sasl, sas)
  116. }
  117. sasr := opencost.NewSummaryAllocationSetRange(sasl...)
  118. w.Write(WrapData(sasr, nil))
  119. }
  120. // ComputeAllocationHandler computes an AllocationSetRange from the CostModel.
  121. func (a *Accesses) ComputeAllocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  122. w.Header().Set("Content-Type", "application/json")
  123. qp := httputil.NewQueryParams(r.URL.Query())
  124. // Window is a required field describing the window of time over which to
  125. // compute allocation data.
  126. window, err := opencost.ParseWindowWithOffset(qp.Get("window", ""), env.GetParsedUTCOffset())
  127. if err != nil {
  128. http.Error(w, fmt.Sprintf("Invalid 'window' parameter: %s", err), http.StatusBadRequest)
  129. }
  130. // Resolution is an optional parameter, defaulting to the configured ETL
  131. // resolution.
  132. resolution := qp.GetDuration("resolution", env.GetETLResolution())
  133. // Step is an optional parameter that defines the duration per-set, i.e.
  134. // the window for an AllocationSet, of the AllocationSetRange to be
  135. // computed. Defaults to the window size, making one set.
  136. step := qp.GetDuration("step", window.Duration())
  137. // Aggregation is an optional comma-separated list of fields by which to
  138. // aggregate results. Some fields allow a sub-field, which is distinguished
  139. // with a colon; e.g. "label:app".
  140. // Examples: "namespace", "namespace,label:app"
  141. aggregations := qp.GetList("aggregate", ",")
  142. aggregateBy, err := ParseAggregationProperties(aggregations)
  143. if err != nil {
  144. http.Error(w, fmt.Sprintf("Invalid 'aggregate' parameter: %s", err), http.StatusBadRequest)
  145. }
  146. // IncludeIdle, if true, uses Asset data to incorporate Idle Allocation
  147. includeIdle := qp.GetBool("includeIdle", false)
  148. // Accumulate is an optional parameter, defaulting to false, which if true
  149. // sums each Set in the Range, producing one Set.
  150. accumulate := qp.GetBool("accumulate", false)
  151. // Accumulate is an optional parameter that accumulates an AllocationSetRange
  152. // by the resolution of the given time duration.
  153. // Defaults to 0. If a value is not passed then the parameter is not used.
  154. accumulateBy := opencost.AccumulateOption(qp.Get("accumulateBy", ""))
  155. // if accumulateBy is not explicitly set, and accumulate is true, ensure result is accumulated
  156. if accumulateBy == opencost.AccumulateOptionNone && accumulate {
  157. accumulateBy = opencost.AccumulateOptionAll
  158. }
  159. // IdleByNode, if true, computes idle allocations at the node level.
  160. // Otherwise it is computed at the cluster level. (Not relevant if idle
  161. // is not included.)
  162. idleByNode := qp.GetBool("idleByNode", false)
  163. sharedLoadBalancer := qp.GetBool("sharelb", false)
  164. // IncludeProportionalAssetResourceCosts, if true,
  165. includeProportionalAssetResourceCosts := qp.GetBool("includeProportionalAssetResourceCosts", false)
  166. // include aggregated labels/annotations if true
  167. includeAggregatedMetadata := qp.GetBool("includeAggregatedMetadata", false)
  168. shareIdle := qp.GetBool("shareIdle", false)
  169. asr, err := a.Model.QueryAllocation(window, resolution, step, aggregateBy, includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, accumulateBy, shareIdle)
  170. if err != nil {
  171. if strings.Contains(strings.ToLower(err.Error()), "bad request") {
  172. WriteError(w, BadRequest(err.Error()))
  173. } else {
  174. WriteError(w, InternalServerError(err.Error()))
  175. }
  176. return
  177. }
  178. w.Write(WrapData(asr, nil))
  179. }
  180. // The below was transferred from a different package in order to maintain
  181. // previous behavior. Ultimately, we should clean this up at some point.
  182. // TODO move to util and/or standardize everything
  183. type Error struct {
  184. StatusCode int
  185. Body string
  186. }
  187. func WriteError(w http.ResponseWriter, err Error) {
  188. status := err.StatusCode
  189. if status == 0 {
  190. status = http.StatusInternalServerError
  191. }
  192. w.WriteHeader(status)
  193. resp, _ := json.Marshal(&Response{
  194. Code: status,
  195. Message: fmt.Sprintf("Error: %s", err.Body),
  196. })
  197. w.Write(resp)
  198. }
  199. func BadRequest(message string) Error {
  200. return Error{
  201. StatusCode: http.StatusBadRequest,
  202. Body: message,
  203. }
  204. }
  205. func InternalServerError(message string) Error {
  206. if message == "" {
  207. message = "Internal Server Error"
  208. }
  209. return Error{
  210. StatusCode: http.StatusInternalServerError,
  211. Body: message,
  212. }
  213. }
  214. func NotFound() Error {
  215. return Error{
  216. StatusCode: http.StatusNotFound,
  217. Body: "Not Found",
  218. }
  219. }