allocationfilter.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package kubecost
  2. import (
  3. "strings"
  4. "github.com/kubecost/opencost/pkg/log"
  5. )
  6. // FilterField is an enum that represents Allocation-specific fields that can be
  7. // filtered on (namespace, label, etc.)
  8. type FilterField string
  9. // If you add a FilterField, MAKE SURE TO UPDATE ALL FILTER IMPLEMENTATIONS! Go
  10. // does not enforce exhaustive pattern matching on "enum" types.
  11. const (
  12. FilterClusterID FilterField = "clusterid"
  13. FilterNode = "node"
  14. FilterNamespace = "namespace"
  15. FilterControllerKind = "controllerkind"
  16. FilterControllerName = "controllername"
  17. FilterPod = "pod"
  18. FilterContainer = "container"
  19. // Filtering based on label aliases (team, department, etc.) should be a
  20. // responsibility of the query handler. By the time it reaches this
  21. // structured representation, we shouldn't have to be aware of what is
  22. // aliased to what.
  23. FilterLabel = "label"
  24. FilterAnnotation = "annotation"
  25. FilterServices = "services"
  26. )
  27. // FilterOp is an enum that represents operations that can be performed
  28. // when filtering (equality, inequality, etc.)
  29. type FilterOp string
  30. // If you add a FilterOp, MAKE SURE TO UPDATE ALL FILTER IMPLEMENTATIONS! Go
  31. // does not enforce exhaustive pattern matching on "enum" types.
  32. const (
  33. // FilterEquals is the equality operator
  34. // "kube-system" FilterEquals "kube-system" = true
  35. // "kube-syste" FilterEquals "kube-system" = false
  36. FilterEquals FilterOp = "equals"
  37. // FilterNotEquals is the inequality operator
  38. FilterNotEquals = "notequals"
  39. // FilterContains is an array/slice membership operator
  40. // ["a", "b", "c"] FilterContains "a" = true
  41. FilterContains = "contains"
  42. // FilterStartsWith matches strings with the given prefix.
  43. // "kube-system" StartsWith "kube" = true
  44. //
  45. // When comparing with a field represented by an array/slice, this is like
  46. // applying FilterContains to every element of the slice.
  47. FilterStartsWith = "startswith"
  48. // FilterContainsPrefix is like FilterContains, but using StartsWith instead
  49. // of Equals.
  50. // ["kube-system", "abc123"] ContainsPrefix ["kube"] = true
  51. FilterContainsPrefix = "containsprefix"
  52. )
  53. // AllocationFilter represents anything that can be used to filter an
  54. // Allocation.
  55. //
  56. // Implement this interface with caution. While it is generic, it
  57. // is intended to be introspectable so query handlers can perform various
  58. // optimizations. These optimizations include:
  59. // - Routing a query to the most optimal cache
  60. // - Querying backing data stores efficiently (e.g. translation to SQL)
  61. //
  62. // Custom implementations of this interface outside of this package should not
  63. // expect to receive these benefits. Passing a custom implementation to a
  64. // handler may in errors.
  65. type AllocationFilter interface {
  66. // Matches is the canonical in-Go function for determing if an Allocation
  67. // matches a filter.
  68. Matches(a *Allocation) bool
  69. }
  70. // AllocationFilterCondition is the lowest-level type of filter. It represents
  71. // the a filter operation (equality, inequality, etc.) on a field (namespace,
  72. // label, etc.).
  73. type AllocationFilterCondition struct {
  74. Field FilterField
  75. Op FilterOp
  76. // Key is for filters that require key-value pairs, like labels or
  77. // annotations.
  78. //
  79. // A filter of 'label[app]:"foo"' has Key="app" and Value="foo"
  80. Key string
  81. // Value is for _all_ filters. A filter of 'namespace:"kubecost"' has
  82. // Value="kubecost"
  83. Value string
  84. }
  85. // AllocationFilterOr is a set of filters that should be evaluated as a logical
  86. // OR.
  87. type AllocationFilterOr struct {
  88. Filters []AllocationFilter
  89. }
  90. // AllocationFilterOr is a set of filters that should be evaluated as a logical
  91. // AND.
  92. type AllocationFilterAnd struct {
  93. Filters []AllocationFilter
  94. }
  95. func (filter AllocationFilterCondition) Matches(a *Allocation) bool {
  96. if a == nil {
  97. return false
  98. }
  99. if a.Properties == nil {
  100. return false
  101. }
  102. // The Allocation's value for the field to compare
  103. // We use an interface{} so this can contain the services []string slice
  104. var valueToCompare interface{}
  105. // toCompareMissing will be true if the value to be compared is missing in
  106. // the Allocation. For example, if we're filtering based on the value of
  107. // the "app" label, but the Allocation doesn't have an "app" label, this
  108. // will become true. This lets us deal with != gracefully.
  109. toCompareMissing := false
  110. // This switch maps the filter.Field to the field to be compared in
  111. // a.Properties and sets valueToCompare from the value in a.Properties.
  112. switch filter.Field {
  113. case FilterClusterID:
  114. valueToCompare = a.Properties.Cluster
  115. case FilterNode:
  116. valueToCompare = a.Properties.Node
  117. case FilterNamespace:
  118. valueToCompare = a.Properties.Namespace
  119. case FilterControllerKind:
  120. valueToCompare = a.Properties.ControllerKind
  121. case FilterControllerName:
  122. valueToCompare = a.Properties.Controller
  123. case FilterPod:
  124. valueToCompare = a.Properties.Pod
  125. case FilterContainer:
  126. valueToCompare = a.Properties.Container
  127. // Comes from GetAnnotation/LabelFilterFunc in KCM
  128. case FilterLabel:
  129. val, ok := a.Properties.Labels[filter.Key]
  130. if !ok {
  131. toCompareMissing = true
  132. } else {
  133. valueToCompare = val
  134. }
  135. case FilterAnnotation:
  136. val, ok := a.Properties.Annotations[filter.Key]
  137. if !ok {
  138. toCompareMissing = true
  139. } else {
  140. valueToCompare = val
  141. }
  142. case FilterServices:
  143. valueToCompare = a.Properties.Services
  144. default:
  145. log.Errorf("Allocation Filter: Unhandled filter field. This is a filter implementation error and requires immediate patching. Field: %s", filter.Field)
  146. return false
  147. }
  148. switch filter.Op {
  149. case FilterEquals:
  150. if toCompareMissing {
  151. return false
  152. }
  153. // namespace:"__unallocated__" should match a.Properties.Namespace = ""
  154. if valueToCompare == "" {
  155. return filter.Value == UnallocatedSuffix
  156. }
  157. if valueToCompare == filter.Value {
  158. return true
  159. }
  160. case FilterNotEquals:
  161. if toCompareMissing {
  162. return true
  163. }
  164. // namespace!:"__unallocated__" should match
  165. // a.Properties.Namespace != ""
  166. if filter.Value == UnallocatedSuffix {
  167. return valueToCompare != ""
  168. }
  169. if valueToCompare != filter.Value {
  170. return true
  171. }
  172. case FilterContains:
  173. if stringSlice, ok := valueToCompare.([]string); ok {
  174. if len(stringSlice) == 0 {
  175. return filter.Value == UnallocatedSuffix
  176. }
  177. for _, s := range stringSlice {
  178. if s == filter.Value {
  179. return true
  180. }
  181. }
  182. } else {
  183. log.Warnf("Allocation Filter: invalid 'contains' call for non-list filter value")
  184. }
  185. case FilterStartsWith:
  186. if toCompareMissing {
  187. return false
  188. }
  189. // We don't need special __unallocated__ logic here because a query
  190. // asking for "__unallocated__" won't have a wildcard and unallocated
  191. // properties are the empty string.
  192. s, ok := valueToCompare.(string)
  193. if !ok {
  194. log.Warnf("Allocation Filter: invalid 'startswith' call for field with unsupported type")
  195. return false
  196. }
  197. return strings.HasPrefix(s, filter.Value)
  198. case FilterContainsPrefix:
  199. if toCompareMissing {
  200. return false
  201. }
  202. // We don't need special __unallocated__ logic here because a query
  203. // asking for "__unallocated__" won't have a wildcard and unallocated
  204. // properties are the empty string.
  205. values, ok := valueToCompare.([]string)
  206. if !ok {
  207. log.Warnf("Allocation Filter: invalid '%s' call for field with unsupported type", FilterContainsPrefix)
  208. return false
  209. }
  210. for _, s := range values {
  211. if strings.HasPrefix(s, filter.Value) {
  212. return true
  213. }
  214. }
  215. return false
  216. default:
  217. log.Errorf("Allocation Filter: Unhandled filter op. This is a filter implementation error and requires immediate patching. Op: %s", filter.Op)
  218. return false
  219. }
  220. return false
  221. }
  222. func (and AllocationFilterAnd) Matches(a *Allocation) bool {
  223. filters := and.Filters
  224. if len(filters) == 0 {
  225. return true
  226. }
  227. for _, filter := range filters {
  228. if !filter.Matches(a) {
  229. return false
  230. }
  231. }
  232. return true
  233. }
  234. func (or AllocationFilterOr) Matches(a *Allocation) bool {
  235. filters := or.Filters
  236. if len(filters) == 0 {
  237. return true
  238. }
  239. for _, filter := range filters {
  240. if filter.Matches(a) {
  241. return true
  242. }
  243. }
  244. return false
  245. }