allocationprops.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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:"-"`
  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. // This just uses the first service
  259. for _, service := range services {
  260. names = append(names, service)
  261. break
  262. }
  263. }
  264. case strings.HasPrefix(agg, "label:"):
  265. labels := p.Labels
  266. if labels == nil {
  267. names = append(names, UnallocatedSuffix)
  268. } else {
  269. labelName := labelConfig.Sanitize(strings.TrimPrefix(agg, "label:"))
  270. if labelValue, ok := labels[labelName]; ok {
  271. names = append(names, fmt.Sprintf("%s", labelValue))
  272. } else {
  273. names = append(names, UnallocatedSuffix)
  274. }
  275. }
  276. case strings.HasPrefix(agg, "annotation:"):
  277. annotations := p.Annotations
  278. if annotations == nil {
  279. names = append(names, UnallocatedSuffix)
  280. } else {
  281. annotationName := labelConfig.Sanitize(strings.TrimPrefix(agg, "annotation:"))
  282. if annotationValue, ok := annotations[annotationName]; ok {
  283. names = append(names, fmt.Sprintf("%s", annotationValue))
  284. } else {
  285. names = append(names, UnallocatedSuffix)
  286. }
  287. }
  288. case agg == AllocationDepartmentProp:
  289. labels := p.Labels
  290. annotations := p.Annotations
  291. if labels == nil && annotations == nil {
  292. names = append(names, UnallocatedSuffix)
  293. } else {
  294. labelNames := strings.Split(labelConfig.DepartmentLabel, ",")
  295. for _, labelName := range labelNames {
  296. labelName = labelConfig.Sanitize(labelName)
  297. if labelValue, ok := labels[labelName]; ok {
  298. names = append(names, labelValue)
  299. } else if annotationValue, ok := annotations[labelName]; ok {
  300. names = append(names, annotationValue)
  301. } else {
  302. names = append(names, UnallocatedSuffix)
  303. }
  304. }
  305. }
  306. case agg == AllocationEnvironmentProp:
  307. labels := p.Labels
  308. annotations := p.Annotations
  309. if labels == nil && annotations == nil {
  310. names = append(names, UnallocatedSuffix)
  311. } else {
  312. labelNames := strings.Split(labelConfig.EnvironmentLabel, ",")
  313. for _, labelName := range labelNames {
  314. labelName = labelConfig.Sanitize(labelName)
  315. if labelValue, ok := labels[labelName]; ok {
  316. names = append(names, labelValue)
  317. } else if annotationValue, ok := annotations[labelName]; ok {
  318. names = append(names, annotationValue)
  319. } else {
  320. names = append(names, UnallocatedSuffix)
  321. }
  322. }
  323. }
  324. case agg == AllocationOwnerProp:
  325. labels := p.Labels
  326. annotations := p.Annotations
  327. if labels == nil && annotations == nil {
  328. names = append(names, UnallocatedSuffix)
  329. } else {
  330. labelNames := strings.Split(labelConfig.OwnerLabel, ",")
  331. for _, labelName := range labelNames {
  332. labelName = labelConfig.Sanitize(labelName)
  333. if labelValue, ok := labels[labelName]; ok {
  334. names = append(names, labelValue)
  335. } else if annotationValue, ok := annotations[labelName]; ok {
  336. names = append(names, annotationValue)
  337. } else {
  338. names = append(names, UnallocatedSuffix)
  339. }
  340. }
  341. }
  342. case agg == AllocationProductProp:
  343. labels := p.Labels
  344. annotations := p.Annotations
  345. if labels == nil && annotations == nil {
  346. names = append(names, UnallocatedSuffix)
  347. } else {
  348. labelNames := strings.Split(labelConfig.ProductLabel, ",")
  349. for _, labelName := range labelNames {
  350. labelName = labelConfig.Sanitize(labelName)
  351. if labelValue, ok := labels[labelName]; ok {
  352. names = append(names, labelValue)
  353. } else if annotationValue, ok := annotations[labelName]; ok {
  354. names = append(names, annotationValue)
  355. } else {
  356. names = append(names, UnallocatedSuffix)
  357. }
  358. }
  359. }
  360. case agg == AllocationTeamProp:
  361. labels := p.Labels
  362. annotations := p.Annotations
  363. if labels == nil && annotations == nil {
  364. names = append(names, UnallocatedSuffix)
  365. } else {
  366. labelNames := strings.Split(labelConfig.TeamLabel, ",")
  367. for _, labelName := range labelNames {
  368. labelName = labelConfig.Sanitize(labelName)
  369. if labelValue, ok := labels[labelName]; ok {
  370. names = append(names, labelValue)
  371. } else if annotationValue, ok := annotations[labelName]; ok {
  372. names = append(names, annotationValue)
  373. } else {
  374. names = append(names, UnallocatedSuffix)
  375. }
  376. }
  377. }
  378. default:
  379. // This case should never be reached, as input up until this point
  380. // should be checked and rejected if invalid. But if we do get a
  381. // value we don't recognize, log a warning.
  382. log.Warnf("generateKey: illegal aggregation parameter: %s", agg)
  383. }
  384. }
  385. return strings.Join(names, "/")
  386. }
  387. // Intersection returns an *AllocationProperties which contains all matching fields between the calling and parameter AllocationProperties
  388. // nillable slices and maps are left as nil
  389. func (p *AllocationProperties) Intersection(that *AllocationProperties) *AllocationProperties {
  390. if p == nil || that == nil {
  391. return nil
  392. }
  393. intersectionProps := &AllocationProperties{}
  394. if p.Cluster == that.Cluster {
  395. intersectionProps.Cluster = p.Cluster
  396. }
  397. if p.Node == that.Node {
  398. intersectionProps.Node = p.Node
  399. }
  400. if p.Container == that.Container {
  401. intersectionProps.Container = p.Container
  402. }
  403. if p.Controller == that.Controller {
  404. intersectionProps.Controller = p.Controller
  405. }
  406. if p.ControllerKind == that.ControllerKind {
  407. intersectionProps.ControllerKind = p.ControllerKind
  408. }
  409. if p.Namespace == that.Namespace {
  410. intersectionProps.Namespace = p.Namespace
  411. // ignore the incoming labels from unallocated or unmounted special case pods
  412. if p.AggregatedMetadata || that.AggregatedMetadata {
  413. intersectionProps.AggregatedMetadata = true
  414. // When aggregating by metadata, we maintain the intersection of the labels/annotations
  415. // of the two AllocationProperties objects being intersected here.
  416. // Special case unallocated/unmounted Allocations never have any labels or annotations.
  417. // As a result, they have the effect of always clearing out the intersection,
  418. // regardless if all the other actual allocations/etc have them.
  419. // This logic is designed to effectively ignore the unmounted/unallocated objects
  420. // and just copy over the labels from the other object - we only take the intersection
  421. // of 'legitimate' allocations.
  422. if p.Container == UnmountedSuffix {
  423. intersectionProps.Annotations = that.Annotations
  424. intersectionProps.Labels = that.Labels
  425. } else if that.Container == UnmountedSuffix {
  426. intersectionProps.Annotations = p.Annotations
  427. intersectionProps.Labels = p.Labels
  428. } else {
  429. intersectionProps.Annotations = mapIntersection(p.Annotations, that.Annotations)
  430. intersectionProps.Labels = mapIntersection(p.Labels, that.Labels)
  431. }
  432. }
  433. }
  434. if p.Pod == that.Pod {
  435. intersectionProps.Pod = p.Pod
  436. }
  437. if p.ProviderID == that.ProviderID {
  438. intersectionProps.ProviderID = p.ProviderID
  439. }
  440. return intersectionProps
  441. }
  442. func mapIntersection(map1, map2 map[string]string) map[string]string {
  443. result := make(map[string]string)
  444. for key, value := range map1 {
  445. if value2, ok := map2[key]; ok {
  446. if value2 == value {
  447. result[key] = value
  448. }
  449. }
  450. }
  451. return result
  452. }
  453. func (p *AllocationProperties) String() string {
  454. if p == nil {
  455. return "<nil>"
  456. }
  457. strs := []string{}
  458. if p.Cluster != "" {
  459. strs = append(strs, "Cluster:"+p.Cluster)
  460. }
  461. if p.Node != "" {
  462. strs = append(strs, "Node:"+p.Node)
  463. }
  464. if p.Container != "" {
  465. strs = append(strs, "Container:"+p.Container)
  466. }
  467. if p.Controller != "" {
  468. strs = append(strs, "Controller:"+p.Controller)
  469. }
  470. if p.ControllerKind != "" {
  471. strs = append(strs, "ControllerKind:"+p.ControllerKind)
  472. }
  473. if p.Namespace != "" {
  474. strs = append(strs, "Namespace:"+p.Namespace)
  475. }
  476. if p.Pod != "" {
  477. strs = append(strs, "Pod:"+p.Pod)
  478. }
  479. if p.ProviderID != "" {
  480. strs = append(strs, "ProviderID:"+p.ProviderID)
  481. }
  482. if len(p.Services) > 0 {
  483. strs = append(strs, "Services:"+strings.Join(p.Services, ";"))
  484. }
  485. var labelStrs []string
  486. for k, prop := range p.Labels {
  487. labelStrs = append(labelStrs, fmt.Sprintf("%s:%s", k, prop))
  488. }
  489. strs = append(strs, fmt.Sprintf("Labels:{%s}", strings.Join(labelStrs, ",")))
  490. var annotationStrs []string
  491. for k, prop := range p.Annotations {
  492. annotationStrs = append(annotationStrs, fmt.Sprintf("%s:%s", k, prop))
  493. }
  494. strs = append(strs, fmt.Sprintf("Annotations:{%s}", strings.Join(annotationStrs, ",")))
  495. return fmt.Sprintf("{%s}", strings.Join(strs, "; "))
  496. }