allocationprops.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. package kubecost
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "github.com/opencost/opencost/pkg/log"
  7. "github.com/opencost/opencost/pkg/prom"
  8. )
  9. const (
  10. AllocationNilProp string = ""
  11. AllocationClusterProp string = "cluster"
  12. AllocationNodeProp string = "node"
  13. AllocationContainerProp string = "container"
  14. AllocationControllerProp string = "controller"
  15. AllocationControllerKindProp string = "controllerKind"
  16. AllocationNamespaceProp string = "namespace"
  17. AllocationPodProp string = "pod"
  18. AllocationProviderIDProp string = "providerID"
  19. AllocationServiceProp string = "service"
  20. AllocationLabelProp string = "label"
  21. AllocationAnnotationProp string = "annotation"
  22. AllocationDeploymentProp string = "deployment"
  23. AllocationStatefulSetProp string = "statefulset"
  24. AllocationDaemonSetProp string = "daemonset"
  25. AllocationJobProp string = "job"
  26. AllocationDepartmentProp string = "department"
  27. AllocationEnvironmentProp string = "environment"
  28. AllocationOwnerProp string = "owner"
  29. AllocationProductProp string = "product"
  30. AllocationTeamProp string = "team"
  31. )
  32. func ParseProperty(text string) (string, error) {
  33. switch strings.TrimSpace(strings.ToLower(text)) {
  34. case "cluster":
  35. return AllocationClusterProp, nil
  36. case "node":
  37. return AllocationNodeProp, nil
  38. case "container":
  39. return AllocationContainerProp, nil
  40. case "controller":
  41. return AllocationControllerProp, nil
  42. case "controllerkind":
  43. return AllocationControllerKindProp, nil
  44. case "namespace":
  45. return AllocationNamespaceProp, nil
  46. case "pod":
  47. return AllocationPodProp, nil
  48. case "providerid":
  49. return AllocationProviderIDProp, nil
  50. case "service":
  51. return AllocationServiceProp, nil
  52. case "label":
  53. return AllocationLabelProp, nil
  54. case "annotation":
  55. return AllocationAnnotationProp, nil
  56. case "deployment":
  57. return AllocationDeploymentProp, nil
  58. case "daemonset":
  59. return AllocationDaemonSetProp, nil
  60. case "statefulset":
  61. return AllocationStatefulSetProp, nil
  62. case "job":
  63. return AllocationJobProp, nil
  64. case "department":
  65. return AllocationDepartmentProp, nil
  66. case "environment":
  67. return AllocationEnvironmentProp, nil
  68. case "owner":
  69. return AllocationOwnerProp, nil
  70. case "product":
  71. return AllocationProductProp, nil
  72. case "team":
  73. return AllocationTeamProp, nil
  74. }
  75. if strings.HasPrefix(text, "label:") {
  76. label := prom.SanitizeLabelName(strings.TrimSpace(strings.TrimPrefix(text, "label:")))
  77. return fmt.Sprintf("label:%s", label), nil
  78. }
  79. if strings.HasPrefix(text, "annotation:") {
  80. annotation := prom.SanitizeLabelName(strings.TrimSpace(strings.TrimPrefix(text, "annotation:")))
  81. return fmt.Sprintf("annotation:%s", annotation), nil
  82. }
  83. return AllocationNilProp, fmt.Errorf("invalid allocation property: %s", text)
  84. }
  85. // AllocationProperties describes a set of Kubernetes objects.
  86. type AllocationProperties struct {
  87. Cluster string `json:"cluster,omitempty"`
  88. Node string `json:"node,omitempty"`
  89. Container string `json:"container,omitempty"`
  90. Controller string `json:"controller,omitempty"`
  91. ControllerKind string `json:"controllerKind,omitempty"`
  92. Namespace string `json:"namespace,omitempty"`
  93. Pod string `json:"pod,omitempty"`
  94. Services []string `json:"services,omitempty"`
  95. ProviderID string `json:"providerID,omitempty"`
  96. Labels AllocationLabels `json:"labels,omitempty"`
  97. Annotations AllocationAnnotations `json:"annotations,omitempty"`
  98. NamespaceLabels AllocationLabels `json:"namespaceLabels,omitempty"` // @bingen:field[version=17]
  99. NamespaceAnnotations AllocationAnnotations `json:"namespaceAnnotations,omitempty"` // @bingen:field[version=17]
  100. // When set to true, maintain the intersection of all labels + annotations
  101. // in the aggregated AllocationProperties object
  102. AggregatedMetadata bool `json:"-"` //@bingen:field[ignore]
  103. }
  104. // AllocationLabels is a schema-free mapping of key/value pairs that can be
  105. // attributed to an Allocation
  106. type AllocationLabels map[string]string
  107. // AllocationAnnotations is a schema-free mapping of key/value pairs that can be
  108. // attributed to an Allocation
  109. type AllocationAnnotations map[string]string
  110. func (p *AllocationProperties) Clone() *AllocationProperties {
  111. if p == nil {
  112. return nil
  113. }
  114. clone := &AllocationProperties{}
  115. clone.Cluster = p.Cluster
  116. clone.Node = p.Node
  117. clone.Container = p.Container
  118. clone.Controller = p.Controller
  119. clone.ControllerKind = p.ControllerKind
  120. clone.Namespace = p.Namespace
  121. clone.Pod = p.Pod
  122. clone.ProviderID = p.ProviderID
  123. var services []string
  124. services = append(services, p.Services...)
  125. clone.Services = services
  126. labels := make(map[string]string, len(p.Labels))
  127. for k, v := range p.Labels {
  128. labels[k] = v
  129. }
  130. clone.Labels = labels
  131. nsLabels := make(map[string]string, len(p.NamespaceLabels))
  132. for k, v := range p.NamespaceLabels {
  133. nsLabels[k] = v
  134. }
  135. clone.NamespaceLabels = nsLabels
  136. annotations := make(map[string]string, len(p.Annotations))
  137. for k, v := range p.Annotations {
  138. annotations[k] = v
  139. }
  140. clone.Annotations = annotations
  141. nsAnnotations := make(map[string]string, len(p.NamespaceAnnotations))
  142. for k, v := range p.NamespaceAnnotations {
  143. nsAnnotations[k] = v
  144. }
  145. clone.NamespaceAnnotations = nsAnnotations
  146. return clone
  147. }
  148. func (p *AllocationProperties) Equal(that *AllocationProperties) bool {
  149. if p == nil || that == nil {
  150. return false
  151. }
  152. if p.Cluster != that.Cluster {
  153. return false
  154. }
  155. if p.Node != that.Node {
  156. return false
  157. }
  158. if p.Container != that.Container {
  159. return false
  160. }
  161. if p.Controller != that.Controller {
  162. return false
  163. }
  164. if p.ControllerKind != that.ControllerKind {
  165. return false
  166. }
  167. if p.Namespace != that.Namespace {
  168. return false
  169. }
  170. if p.Pod != that.Pod {
  171. return false
  172. }
  173. if p.ProviderID != that.ProviderID {
  174. return false
  175. }
  176. pLabels := p.Labels
  177. thatLabels := that.Labels
  178. if len(pLabels) == len(thatLabels) {
  179. for k, pv := range pLabels {
  180. tv, ok := thatLabels[k]
  181. if !ok || tv != pv {
  182. return false
  183. }
  184. }
  185. } else {
  186. return false
  187. }
  188. pNamespaceLabels := p.NamespaceLabels
  189. thatNamespaceLabels := that.NamespaceLabels
  190. if len(pNamespaceLabels) == len(thatNamespaceLabels) {
  191. for k, pv := range pNamespaceLabels {
  192. tv, ok := thatNamespaceLabels[k]
  193. if !ok || tv != pv {
  194. return false
  195. }
  196. }
  197. } else {
  198. return false
  199. }
  200. pAnnotations := p.Annotations
  201. thatAnnotations := that.Annotations
  202. if len(pAnnotations) == len(thatAnnotations) {
  203. for k, pv := range pAnnotations {
  204. tv, ok := thatAnnotations[k]
  205. if !ok || tv != pv {
  206. return false
  207. }
  208. }
  209. } else {
  210. return false
  211. }
  212. pNamespaceAnnotations := p.NamespaceAnnotations
  213. thatNamespaceAnnotations := that.NamespaceAnnotations
  214. if len(pNamespaceAnnotations) == len(thatNamespaceAnnotations) {
  215. for k, pv := range pNamespaceAnnotations {
  216. tv, ok := thatNamespaceAnnotations[k]
  217. if !ok || tv != pv {
  218. return false
  219. }
  220. }
  221. } else {
  222. return false
  223. }
  224. pServices := p.Services
  225. thatServices := that.Services
  226. if len(pServices) == len(thatServices) {
  227. sort.Strings(pServices)
  228. sort.Strings(thatServices)
  229. for i, pv := range pServices {
  230. tv := thatServices[i]
  231. if tv != pv {
  232. return false
  233. }
  234. }
  235. } else {
  236. return false
  237. }
  238. return true
  239. }
  240. // GenerateKey generates a string that represents the key by which the
  241. // AllocationProperties should be aggregated, given the properties defined by
  242. // the aggregateBy parameter and the given label configuration.
  243. func (p *AllocationProperties) GenerateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  244. if p == nil {
  245. return ""
  246. }
  247. if labelConfig == nil {
  248. labelConfig = NewLabelConfig()
  249. }
  250. // Names will ultimately be joined into a single name, which uniquely
  251. // identifies allocations.
  252. names := []string{}
  253. for _, agg := range aggregateBy {
  254. switch true {
  255. case agg == AllocationClusterProp:
  256. names = append(names, p.Cluster)
  257. case agg == AllocationNodeProp:
  258. names = append(names, p.Node)
  259. case agg == AllocationNamespaceProp:
  260. names = append(names, p.Namespace)
  261. case agg == AllocationControllerKindProp:
  262. controllerKind := p.ControllerKind
  263. if controllerKind == "" {
  264. // Indicate that allocation has no controller
  265. controllerKind = UnallocatedSuffix
  266. }
  267. names = append(names, controllerKind)
  268. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  269. controller := p.Controller
  270. if agg != p.ControllerKind || controller == "" {
  271. // The allocation does not have the specified controller kind
  272. controller = UnallocatedSuffix
  273. }
  274. names = append(names, controller)
  275. case agg == AllocationControllerProp:
  276. controller := p.Controller
  277. if controller == "" {
  278. // Indicate that allocation has no controller
  279. controller = UnallocatedSuffix
  280. } else if p.ControllerKind != "" {
  281. controller = fmt.Sprintf("%s:%s", p.ControllerKind, controller)
  282. }
  283. names = append(names, controller)
  284. case agg == AllocationPodProp:
  285. names = append(names, p.Pod)
  286. case agg == AllocationContainerProp:
  287. names = append(names, p.Container)
  288. case agg == AllocationServiceProp:
  289. services := p.Services
  290. if len(services) == 0 {
  291. // Indicate that allocation has no services
  292. names = append(names, UnallocatedSuffix)
  293. } else {
  294. // Unmounted load balancers lead to __unmounted__ Allocations whose
  295. // services field is populated. If we don't have a special case, the
  296. // __unmounted__ Allocation will be transformed into a regular Allocation,
  297. // causing issues with AggregateBy and drilldown
  298. if p.Pod == UnmountedSuffix || p.Namespace == UnmountedSuffix || p.Container == UnmountedSuffix {
  299. names = append(names, UnmountedSuffix)
  300. } else {
  301. // This just uses the first service
  302. for _, service := range services {
  303. names = append(names, service)
  304. break
  305. }
  306. }
  307. }
  308. case strings.HasPrefix(agg, "label:"):
  309. labels := p.Labels
  310. if labels == nil {
  311. names = append(names, UnallocatedSuffix)
  312. } else {
  313. labelName := labelConfig.Sanitize(strings.TrimPrefix(agg, "label:"))
  314. if labelValue, ok := labels[labelName]; ok {
  315. names = append(names, fmt.Sprintf("%s", labelValue))
  316. } else {
  317. names = append(names, UnallocatedSuffix)
  318. }
  319. }
  320. case strings.HasPrefix(agg, "annotation:"):
  321. annotations := p.Annotations
  322. if annotations == nil {
  323. names = append(names, UnallocatedSuffix)
  324. } else {
  325. annotationName := labelConfig.Sanitize(strings.TrimPrefix(agg, "annotation:"))
  326. if annotationValue, ok := annotations[annotationName]; ok {
  327. names = append(names, fmt.Sprintf("%s", annotationValue))
  328. } else {
  329. names = append(names, UnallocatedSuffix)
  330. }
  331. }
  332. case agg == AllocationDepartmentProp:
  333. labels := p.Labels
  334. annotations := p.Annotations
  335. if labels == nil && annotations == nil {
  336. names = append(names, UnallocatedSuffix)
  337. } else {
  338. labelNames := strings.Split(labelConfig.DepartmentLabel, ",")
  339. for _, labelName := range labelNames {
  340. labelName = labelConfig.Sanitize(labelName)
  341. if labelValue, ok := labels[labelName]; ok {
  342. names = append(names, labelValue)
  343. } else if annotationValue, ok := annotations[labelName]; ok {
  344. names = append(names, annotationValue)
  345. } else {
  346. names = append(names, UnallocatedSuffix)
  347. }
  348. }
  349. }
  350. case agg == AllocationEnvironmentProp:
  351. labels := p.Labels
  352. annotations := p.Annotations
  353. if labels == nil && annotations == nil {
  354. names = append(names, UnallocatedSuffix)
  355. } else {
  356. labelNames := strings.Split(labelConfig.EnvironmentLabel, ",")
  357. for _, labelName := range labelNames {
  358. labelName = labelConfig.Sanitize(labelName)
  359. if labelValue, ok := labels[labelName]; ok {
  360. names = append(names, labelValue)
  361. } else if annotationValue, ok := annotations[labelName]; ok {
  362. names = append(names, annotationValue)
  363. } else {
  364. names = append(names, UnallocatedSuffix)
  365. }
  366. }
  367. }
  368. case agg == AllocationOwnerProp:
  369. labels := p.Labels
  370. annotations := p.Annotations
  371. if labels == nil && annotations == nil {
  372. names = append(names, UnallocatedSuffix)
  373. } else {
  374. labelNames := strings.Split(labelConfig.OwnerLabel, ",")
  375. for _, labelName := range labelNames {
  376. labelName = labelConfig.Sanitize(labelName)
  377. if labelValue, ok := labels[labelName]; ok {
  378. names = append(names, labelValue)
  379. } else if annotationValue, ok := annotations[labelName]; ok {
  380. names = append(names, annotationValue)
  381. } else {
  382. names = append(names, UnallocatedSuffix)
  383. }
  384. }
  385. }
  386. case agg == AllocationProductProp:
  387. labels := p.Labels
  388. annotations := p.Annotations
  389. if labels == nil && annotations == nil {
  390. names = append(names, UnallocatedSuffix)
  391. } else {
  392. labelNames := strings.Split(labelConfig.ProductLabel, ",")
  393. for _, labelName := range labelNames {
  394. labelName = labelConfig.Sanitize(labelName)
  395. if labelValue, ok := labels[labelName]; ok {
  396. names = append(names, labelValue)
  397. } else if annotationValue, ok := annotations[labelName]; ok {
  398. names = append(names, annotationValue)
  399. } else {
  400. names = append(names, UnallocatedSuffix)
  401. }
  402. }
  403. }
  404. case agg == AllocationTeamProp:
  405. labels := p.Labels
  406. annotations := p.Annotations
  407. if labels == nil && annotations == nil {
  408. names = append(names, UnallocatedSuffix)
  409. } else {
  410. labelNames := strings.Split(labelConfig.TeamLabel, ",")
  411. for _, labelName := range labelNames {
  412. labelName = labelConfig.Sanitize(labelName)
  413. if labelValue, ok := labels[labelName]; ok {
  414. names = append(names, labelValue)
  415. } else if annotationValue, ok := annotations[labelName]; ok {
  416. names = append(names, annotationValue)
  417. } else {
  418. names = append(names, UnallocatedSuffix)
  419. }
  420. }
  421. }
  422. default:
  423. // This case should never be reached, as input up until this point
  424. // should be checked and rejected if invalid. But if we do get a
  425. // value we don't recognize, log a warning.
  426. log.Warnf("generateKey: illegal aggregation parameter: %s", agg)
  427. }
  428. }
  429. return strings.Join(names, "/")
  430. }
  431. // Intersection returns an *AllocationProperties which contains all matching fields between the calling and parameter AllocationProperties
  432. // nillable slices and maps are left as nil
  433. func (p *AllocationProperties) Intersection(that *AllocationProperties) *AllocationProperties {
  434. if p == nil || that == nil {
  435. return nil
  436. }
  437. intersectionProps := &AllocationProperties{}
  438. if p.Cluster == that.Cluster {
  439. intersectionProps.Cluster = p.Cluster
  440. }
  441. if p.Node == that.Node {
  442. intersectionProps.Node = p.Node
  443. }
  444. if p.Container == that.Container {
  445. intersectionProps.Container = p.Container
  446. }
  447. if p.Controller == that.Controller {
  448. intersectionProps.Controller = p.Controller
  449. }
  450. if p.ControllerKind == that.ControllerKind {
  451. intersectionProps.ControllerKind = p.ControllerKind
  452. }
  453. if p.Namespace == that.Namespace {
  454. intersectionProps.Namespace = p.Namespace
  455. // CORE-140: In the case that the namespace is the same, also copy over the namespaceLabels and annotations
  456. // Note - assume that if the namespace is the same on both, then namespace label/annotation sets
  457. // will be the same, so just carry one set over
  458. if p.Container == UnmountedSuffix {
  459. // This logic is designed to effectively ignore the unmounted/unallocated objects
  460. // and just copy over the labels from the other, 'legitimate' allocation.
  461. intersectionProps.NamespaceLabels = copyStringMap(that.NamespaceLabels)
  462. intersectionProps.NamespaceAnnotations = copyStringMap(that.NamespaceAnnotations)
  463. } else {
  464. intersectionProps.NamespaceLabels = copyStringMap(p.NamespaceLabels)
  465. intersectionProps.NamespaceAnnotations = copyStringMap(p.NamespaceAnnotations)
  466. }
  467. // ignore the incoming labels from unallocated or unmounted special case pods
  468. if p.AggregatedMetadata || that.AggregatedMetadata {
  469. intersectionProps.AggregatedMetadata = true
  470. // When aggregating by metadata, we maintain the intersection of the labels/annotations
  471. // of the two AllocationProperties objects being intersected here.
  472. // Special case unallocated/unmounted Allocations never have any labels or annotations.
  473. // As a result, they have the effect of always clearing out the intersection,
  474. // regardless if all the other actual allocations/etc have them.
  475. // This logic is designed to effectively ignore the unmounted/unallocated objects
  476. // and just copy over the labels from the other object - we only take the intersection
  477. // of 'legitimate' allocations.
  478. if p.Container == UnmountedSuffix {
  479. intersectionProps.Annotations = that.Annotations
  480. intersectionProps.Labels = that.Labels
  481. } else if that.Container == UnmountedSuffix {
  482. intersectionProps.Annotations = p.Annotations
  483. intersectionProps.Labels = p.Labels
  484. } else {
  485. intersectionProps.Annotations = mapIntersection(p.Annotations, that.Annotations)
  486. intersectionProps.Labels = mapIntersection(p.Labels, that.Labels)
  487. }
  488. }
  489. }
  490. if p.Pod == that.Pod {
  491. intersectionProps.Pod = p.Pod
  492. }
  493. if p.ProviderID == that.ProviderID {
  494. intersectionProps.ProviderID = p.ProviderID
  495. }
  496. return intersectionProps
  497. }
  498. func copyStringMap(original map[string]string) map[string]string {
  499. copy := make(map[string]string)
  500. for key, value := range original {
  501. copy[key] = value
  502. }
  503. return copy
  504. }
  505. func mapIntersection(map1, map2 map[string]string) map[string]string {
  506. result := make(map[string]string)
  507. for key, value := range map1 {
  508. if value2, ok := map2[key]; ok {
  509. if value2 == value {
  510. result[key] = value
  511. }
  512. }
  513. }
  514. return result
  515. }
  516. func (p *AllocationProperties) String() string {
  517. if p == nil {
  518. return "<nil>"
  519. }
  520. strs := []string{}
  521. if p.Cluster != "" {
  522. strs = append(strs, "Cluster:"+p.Cluster)
  523. }
  524. if p.Node != "" {
  525. strs = append(strs, "Node:"+p.Node)
  526. }
  527. if p.Container != "" {
  528. strs = append(strs, "Container:"+p.Container)
  529. }
  530. if p.Controller != "" {
  531. strs = append(strs, "Controller:"+p.Controller)
  532. }
  533. if p.ControllerKind != "" {
  534. strs = append(strs, "ControllerKind:"+p.ControllerKind)
  535. }
  536. if p.Namespace != "" {
  537. strs = append(strs, "Namespace:"+p.Namespace)
  538. }
  539. if p.Pod != "" {
  540. strs = append(strs, "Pod:"+p.Pod)
  541. }
  542. if p.ProviderID != "" {
  543. strs = append(strs, "ProviderID:"+p.ProviderID)
  544. }
  545. if len(p.Services) > 0 {
  546. strs = append(strs, "Services:"+strings.Join(p.Services, ";"))
  547. }
  548. var labelStrs []string
  549. for k, prop := range p.Labels {
  550. labelStrs = append(labelStrs, fmt.Sprintf("%s:%s", k, prop))
  551. }
  552. strs = append(strs, fmt.Sprintf("Labels:{%s}", strings.Join(labelStrs, ",")))
  553. var nsLabelStrs []string
  554. for k, prop := range p.NamespaceLabels {
  555. nsLabelStrs = append(nsLabelStrs, fmt.Sprintf("%s:%s", k, prop))
  556. }
  557. strs = append(strs, fmt.Sprintf("NamespaceLabels:{%s}", strings.Join(nsLabelStrs, ",")))
  558. var annotationStrs []string
  559. for k, prop := range p.Annotations {
  560. annotationStrs = append(annotationStrs, fmt.Sprintf("%s:%s", k, prop))
  561. }
  562. strs = append(strs, fmt.Sprintf("Annotations:{%s}", strings.Join(annotationStrs, ",")))
  563. var nsAnnotationStrs []string
  564. for k, prop := range p.NamespaceAnnotations {
  565. nsAnnotationStrs = append(nsAnnotationStrs, fmt.Sprintf("%s:%s", k, prop))
  566. }
  567. strs = append(strs, fmt.Sprintf("NamespaceAnnotations:{%s}", strings.Join(nsAnnotationStrs, ",")))
  568. return fmt.Sprintf("{%s}", strings.Join(strs, "; "))
  569. }