cloudcostprops.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package opencost
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/opencost/opencost/core/pkg/log"
  6. "github.com/opencost/opencost/core/pkg/util/promutil"
  7. )
  8. type CloudCostProperty string
  9. // IsLabel returns true if the allocation property has a label prefix
  10. func (apt *CloudCostProperty) IsLabel() bool {
  11. return strings.HasPrefix(string(*apt), "label:")
  12. }
  13. // GetLabel returns the label string associated with the label property if it exists.
  14. // Otherwise, empty string is returned.
  15. func (apt *CloudCostProperty) GetLabel() string {
  16. if apt.IsLabel() {
  17. return strings.TrimSpace(strings.TrimPrefix(string(*apt), "label:"))
  18. }
  19. return ""
  20. }
  21. const (
  22. CloudCostInvoiceEntityIDProp string = "invoiceEntityID"
  23. CloudCostAccountIDProp string = "accountID"
  24. CloudCostProviderProp string = "provider"
  25. CloudCostProviderIDProp string = "providerID"
  26. CloudCostCategoryProp string = "category"
  27. CloudCostServiceProp string = "service"
  28. CloudCostLabelProp string = "label"
  29. )
  30. func ParseCloudProperties(props []string) ([]CloudCostProperty, error) {
  31. properties := []CloudCostProperty{}
  32. added := make(map[CloudCostProperty]struct{})
  33. for _, prop := range props {
  34. property, err := ParseCloudCostProperty(prop)
  35. if err != nil {
  36. return nil, fmt.Errorf("Failed to parse property: %w", err)
  37. }
  38. if _, ok := added[property]; !ok {
  39. added[property] = struct{}{}
  40. properties = append(properties, property)
  41. }
  42. }
  43. return properties, nil
  44. }
  45. func ParseCloudCostProperty(text string) (CloudCostProperty, error) {
  46. switch strings.TrimSpace(strings.ToLower(text)) {
  47. case "invoiceentityid":
  48. return CloudCostProperty(CloudCostInvoiceEntityIDProp), nil
  49. case "accountid":
  50. return CloudCostProperty(CloudCostAccountIDProp), nil
  51. case "provider":
  52. return CloudCostProperty(CloudCostProviderProp), nil
  53. case "providerid":
  54. return CloudCostProperty(CloudCostProviderIDProp), nil
  55. case "category":
  56. return CloudCostProperty(CloudCostCategoryProp), nil
  57. case "service":
  58. return CloudCostProperty(CloudCostServiceProp), nil
  59. }
  60. if strings.HasPrefix(text, "label:") {
  61. label := promutil.SanitizeLabelName(strings.TrimSpace(strings.TrimPrefix(text, "label:")))
  62. return CloudCostProperty(fmt.Sprintf("label:%s", label)), nil
  63. }
  64. return "", fmt.Errorf("invalid cloud cost property: %s", text)
  65. }
  66. const (
  67. // CloudCostClusterManagementCategory describes CloudCost representing Hosted Kubernetes Fees
  68. CloudCostClusterManagementCategory string = "Cluster Management"
  69. // CloudCostDiskCategory describes CloudCost representing Disk usage
  70. CloudCostDiskCategory string = "Disk"
  71. // CloudCostLoadBalancerCategory describes CloudCost representing Load Balancer usage
  72. CloudCostLoadBalancerCategory string = "Load Balancer"
  73. // CloudCostNetworkCategory describes CloudCost representing Network usage
  74. CloudCostNetworkCategory string = "Network"
  75. // CloudCostVirtualMachineCategory describes CloudCost representing VM usage
  76. CloudCostVirtualMachineCategory string = "Virtual Machine"
  77. // CloudCostOtherCategory describes CloudCost that do not belong to a defined category
  78. CloudCostOtherCategory string = "Other"
  79. )
  80. type CloudCostLabels map[string]string
  81. func (ccl CloudCostLabels) Clone() CloudCostLabels {
  82. result := make(map[string]string, len(ccl))
  83. for k, v := range ccl {
  84. result[k] = v
  85. }
  86. return result
  87. }
  88. func (ccl CloudCostLabels) Equal(that CloudCostLabels) bool {
  89. if len(ccl) != len(that) {
  90. return false
  91. }
  92. // Maps are of equal length, so if all keys are in both maps, we don't
  93. // have to check the keys of the other map.
  94. for k, val := range ccl {
  95. if thatVal, ok := that[k]; !ok || val != thatVal {
  96. return false
  97. }
  98. }
  99. return true
  100. }
  101. // Intersection returns the set of labels that have the same key and value in the receiver and arg
  102. func (ccl CloudCostLabels) Intersection(that CloudCostLabels) CloudCostLabels {
  103. intersection := make(map[string]string)
  104. if len(ccl) == 0 || len(that) == 0 {
  105. return intersection
  106. }
  107. // Pick the smaller of the two label sets
  108. smallerLabels := ccl
  109. largerLabels := that
  110. if len(ccl) > len(that) {
  111. smallerLabels = that
  112. largerLabels = ccl
  113. }
  114. // Loop through the smaller label set
  115. for k, sVal := range smallerLabels {
  116. if lVal, ok := largerLabels[k]; ok && sVal == lVal {
  117. intersection[k] = sVal
  118. }
  119. }
  120. return intersection
  121. }
  122. type CloudCostProperties struct {
  123. ProviderID string `json:"providerID,omitempty"`
  124. Provider string `json:"provider,omitempty"`
  125. AccountID string `json:"accountID,omitempty"`
  126. InvoiceEntityID string `json:"invoiceEntityID,omitempty"`
  127. Service string `json:"service,omitempty"`
  128. Category string `json:"category,omitempty"`
  129. Labels CloudCostLabels `json:"labels,omitempty"`
  130. }
  131. func (ccp *CloudCostProperties) Equal(that *CloudCostProperties) bool {
  132. return ccp.ProviderID == that.ProviderID &&
  133. ccp.Provider == that.Provider &&
  134. ccp.AccountID == that.AccountID &&
  135. ccp.InvoiceEntityID == that.InvoiceEntityID &&
  136. ccp.Service == that.Service &&
  137. ccp.Category == that.Category &&
  138. ccp.Labels.Equal(that.Labels)
  139. }
  140. func (ccp *CloudCostProperties) Clone() *CloudCostProperties {
  141. return &CloudCostProperties{
  142. ProviderID: ccp.ProviderID,
  143. Provider: ccp.Provider,
  144. AccountID: ccp.AccountID,
  145. InvoiceEntityID: ccp.InvoiceEntityID,
  146. Service: ccp.Service,
  147. Category: ccp.Category,
  148. Labels: ccp.Labels.Clone(),
  149. }
  150. }
  151. // Intersection ensure the values of two CloudCostAggregateProperties are maintain only if they are equal
  152. func (ccp *CloudCostProperties) Intersection(that *CloudCostProperties) *CloudCostProperties {
  153. if ccp == nil || that == nil {
  154. return nil
  155. }
  156. if ccp.Equal(that) {
  157. return ccp
  158. }
  159. intersectionCCP := &CloudCostProperties{}
  160. if ccp.Equal(intersectionCCP) || that.Equal(intersectionCCP) {
  161. return intersectionCCP
  162. }
  163. if ccp.Provider == that.Provider {
  164. intersectionCCP.Provider = ccp.Provider
  165. }
  166. if ccp.ProviderID == that.ProviderID {
  167. intersectionCCP.ProviderID = ccp.ProviderID
  168. }
  169. if ccp.AccountID == that.AccountID {
  170. intersectionCCP.AccountID = ccp.AccountID
  171. }
  172. if ccp.InvoiceEntityID == that.InvoiceEntityID {
  173. intersectionCCP.InvoiceEntityID = ccp.InvoiceEntityID
  174. }
  175. if ccp.Service == that.Service {
  176. intersectionCCP.Service = ccp.Service
  177. }
  178. if ccp.Category == that.Category {
  179. intersectionCCP.Category = ccp.Category
  180. }
  181. intersectionCCP.Labels = ccp.Labels.Intersection(that.Labels)
  182. return intersectionCCP
  183. }
  184. var cloudCostDefaultKeyProperties = []string{
  185. CloudCostProviderProp,
  186. CloudCostInvoiceEntityIDProp,
  187. CloudCostAccountIDProp,
  188. CloudCostCategoryProp,
  189. CloudCostServiceProp,
  190. CloudCostProviderIDProp,
  191. }
  192. // GenerateKey takes a list of properties and creates a "/" seperated key based on the values of the requested properties.
  193. // Invalid values are ignored with a warning. A nil input returns the default key, while an empty slice returns the empty string
  194. func (ccp *CloudCostProperties) GenerateKey(props []string) string {
  195. // nil props replaced with default property list
  196. if props == nil {
  197. props = cloudCostDefaultKeyProperties
  198. }
  199. values := make([]string, len(props))
  200. for i, prop := range props {
  201. propVal := UnallocatedSuffix
  202. switch true {
  203. case prop == CloudCostProviderProp:
  204. if ccp.Provider != "" {
  205. propVal = ccp.Provider
  206. }
  207. case prop == CloudCostProviderIDProp:
  208. if ccp.ProviderID != "" {
  209. propVal = ccp.ProviderID
  210. }
  211. case prop == CloudCostCategoryProp:
  212. if ccp.Category != "" {
  213. propVal = ccp.Category
  214. }
  215. case prop == CloudCostInvoiceEntityIDProp:
  216. if ccp.InvoiceEntityID != "" {
  217. propVal = ccp.InvoiceEntityID
  218. }
  219. case prop == CloudCostAccountIDProp:
  220. if ccp.AccountID != "" {
  221. propVal = ccp.AccountID
  222. }
  223. case prop == CloudCostServiceProp:
  224. if ccp.Service != "" {
  225. propVal = ccp.Service
  226. }
  227. case strings.HasPrefix(prop, "label:"):
  228. labels := ccp.Labels
  229. if labels != nil {
  230. labelName := strings.TrimPrefix(prop, "label:")
  231. if labelValue, ok := labels[labelName]; ok && labelValue != "" {
  232. propVal = labelValue
  233. }
  234. }
  235. default:
  236. // This case should never be reached, as input up until this point
  237. // should be checked and rejected if invalid. But if we do get a
  238. // value we don't recognize, log a warning.
  239. log.Warnf("CloudCost: GenerateKey: illegal aggregation parameter: %s", prop)
  240. }
  241. values[i] = propVal
  242. }
  243. return strings.Join(values, "/")
  244. }