allocationfilter.go 11 KB

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