allocationfilter.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. package kubecost
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. "github.com/opencost/opencost/pkg/log"
  7. )
  8. // FilterField is an enum that represents Allocation-specific fields that can be
  9. // filtered on (namespace, label, etc.)
  10. type FilterField string
  11. // If you add a FilterField, MAKE SURE TO UPDATE ALL FILTER IMPLEMENTATIONS! Go
  12. // does not enforce exhaustive pattern matching on "enum" types.
  13. const (
  14. FilterClusterID FilterField = "clusterid"
  15. FilterNode = "node"
  16. FilterNamespace = "namespace"
  17. FilterControllerKind = "controllerkind"
  18. FilterControllerName = "controllername"
  19. FilterPod = "pod"
  20. FilterContainer = "container"
  21. // Filtering based on label aliases (team, department, etc.) should be a
  22. // responsibility of the query handler. By the time it reaches this
  23. // structured representation, we shouldn't have to be aware of what is
  24. // aliased to what.
  25. FilterLabel = "label"
  26. FilterAnnotation = "annotation"
  27. FilterAlias = "alias"
  28. FilterServices = "services"
  29. )
  30. // FilterOp is an enum that represents operations that can be performed
  31. // when filtering (equality, inequality, etc.)
  32. type FilterOp string
  33. // If you add a FilterOp, MAKE SURE TO UPDATE ALL FILTER IMPLEMENTATIONS! Go
  34. // does not enforce exhaustive pattern matching on "enum" types.
  35. const (
  36. // FilterEquals is the equality operator
  37. // "kube-system" FilterEquals "kube-system" = true
  38. // "kube-syste" FilterEquals "kube-system" = false
  39. FilterEquals FilterOp = "equals"
  40. // FilterNotEquals is the inequality operator
  41. FilterNotEquals = "notequals"
  42. // FilterContains is an array/slice membership operator
  43. // ["a", "b", "c"] FilterContains "a" = true
  44. FilterContains = "contains"
  45. // FilterNotContains is an array/slice non-membership operator
  46. // ["a", "b", "c"] FilterNotContains "d" = true
  47. FilterNotContains = "notcontains"
  48. // FilterStartsWith matches strings with the given prefix.
  49. // "kube-system" StartsWith "kube" = true
  50. //
  51. // When comparing with a field represented by an array/slice, this is like
  52. // applying FilterContains to every element of the slice.
  53. FilterStartsWith = "startswith"
  54. // FilterContainsPrefix is like FilterContains, but using StartsWith instead
  55. // of Equals.
  56. // ["kube-system", "abc123"] ContainsPrefix ["kube"] = true
  57. FilterContainsPrefix = "containsprefix"
  58. )
  59. // AllocationFilter represents anything that can be used to filter an
  60. // Allocation.
  61. //
  62. // Implement this interface with caution. While it is generic, it
  63. // is intended to be introspectable so query handlers can perform various
  64. // optimizations. These optimizations include:
  65. // - Routing a query to the most optimal cache
  66. // - Querying backing data stores efficiently (e.g. translation to SQL)
  67. //
  68. // Custom implementations of this interface outside of this package should not
  69. // expect to receive these benefits. Passing a custom implementation to a
  70. // handler may in errors.
  71. type AllocationFilter interface {
  72. // Matches is the canonical in-Go function for determing if an Allocation
  73. // matches a filter.
  74. Matches(a *Allocation) bool
  75. // Flattened converts a filter into a minimal form, removing unnecessary
  76. // intermediate objects, like single-element or zero-element AND and OR
  77. // conditions.
  78. //
  79. // It returns nil if the filter is filtering nothing.
  80. //
  81. // Example:
  82. // (and (or (namespaceequals "kubecost")) (or)) ->
  83. // (namespaceequals "kubecost")
  84. //
  85. // (and (or)) -> nil
  86. Flattened() AllocationFilter
  87. String() string
  88. // Equals returns true if the two AllocationFilters are logically
  89. // equivalent.
  90. Equals(AllocationFilter) bool
  91. }
  92. // AllocationFilterCondition is the lowest-level type of filter. It represents
  93. // the a filter operation (equality, inequality, etc.) on a field (namespace,
  94. // label, etc.).
  95. type AllocationFilterCondition struct {
  96. Field FilterField
  97. Op FilterOp
  98. // Key is for filters that require key-value pairs, like labels or
  99. // annotations.
  100. //
  101. // A filter of 'label[app]:"foo"' has Key="app" and Value="foo"
  102. Key string
  103. // Value is for _all_ filters. A filter of 'namespace:"kubecost"' has
  104. // Value="kubecost"
  105. Value string
  106. }
  107. func (afc AllocationFilterCondition) String() string {
  108. if afc.Key == "" {
  109. return fmt.Sprintf(`(%s %s "%s")`, afc.Op, afc.Field, afc.Value)
  110. }
  111. return fmt.Sprintf(`(%s %s[%s] "%s")`, afc.Op, afc.Field, afc.Key, afc.Value)
  112. }
  113. // Flattened returns itself because you cannot flatten a base condition further
  114. func (filter AllocationFilterCondition) Flattened() AllocationFilter {
  115. return filter
  116. }
  117. func (left AllocationFilterCondition) Equals(right AllocationFilter) bool {
  118. if rightAFC, ok := right.(AllocationFilterCondition); ok {
  119. return left == rightAFC
  120. }
  121. return false
  122. }
  123. // AllocationFilterOr is a set of filters that should be evaluated as a logical
  124. // OR.
  125. type AllocationFilterOr struct {
  126. Filters []AllocationFilter
  127. }
  128. func (af AllocationFilterOr) String() string {
  129. s := "(or"
  130. for _, f := range af.Filters {
  131. s += fmt.Sprintf(" %s", f)
  132. }
  133. s += ")"
  134. return s
  135. }
  136. // flattened returns a new slice of filters after flattening.
  137. func flattened(filters []AllocationFilter) []AllocationFilter {
  138. var flattenedFilters []AllocationFilter
  139. for _, innerFilter := range filters {
  140. if innerFilter == nil {
  141. continue
  142. }
  143. flattenedInner := innerFilter.Flattened()
  144. if flattenedInner != nil {
  145. flattenedFilters = append(flattenedFilters, flattenedInner)
  146. }
  147. }
  148. return flattenedFilters
  149. }
  150. // Flattened converts a filter into a minimal form, removing unnecessary
  151. // intermediate objects
  152. //
  153. // Flattened returns:
  154. // - nil if filter contains no filters
  155. // - the inner filter if filter contains one filter
  156. // - an equivalent AllocationFilterOr if filter contains more than one filter
  157. func (filter AllocationFilterOr) Flattened() AllocationFilter {
  158. flattenedFilters := flattened(filter.Filters)
  159. if len(flattenedFilters) == 0 {
  160. return nil
  161. }
  162. if len(flattenedFilters) == 1 {
  163. return flattenedFilters[0]
  164. }
  165. return AllocationFilterOr{Filters: flattenedFilters}
  166. }
  167. func (filter AllocationFilterOr) sort() {
  168. for _, inner := range filter.Filters {
  169. if and, ok := inner.(AllocationFilterAnd); ok {
  170. and.sort()
  171. } else if or, ok := inner.(AllocationFilterOr); ok {
  172. or.sort()
  173. }
  174. }
  175. // While a slight hack, we can rely on the string serialization of the
  176. // inner filters to get a sortable representation.
  177. sort.SliceStable(filter.Filters, func(i, j int) bool {
  178. return filter.Filters[i].String() < filter.Filters[j].String()
  179. })
  180. }
  181. func (left AllocationFilterOr) Equals(right AllocationFilter) bool {
  182. // The type cast takes care of right == nil as well
  183. rightOr, ok := right.(AllocationFilterOr)
  184. if !ok {
  185. return false
  186. }
  187. if len(left.Filters) != len(rightOr.Filters) {
  188. return false
  189. }
  190. left.sort()
  191. rightOr.sort()
  192. for i := range left.Filters {
  193. if !left.Filters[i].Equals(rightOr.Filters[i]) {
  194. return false
  195. }
  196. }
  197. return true
  198. }
  199. // AllocationFilterOr is a set of filters that should be evaluated as a logical
  200. // AND.
  201. type AllocationFilterAnd struct {
  202. Filters []AllocationFilter
  203. }
  204. func (af AllocationFilterAnd) String() string {
  205. s := "(and"
  206. for _, f := range af.Filters {
  207. s += fmt.Sprintf(" %s", f)
  208. }
  209. s += ")"
  210. return s
  211. }
  212. // Flattened converts a filter into a minimal form, removing unnecessary
  213. // intermediate objects
  214. //
  215. // Flattened returns:
  216. // - nil if filter contains no filters
  217. // - the inner filter if filter contains one filter
  218. // - an equivalent AllocationFilterAnd if filter contains more than one filter
  219. func (filter AllocationFilterAnd) Flattened() AllocationFilter {
  220. flattenedFilters := flattened(filter.Filters)
  221. if len(flattenedFilters) == 0 {
  222. return nil
  223. }
  224. if len(flattenedFilters) == 1 {
  225. return flattenedFilters[0]
  226. }
  227. return AllocationFilterAnd{Filters: flattenedFilters}
  228. }
  229. func (filter AllocationFilterAnd) sort() {
  230. for _, inner := range filter.Filters {
  231. if and, ok := inner.(AllocationFilterAnd); ok {
  232. and.sort()
  233. } else if or, ok := inner.(AllocationFilterOr); ok {
  234. or.sort()
  235. }
  236. }
  237. // While a slight hack, we can rely on the string serialization of the
  238. // inner filters.
  239. sort.SliceStable(filter.Filters, func(i, j int) bool {
  240. return filter.Filters[i].String() < filter.Filters[j].String()
  241. })
  242. }
  243. func (left AllocationFilterAnd) Equals(right AllocationFilter) bool {
  244. // The type cast takes care of right == nil as well
  245. rightAnd, ok := right.(AllocationFilterAnd)
  246. if !ok {
  247. return false
  248. }
  249. if len(left.Filters) != len(rightAnd.Filters) {
  250. return false
  251. }
  252. left.sort()
  253. rightAnd.sort()
  254. for i := range left.Filters {
  255. if !left.Filters[i].Equals(rightAnd.Filters[i]) {
  256. return false
  257. }
  258. }
  259. return true
  260. }
  261. func (filter AllocationFilterCondition) Matches(a *Allocation) bool {
  262. if a == nil {
  263. return false
  264. }
  265. if a.Properties == nil {
  266. return false
  267. }
  268. // The Allocation's value for the field to compare
  269. // We use an interface{} so this can contain the services []string slice
  270. var valueToCompare interface{}
  271. // toCompareMissing will be true if the value to be compared is missing in
  272. // the Allocation. For example, if we're filtering based on the value of
  273. // the "app" label, but the Allocation doesn't have an "app" label, this
  274. // will become true. This lets us deal with != gracefully.
  275. toCompareMissing := false
  276. // This switch maps the filter.Field to the field to be compared in
  277. // a.Properties and sets valueToCompare from the value in a.Properties.
  278. switch filter.Field {
  279. case FilterClusterID:
  280. valueToCompare = a.Properties.Cluster
  281. case FilterNode:
  282. valueToCompare = a.Properties.Node
  283. case FilterNamespace:
  284. valueToCompare = a.Properties.Namespace
  285. case FilterControllerKind:
  286. valueToCompare = a.Properties.ControllerKind
  287. case FilterControllerName:
  288. valueToCompare = a.Properties.Controller
  289. case FilterPod:
  290. valueToCompare = a.Properties.Pod
  291. case FilterContainer:
  292. valueToCompare = a.Properties.Container
  293. // Comes from GetAnnotation/LabelFilterFunc in KCM
  294. case FilterLabel:
  295. val, ok := a.Properties.Labels[filter.Key]
  296. if !ok {
  297. toCompareMissing = true
  298. } else {
  299. valueToCompare = val
  300. }
  301. case FilterAnnotation:
  302. val, ok := a.Properties.Annotations[filter.Key]
  303. if !ok {
  304. toCompareMissing = true
  305. } else {
  306. valueToCompare = val
  307. }
  308. case FilterAlias:
  309. var ok bool
  310. valueToCompare, ok = a.Properties.Labels[filter.Key]
  311. if !ok {
  312. valueToCompare, ok = a.Properties.Annotations[filter.Key]
  313. if !ok {
  314. toCompareMissing = true
  315. }
  316. }
  317. case FilterServices:
  318. valueToCompare = a.Properties.Services
  319. default:
  320. log.Errorf("Allocation Filter: Unhandled filter field. This is a filter implementation error and requires immediate patching. Field: %s", filter.Field)
  321. return false
  322. }
  323. switch filter.Op {
  324. case FilterEquals:
  325. // namespace:"__unallocated__" should match a.Properties.Namespace = ""
  326. // label[app]:"__unallocated__" should match _, ok := Labels[app]; !ok
  327. if toCompareMissing || valueToCompare == "" {
  328. return filter.Value == UnallocatedSuffix
  329. }
  330. if valueToCompare == filter.Value {
  331. return true
  332. }
  333. case FilterNotEquals:
  334. // namespace!:"__unallocated__" should match
  335. // a.Properties.Namespace != ""
  336. // label[app]!:"__unallocated__" should match _, ok := Labels[app]; ok
  337. if filter.Value == UnallocatedSuffix {
  338. if toCompareMissing {
  339. return false
  340. }
  341. return valueToCompare != ""
  342. }
  343. if toCompareMissing {
  344. return true
  345. }
  346. if valueToCompare != filter.Value {
  347. return true
  348. }
  349. case FilterContains:
  350. if stringSlice, ok := valueToCompare.([]string); ok {
  351. if len(stringSlice) == 0 {
  352. return filter.Value == UnallocatedSuffix
  353. }
  354. for _, s := range stringSlice {
  355. if s == filter.Value {
  356. return true
  357. }
  358. }
  359. } else {
  360. log.Warnf("Allocation Filter: invalid 'contains' call for non-list filter value")
  361. }
  362. case FilterNotContains:
  363. if stringSlice, ok := valueToCompare.([]string); ok {
  364. // services!:"__unallocated__" should match
  365. // len(a.Properties.Services) > 0
  366. //
  367. // TODO: is this true?
  368. if filter.Value == UnallocatedSuffix {
  369. return len(stringSlice) > 0
  370. }
  371. for _, s := range stringSlice {
  372. if s == filter.Value {
  373. return false
  374. }
  375. }
  376. return true
  377. } else {
  378. log.Warnf("Allocation Filter: invalid 'notcontains' call for non-list filter value")
  379. }
  380. case FilterStartsWith:
  381. if toCompareMissing {
  382. return false
  383. }
  384. // We don't need special __unallocated__ logic here because a query
  385. // asking for "__unallocated__" won't have a wildcard and unallocated
  386. // properties are the empty string.
  387. s, ok := valueToCompare.(string)
  388. if !ok {
  389. log.Warnf("Allocation Filter: invalid 'startswith' call for field with unsupported type")
  390. return false
  391. }
  392. return strings.HasPrefix(s, filter.Value)
  393. case FilterContainsPrefix:
  394. if toCompareMissing {
  395. return false
  396. }
  397. // We don't need special __unallocated__ logic here because a query
  398. // asking for "__unallocated__" won't have a wildcard and unallocated
  399. // properties are the empty string.
  400. values, ok := valueToCompare.([]string)
  401. if !ok {
  402. log.Warnf("Allocation Filter: invalid '%s' call for field with unsupported type", FilterContainsPrefix)
  403. return false
  404. }
  405. for _, s := range values {
  406. if strings.HasPrefix(s, filter.Value) {
  407. return true
  408. }
  409. }
  410. return false
  411. default:
  412. log.Errorf("Allocation Filter: Unhandled filter op. This is a filter implementation error and requires immediate patching. Op: %s", filter.Op)
  413. return false
  414. }
  415. return false
  416. }
  417. func (and AllocationFilterAnd) Matches(a *Allocation) bool {
  418. filters := and.Filters
  419. if len(filters) == 0 {
  420. return true
  421. }
  422. for _, filter := range filters {
  423. if !filter.Matches(a) {
  424. return false
  425. }
  426. }
  427. return true
  428. }
  429. func (or AllocationFilterOr) Matches(a *Allocation) bool {
  430. filters := or.Filters
  431. if len(filters) == 0 {
  432. return true
  433. }
  434. for _, filter := range filters {
  435. if filter.Matches(a) {
  436. return true
  437. }
  438. }
  439. return false
  440. }
  441. // AllocationFilterNone is a filter that matches no allocations. This is useful
  442. // for applications like authorization, where a user/group/role may be disallowed
  443. // from viewing Allocation data entirely.
  444. type AllocationFilterNone struct{}
  445. func (afn AllocationFilterNone) String() string { return "(none)" }
  446. func (afn AllocationFilterNone) Flattened() AllocationFilter { return afn }
  447. func (afn AllocationFilterNone) Matches(a *Allocation) bool { return false }
  448. func (left AllocationFilterNone) Equals(right AllocationFilter) bool {
  449. _, ok := right.(AllocationFilterNone)
  450. return ok
  451. }