allocationprops.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. // When set to true, maintain the intersection of all labels + annotations
  99. // in the aggregated AllocationProperties object
  100. AggregatedMetadata bool `json:"-"` //@bingen:field[ignore]
  101. }
  102. // AllocationLabels is a schema-free mapping of key/value pairs that can be
  103. // attributed to an Allocation
  104. type AllocationLabels map[string]string
  105. // AllocationAnnotations is a schema-free mapping of key/value pairs that can be
  106. // attributed to an Allocation
  107. type AllocationAnnotations map[string]string
  108. func (p *AllocationProperties) Clone() *AllocationProperties {
  109. if p == nil {
  110. return nil
  111. }
  112. clone := &AllocationProperties{}
  113. clone.Cluster = p.Cluster
  114. clone.Node = p.Node
  115. clone.Container = p.Container
  116. clone.Controller = p.Controller
  117. clone.ControllerKind = p.ControllerKind
  118. clone.Namespace = p.Namespace
  119. clone.Pod = p.Pod
  120. clone.ProviderID = p.ProviderID
  121. var services []string
  122. services = append(services, p.Services...)
  123. clone.Services = services
  124. labels := make(map[string]string, len(p.Labels))
  125. for k, v := range p.Labels {
  126. labels[k] = v
  127. }
  128. clone.Labels = labels
  129. annotations := make(map[string]string, len(p.Annotations))
  130. for k, v := range p.Annotations {
  131. annotations[k] = v
  132. }
  133. clone.Annotations = annotations
  134. return clone
  135. }
  136. func (p *AllocationProperties) Equal(that *AllocationProperties) bool {
  137. if p == nil || that == nil {
  138. return false
  139. }
  140. if p.Cluster != that.Cluster {
  141. return false
  142. }
  143. if p.Node != that.Node {
  144. return false
  145. }
  146. if p.Container != that.Container {
  147. return false
  148. }
  149. if p.Controller != that.Controller {
  150. return false
  151. }
  152. if p.ControllerKind != that.ControllerKind {
  153. return false
  154. }
  155. if p.Namespace != that.Namespace {
  156. return false
  157. }
  158. if p.Pod != that.Pod {
  159. return false
  160. }
  161. if p.ProviderID != that.ProviderID {
  162. return false
  163. }
  164. pLabels := p.Labels
  165. thatLabels := that.Labels
  166. if len(pLabels) == len(thatLabels) {
  167. for k, pv := range pLabels {
  168. tv, ok := thatLabels[k]
  169. if !ok || tv != pv {
  170. return false
  171. }
  172. }
  173. } else {
  174. return false
  175. }
  176. pAnnotations := p.Annotations
  177. thatAnnotations := that.Annotations
  178. if len(pAnnotations) == len(thatAnnotations) {
  179. for k, pv := range pAnnotations {
  180. tv, ok := thatAnnotations[k]
  181. if !ok || tv != pv {
  182. return false
  183. }
  184. }
  185. } else {
  186. return false
  187. }
  188. pServices := p.Services
  189. thatServices := that.Services
  190. if len(pServices) == len(thatServices) {
  191. sort.Strings(pServices)
  192. sort.Strings(thatServices)
  193. for i, pv := range pServices {
  194. tv := thatServices[i]
  195. if tv != pv {
  196. return false
  197. }
  198. }
  199. } else {
  200. return false
  201. }
  202. return true
  203. }
  204. // GenerateKey generates a string that represents the key by which the
  205. // AllocationProperties should be aggregated, given the properties defined by
  206. // the aggregateBy parameter and the given label configuration.
  207. func (p *AllocationProperties) GenerateKey(aggregateBy []string, labelConfig *LabelConfig) string {
  208. if p == nil {
  209. return ""
  210. }
  211. if labelConfig == nil {
  212. labelConfig = NewLabelConfig()
  213. }
  214. // Names will ultimately be joined into a single name, which uniquely
  215. // identifies allocations.
  216. names := []string{}
  217. for _, agg := range aggregateBy {
  218. switch true {
  219. case agg == AllocationClusterProp:
  220. names = append(names, p.Cluster)
  221. case agg == AllocationNodeProp:
  222. names = append(names, p.Node)
  223. case agg == AllocationNamespaceProp:
  224. names = append(names, p.Namespace)
  225. case agg == AllocationControllerKindProp:
  226. controllerKind := p.ControllerKind
  227. if controllerKind == "" {
  228. // Indicate that allocation has no controller
  229. controllerKind = UnallocatedSuffix
  230. }
  231. names = append(names, controllerKind)
  232. case agg == AllocationDaemonSetProp || agg == AllocationStatefulSetProp || agg == AllocationDeploymentProp || agg == AllocationJobProp:
  233. controller := p.Controller
  234. if agg != p.ControllerKind || controller == "" {
  235. // The allocation does not have the specified controller kind
  236. controller = UnallocatedSuffix
  237. }
  238. names = append(names, controller)
  239. case agg == AllocationControllerProp:
  240. controller := p.Controller
  241. if controller == "" {
  242. // Indicate that allocation has no controller
  243. controller = UnallocatedSuffix
  244. } else if p.ControllerKind != "" {
  245. controller = fmt.Sprintf("%s:%s", p.ControllerKind, controller)
  246. }
  247. names = append(names, controller)
  248. case agg == AllocationPodProp:
  249. names = append(names, p.Pod)
  250. case agg == AllocationContainerProp:
  251. names = append(names, p.Container)
  252. case agg == AllocationServiceProp:
  253. services := p.Services
  254. if len(services) == 0 {
  255. // Indicate that allocation has no services
  256. names = append(names, UnallocatedSuffix)
  257. } else {
  258. // Unmounted load balancers lead to __unmounted__ Allocations whose
  259. // services field is populated. If we don't have a special case, the
  260. // __unmounted__ Allocation will be transformed into a regular Allocation,
  261. // causing issues with AggregateBy and drilldown
  262. if p.Pod == UnmountedSuffix || p.Namespace == UnmountedSuffix || p.Container == UnmountedSuffix {
  263. names = append(names, UnmountedSuffix)
  264. } else {
  265. // This just uses the first service
  266. for _, service := range services {
  267. names = append(names, service)
  268. break
  269. }
  270. }
  271. }
  272. case strings.HasPrefix(agg, "label:"):
  273. labels := p.Labels
  274. if labels == nil {
  275. names = append(names, UnallocatedSuffix)
  276. } else {
  277. labelName := labelConfig.Sanitize(strings.TrimPrefix(agg, "label:"))
  278. if labelValue, ok := labels[labelName]; ok {
  279. names = append(names, fmt.Sprintf("%s", labelValue))
  280. } else {
  281. names = append(names, UnallocatedSuffix)
  282. }
  283. }
  284. case strings.HasPrefix(agg, "annotation:"):
  285. annotations := p.Annotations
  286. if annotations == nil {
  287. names = append(names, UnallocatedSuffix)
  288. } else {
  289. annotationName := labelConfig.Sanitize(strings.TrimPrefix(agg, "annotation:"))
  290. if annotationValue, ok := annotations[annotationName]; ok {
  291. names = append(names, fmt.Sprintf("%s", annotationValue))
  292. } else {
  293. names = append(names, UnallocatedSuffix)
  294. }
  295. }
  296. case agg == AllocationDepartmentProp:
  297. labels := p.Labels
  298. annotations := p.Annotations
  299. if labels == nil && annotations == nil {
  300. names = append(names, UnallocatedSuffix)
  301. } else {
  302. labelNames := strings.Split(labelConfig.DepartmentLabel, ",")
  303. for _, labelName := range labelNames {
  304. labelName = labelConfig.Sanitize(labelName)
  305. if labelValue, ok := labels[labelName]; ok {
  306. names = append(names, labelValue)
  307. } else if annotationValue, ok := annotations[labelName]; ok {
  308. names = append(names, annotationValue)
  309. } else {
  310. names = append(names, UnallocatedSuffix)
  311. }
  312. }
  313. }
  314. case agg == AllocationEnvironmentProp:
  315. labels := p.Labels
  316. annotations := p.Annotations
  317. if labels == nil && annotations == nil {
  318. names = append(names, UnallocatedSuffix)
  319. } else {
  320. labelNames := strings.Split(labelConfig.EnvironmentLabel, ",")
  321. for _, labelName := range labelNames {
  322. labelName = labelConfig.Sanitize(labelName)
  323. if labelValue, ok := labels[labelName]; ok {
  324. names = append(names, labelValue)
  325. } else if annotationValue, ok := annotations[labelName]; ok {
  326. names = append(names, annotationValue)
  327. } else {
  328. names = append(names, UnallocatedSuffix)
  329. }
  330. }
  331. }
  332. case agg == AllocationOwnerProp:
  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.OwnerLabel, ",")
  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 == AllocationProductProp:
  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.ProductLabel, ",")
  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 == AllocationTeamProp:
  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.TeamLabel, ",")
  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. default:
  387. // This case should never be reached, as input up until this point
  388. // should be checked and rejected if invalid. But if we do get a
  389. // value we don't recognize, log a warning.
  390. log.Warnf("generateKey: illegal aggregation parameter: %s", agg)
  391. }
  392. }
  393. return strings.Join(names, "/")
  394. }
  395. // Intersection returns an *AllocationProperties which contains all matching fields between the calling and parameter AllocationProperties
  396. // nillable slices and maps are left as nil
  397. func (p *AllocationProperties) Intersection(that *AllocationProperties) *AllocationProperties {
  398. if p == nil || that == nil {
  399. return nil
  400. }
  401. intersectionProps := &AllocationProperties{}
  402. if p.Cluster == that.Cluster {
  403. intersectionProps.Cluster = p.Cluster
  404. }
  405. if p.Node == that.Node {
  406. intersectionProps.Node = p.Node
  407. }
  408. if p.Container == that.Container {
  409. intersectionProps.Container = p.Container
  410. }
  411. if p.Controller == that.Controller {
  412. intersectionProps.Controller = p.Controller
  413. }
  414. if p.ControllerKind == that.ControllerKind {
  415. intersectionProps.ControllerKind = p.ControllerKind
  416. }
  417. if p.Namespace == that.Namespace {
  418. intersectionProps.Namespace = p.Namespace
  419. // ignore the incoming labels from unallocated or unmounted special case pods
  420. if p.AggregatedMetadata || that.AggregatedMetadata {
  421. intersectionProps.AggregatedMetadata = true
  422. // When aggregating by metadata, we maintain the intersection of the labels/annotations
  423. // of the two AllocationProperties objects being intersected here.
  424. // Special case unallocated/unmounted Allocations never have any labels or annotations.
  425. // As a result, they have the effect of always clearing out the intersection,
  426. // regardless if all the other actual allocations/etc have them.
  427. // This logic is designed to effectively ignore the unmounted/unallocated objects
  428. // and just copy over the labels from the other object - we only take the intersection
  429. // of 'legitimate' allocations.
  430. if p.Container == UnmountedSuffix {
  431. intersectionProps.Annotations = that.Annotations
  432. intersectionProps.Labels = that.Labels
  433. } else if that.Container == UnmountedSuffix {
  434. intersectionProps.Annotations = p.Annotations
  435. intersectionProps.Labels = p.Labels
  436. } else {
  437. intersectionProps.Annotations = mapIntersection(p.Annotations, that.Annotations)
  438. intersectionProps.Labels = mapIntersection(p.Labels, that.Labels)
  439. }
  440. }
  441. }
  442. if p.Pod == that.Pod {
  443. intersectionProps.Pod = p.Pod
  444. }
  445. if p.ProviderID == that.ProviderID {
  446. intersectionProps.ProviderID = p.ProviderID
  447. }
  448. return intersectionProps
  449. }
  450. func mapIntersection(map1, map2 map[string]string) map[string]string {
  451. result := make(map[string]string)
  452. for key, value := range map1 {
  453. if value2, ok := map2[key]; ok {
  454. if value2 == value {
  455. result[key] = value
  456. }
  457. }
  458. }
  459. return result
  460. }
  461. func (p *AllocationProperties) String() string {
  462. if p == nil {
  463. return "<nil>"
  464. }
  465. strs := []string{}
  466. if p.Cluster != "" {
  467. strs = append(strs, "Cluster:"+p.Cluster)
  468. }
  469. if p.Node != "" {
  470. strs = append(strs, "Node:"+p.Node)
  471. }
  472. if p.Container != "" {
  473. strs = append(strs, "Container:"+p.Container)
  474. }
  475. if p.Controller != "" {
  476. strs = append(strs, "Controller:"+p.Controller)
  477. }
  478. if p.ControllerKind != "" {
  479. strs = append(strs, "ControllerKind:"+p.ControllerKind)
  480. }
  481. if p.Namespace != "" {
  482. strs = append(strs, "Namespace:"+p.Namespace)
  483. }
  484. if p.Pod != "" {
  485. strs = append(strs, "Pod:"+p.Pod)
  486. }
  487. if p.ProviderID != "" {
  488. strs = append(strs, "ProviderID:"+p.ProviderID)
  489. }
  490. if len(p.Services) > 0 {
  491. strs = append(strs, "Services:"+strings.Join(p.Services, ";"))
  492. }
  493. var labelStrs []string
  494. for k, prop := range p.Labels {
  495. labelStrs = append(labelStrs, fmt.Sprintf("%s:%s", k, prop))
  496. }
  497. strs = append(strs, fmt.Sprintf("Labels:{%s}", strings.Join(labelStrs, ",")))
  498. var annotationStrs []string
  499. for k, prop := range p.Annotations {
  500. annotationStrs = append(annotationStrs, fmt.Sprintf("%s:%s", k, prop))
  501. }
  502. strs = append(strs, fmt.Sprintf("Annotations:{%s}", strings.Join(annotationStrs, ",")))
  503. return fmt.Sprintf("{%s}", strings.Join(strs, "; "))
  504. }