aggregation.go 7.8 KB

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