cloudcostprops.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package opencost
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "hash/fnv"
  6. "sort"
  7. "strings"
  8. "github.com/opencost/opencost/core/pkg/log"
  9. "golang.org/x/exp/maps"
  10. )
  11. type CloudCostProperty string
  12. // IsLabel returns true if the allocation property has a label prefix
  13. func (apt *CloudCostProperty) IsLabel() bool {
  14. return strings.HasPrefix(string(*apt), "label:")
  15. }
  16. // GetLabel returns the label string associated with the label property if it exists.
  17. // Otherwise, empty string is returned.
  18. func (apt *CloudCostProperty) GetLabel() string {
  19. if apt.IsLabel() {
  20. return strings.TrimSpace(strings.TrimPrefix(string(*apt), "label:"))
  21. }
  22. return ""
  23. }
  24. const (
  25. CloudCostInvoiceEntityIDProp string = "invoiceEntityID"
  26. CloudCostInvoiceEntityNameProp string = "invoiceEntityName"
  27. CloudCostAccountIDProp string = "accountID"
  28. CloudCostAccountNameProp string = "accountName"
  29. CloudCostRegionIDProp string = "regionID"
  30. CloudCostAvailabilityZoneProp string = "availabilityZone"
  31. CloudCostProviderProp string = "provider"
  32. CloudCostProviderIDProp string = "providerID"
  33. CloudCostCategoryProp string = "category"
  34. CloudCostServiceProp string = "service"
  35. CloudCostLabelProp string = "label"
  36. CloudCostLabelSetProp string = "labelSet"
  37. )
  38. func ParseCloudProperties(props []string) ([]CloudCostProperty, error) {
  39. properties := []CloudCostProperty{}
  40. added := make(map[CloudCostProperty]struct{})
  41. for _, prop := range props {
  42. property, err := ParseCloudCostProperty(prop)
  43. if err != nil {
  44. return nil, fmt.Errorf("Failed to parse property: %w", err)
  45. }
  46. if _, ok := added[property]; !ok {
  47. added[property] = struct{}{}
  48. properties = append(properties, property)
  49. }
  50. }
  51. return properties, nil
  52. }
  53. func ParseCloudCostProperty(text string) (CloudCostProperty, error) {
  54. switch strings.TrimSpace(strings.ToLower(text)) {
  55. case "invoiceentityid":
  56. return CloudCostProperty(CloudCostInvoiceEntityIDProp), nil
  57. case "invoiceentityname":
  58. return CloudCostProperty(CloudCostInvoiceEntityNameProp), nil
  59. case "accountid":
  60. return CloudCostProperty(CloudCostAccountIDProp), nil
  61. case "accountname":
  62. return CloudCostProperty(CloudCostAccountNameProp), nil
  63. case "regionid":
  64. return CloudCostProperty(CloudCostRegionIDProp), nil
  65. case "availabilityzone":
  66. return CloudCostProperty(CloudCostAvailabilityZoneProp), nil
  67. case "provider":
  68. return CloudCostProperty(CloudCostProviderProp), nil
  69. case "providerid":
  70. return CloudCostProperty(CloudCostProviderIDProp), nil
  71. case "category":
  72. return CloudCostProperty(CloudCostCategoryProp), nil
  73. case "service":
  74. return CloudCostProperty(CloudCostServiceProp), nil
  75. }
  76. if strings.HasPrefix(text, "label:") {
  77. label := strings.TrimSpace(strings.TrimPrefix(text, "label:"))
  78. return CloudCostProperty(fmt.Sprintf("label:%s", label)), nil
  79. }
  80. return "", fmt.Errorf("invalid cloud cost property: %s", text)
  81. }
  82. const (
  83. // CloudCostClusterManagementCategory describes CloudCost representing Hosted Kubernetes Fees
  84. CloudCostClusterManagementCategory string = "Cluster Management"
  85. // CloudCostDiskCategory describes CloudCost representing Disk usage
  86. CloudCostDiskCategory string = "Disk"
  87. // CloudCostLoadBalancerCategory describes CloudCost representing Load Balancer usage
  88. CloudCostLoadBalancerCategory string = "Load Balancer"
  89. // CloudCostNetworkCategory describes CloudCost representing Network usage
  90. CloudCostNetworkCategory string = "Network"
  91. // CloudCostVirtualMachineCategory describes CloudCost representing VM usage
  92. CloudCostVirtualMachineCategory string = "Virtual Machine"
  93. // CloudCostOtherCategory describes CloudCost that do not belong to a defined category
  94. CloudCostOtherCategory string = "Other"
  95. )
  96. type CloudCostLabels map[string]string
  97. func (ccl CloudCostLabels) Clone() CloudCostLabels {
  98. result := make(map[string]string, len(ccl))
  99. for k, v := range ccl {
  100. result[k] = v
  101. }
  102. return result
  103. }
  104. func (ccl CloudCostLabels) Equal(that CloudCostLabels) bool {
  105. if len(ccl) != len(that) {
  106. return false
  107. }
  108. // Maps are of equal length, so if all keys are in both maps, we don't
  109. // have to check the keys of the other map.
  110. for k, val := range ccl {
  111. if thatVal, ok := that[k]; !ok || val != thatVal {
  112. return false
  113. }
  114. }
  115. return true
  116. }
  117. // Intersection returns the set of labels that have the same key and value in the receiver and arg
  118. func (ccl CloudCostLabels) Intersection(that CloudCostLabels) CloudCostLabels {
  119. intersection := make(map[string]string)
  120. if len(ccl) == 0 || len(that) == 0 {
  121. return intersection
  122. }
  123. // Pick the smaller of the two label sets
  124. smallerLabels := ccl
  125. largerLabels := that
  126. if len(ccl) > len(that) {
  127. smallerLabels = that
  128. largerLabels = ccl
  129. }
  130. // Loop through the smaller label set
  131. for k, sVal := range smallerLabels {
  132. if lVal, ok := largerLabels[k]; ok && sVal == lVal {
  133. intersection[k] = sVal
  134. }
  135. }
  136. return intersection
  137. }
  138. type CloudCostProperties struct {
  139. ProviderID string `json:"providerID,omitempty"`
  140. Provider string `json:"provider,omitempty"`
  141. AccountID string `json:"accountID,omitempty"`
  142. AccountName string `json:"accountName,omitempty"` // @bingen:field[version=3]
  143. InvoiceEntityID string `json:"invoiceEntityID,omitempty"`
  144. InvoiceEntityName string `json:"invoiceEntityName,omitempty"` // @bingen:field[version=3]
  145. RegionID string `json:"regionID,omitempty"` // @bingen:field[version=3]
  146. AvailabilityZone string `json:"availabilityZone,omitempty"` // @bingen:field[version=3]
  147. Service string `json:"service,omitempty"`
  148. Category string `json:"category,omitempty"`
  149. Labels CloudCostLabels `json:"labels,omitempty"`
  150. }
  151. func (ccp *CloudCostProperties) Equal(that *CloudCostProperties) bool {
  152. return ccp.ProviderID == that.ProviderID &&
  153. ccp.Provider == that.Provider &&
  154. ccp.AccountID == that.AccountID &&
  155. ccp.AccountName == that.AccountName &&
  156. ccp.InvoiceEntityID == that.InvoiceEntityID &&
  157. ccp.InvoiceEntityName == that.InvoiceEntityName &&
  158. ccp.RegionID == that.RegionID &&
  159. ccp.AvailabilityZone == that.AvailabilityZone &&
  160. ccp.Service == that.Service &&
  161. ccp.Category == that.Category &&
  162. ccp.Labels.Equal(that.Labels)
  163. }
  164. func (ccp *CloudCostProperties) Clone() *CloudCostProperties {
  165. return &CloudCostProperties{
  166. ProviderID: ccp.ProviderID,
  167. Provider: ccp.Provider,
  168. AccountID: ccp.AccountID,
  169. AccountName: ccp.AccountName,
  170. InvoiceEntityID: ccp.InvoiceEntityID,
  171. InvoiceEntityName: ccp.InvoiceEntityName,
  172. RegionID: ccp.RegionID,
  173. AvailabilityZone: ccp.AvailabilityZone,
  174. Service: ccp.Service,
  175. Category: ccp.Category,
  176. Labels: ccp.Labels.Clone(),
  177. }
  178. }
  179. // Intersection ensure the values of two CloudCostAggregateProperties are maintain only if they are equal
  180. func (ccp *CloudCostProperties) Intersection(that *CloudCostProperties) *CloudCostProperties {
  181. if ccp == nil || that == nil {
  182. return nil
  183. }
  184. if ccp.Equal(that) {
  185. return ccp
  186. }
  187. intersectionCCP := &CloudCostProperties{}
  188. if ccp.Equal(intersectionCCP) || that.Equal(intersectionCCP) {
  189. return intersectionCCP
  190. }
  191. if ccp.Provider == that.Provider {
  192. intersectionCCP.Provider = ccp.Provider
  193. }
  194. if ccp.ProviderID == that.ProviderID {
  195. intersectionCCP.ProviderID = ccp.ProviderID
  196. }
  197. if ccp.AccountID == that.AccountID {
  198. intersectionCCP.AccountID = ccp.AccountID
  199. }
  200. if ccp.AccountName == that.AccountName {
  201. intersectionCCP.AccountName = ccp.AccountName
  202. }
  203. if ccp.InvoiceEntityID == that.InvoiceEntityID {
  204. intersectionCCP.InvoiceEntityID = ccp.InvoiceEntityID
  205. }
  206. if ccp.InvoiceEntityName == that.InvoiceEntityName {
  207. intersectionCCP.InvoiceEntityName = ccp.InvoiceEntityName
  208. }
  209. if ccp.RegionID == that.RegionID {
  210. intersectionCCP.RegionID = ccp.RegionID
  211. }
  212. if ccp.AvailabilityZone == that.AvailabilityZone {
  213. intersectionCCP.AvailabilityZone = ccp.AvailabilityZone
  214. }
  215. if ccp.Service == that.Service {
  216. intersectionCCP.Service = ccp.Service
  217. }
  218. if ccp.Category == that.Category {
  219. intersectionCCP.Category = ccp.Category
  220. }
  221. intersectionCCP.Labels = ccp.Labels.Intersection(that.Labels)
  222. return intersectionCCP
  223. }
  224. // GenerateKey takes a list of properties and creates a "/" seperated key based on the values of the requested properties.
  225. // Invalid values are ignored with a warning. A nil input returns the default key, while an empty slice returns the empty string
  226. func (ccp *CloudCostProperties) GenerateKey(props []string) string {
  227. // nil props replaced with default property list
  228. if props == nil {
  229. return ccp.hashKey()
  230. }
  231. values := make([]string, len(props))
  232. for i, prop := range props {
  233. propVal := UnallocatedSuffix
  234. switch true {
  235. case prop == CloudCostProviderProp:
  236. if ccp.Provider != "" {
  237. propVal = ccp.Provider
  238. }
  239. case prop == CloudCostProviderIDProp:
  240. if ccp.ProviderID != "" {
  241. propVal = ccp.ProviderID
  242. }
  243. case prop == CloudCostCategoryProp:
  244. if ccp.Category != "" {
  245. propVal = ccp.Category
  246. }
  247. case prop == CloudCostInvoiceEntityIDProp:
  248. if ccp.InvoiceEntityID != "" {
  249. propVal = ccp.InvoiceEntityID
  250. }
  251. case prop == CloudCostInvoiceEntityNameProp:
  252. if ccp.InvoiceEntityName != "" {
  253. propVal = ccp.InvoiceEntityName
  254. }
  255. case prop == CloudCostAccountIDProp:
  256. if ccp.AccountID != "" {
  257. propVal = ccp.AccountID
  258. }
  259. case prop == CloudCostAccountNameProp:
  260. if ccp.AccountName != "" {
  261. propVal = ccp.AccountName
  262. }
  263. case prop == CloudCostRegionIDProp:
  264. if ccp.RegionID != "" {
  265. propVal = ccp.RegionID
  266. }
  267. case prop == CloudCostAvailabilityZoneProp:
  268. if ccp.AvailabilityZone != "" {
  269. propVal = ccp.AvailabilityZone
  270. }
  271. case prop == CloudCostServiceProp:
  272. if ccp.Service != "" {
  273. propVal = ccp.Service
  274. }
  275. case strings.HasPrefix(prop, "label:"):
  276. labels := ccp.Labels
  277. if labels != nil {
  278. labelName := strings.TrimPrefix(prop, "label:")
  279. if labelValue, ok := labels[labelName]; ok && labelValue != "" {
  280. propVal = labelValue
  281. }
  282. }
  283. default:
  284. // This case should never be reached, as input up until this point
  285. // should be checked and rejected if invalid. But if we do get a
  286. // value we don't recognize, log a warning.
  287. log.Warnf("CloudCost: GenerateKey: illegal aggregation parameter: %s", prop)
  288. }
  289. values[i] = propVal
  290. }
  291. return strings.Join(values, "/")
  292. }
  293. // HashKey creates a key on the entire property set including labels of a uniform length.
  294. // This key is meant to be used when constructing unaggregated CloudCostSet for storage.
  295. // Including labels prevents CloudCosts that are missing providerIDs from having their labels
  296. // erased as they are saved to cloud cost set.
  297. func (ccp *CloudCostProperties) hashKey() string {
  298. builder := strings.Builder{}
  299. builder.WriteString(ccp.ProviderID)
  300. builder.WriteString(ccp.Provider)
  301. builder.WriteString(ccp.AccountID)
  302. builder.WriteString(ccp.AccountName)
  303. builder.WriteString(ccp.InvoiceEntityID)
  304. builder.WriteString(ccp.InvoiceEntityName)
  305. builder.WriteString(ccp.RegionID)
  306. builder.WriteString(ccp.AvailabilityZone)
  307. builder.WriteString(ccp.Service)
  308. builder.WriteString(ccp.Category)
  309. // Sort label keys before adding key/value pairs to the hash string to ensure label set is
  310. // always returns the same key
  311. labelKeys := maps.Keys(ccp.Labels)
  312. sort.Strings(labelKeys)
  313. for _, k := range labelKeys {
  314. builder.WriteString(k)
  315. builder.WriteString(ccp.Labels[k])
  316. }
  317. hasher := fnv.New64a()
  318. hasher.Write([]byte(builder.String()))
  319. return hex.EncodeToString(hasher.Sum(nil))
  320. }