selector.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package labels
  14. import (
  15. "fmt"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "github.com/google/go-cmp/cmp"
  20. "k8s.io/apimachinery/pkg/selection"
  21. "k8s.io/apimachinery/pkg/util/sets"
  22. "k8s.io/apimachinery/pkg/util/validation"
  23. "k8s.io/apimachinery/pkg/util/validation/field"
  24. "k8s.io/klog/v2"
  25. )
  26. var (
  27. validRequirementOperators = []string{
  28. string(selection.In), string(selection.NotIn),
  29. string(selection.Equals), string(selection.DoubleEquals), string(selection.NotEquals),
  30. string(selection.Exists), string(selection.DoesNotExist),
  31. string(selection.GreaterThan), string(selection.LessThan),
  32. }
  33. )
  34. // Requirements is AND of all requirements.
  35. type Requirements []Requirement
  36. // Selector represents a label selector.
  37. type Selector interface {
  38. // Matches returns true if this selector matches the given set of labels.
  39. Matches(Labels) bool
  40. // Empty returns true if this selector does not restrict the selection space.
  41. Empty() bool
  42. // String returns a human readable string that represents this selector.
  43. String() string
  44. // Add adds requirements to the Selector
  45. Add(r ...Requirement) Selector
  46. // Requirements converts this interface into Requirements to expose
  47. // more detailed selection information.
  48. // If there are querying parameters, it will return converted requirements and selectable=true.
  49. // If this selector doesn't want to select anything, it will return selectable=false.
  50. Requirements() (requirements Requirements, selectable bool)
  51. // Make a deep copy of the selector.
  52. DeepCopySelector() Selector
  53. // RequiresExactMatch allows a caller to introspect whether a given selector
  54. // requires a single specific label to be set, and if so returns the value it
  55. // requires.
  56. RequiresExactMatch(label string) (value string, found bool)
  57. }
  58. // Everything returns a selector that matches all labels.
  59. func Everything() Selector {
  60. return internalSelector{}
  61. }
  62. type nothingSelector struct{}
  63. func (n nothingSelector) Matches(_ Labels) bool { return false }
  64. func (n nothingSelector) Empty() bool { return false }
  65. func (n nothingSelector) String() string { return "" }
  66. func (n nothingSelector) Add(_ ...Requirement) Selector { return n }
  67. func (n nothingSelector) Requirements() (Requirements, bool) { return nil, false }
  68. func (n nothingSelector) DeepCopySelector() Selector { return n }
  69. func (n nothingSelector) RequiresExactMatch(label string) (value string, found bool) {
  70. return "", false
  71. }
  72. // Nothing returns a selector that matches no labels
  73. func Nothing() Selector {
  74. return nothingSelector{}
  75. }
  76. // NewSelector returns a nil selector
  77. func NewSelector() Selector {
  78. return internalSelector(nil)
  79. }
  80. type internalSelector []Requirement
  81. func (s internalSelector) DeepCopy() internalSelector {
  82. if s == nil {
  83. return nil
  84. }
  85. result := make([]Requirement, len(s))
  86. for i := range s {
  87. s[i].DeepCopyInto(&result[i])
  88. }
  89. return result
  90. }
  91. func (s internalSelector) DeepCopySelector() Selector {
  92. return s.DeepCopy()
  93. }
  94. // ByKey sorts requirements by key to obtain deterministic parser
  95. type ByKey []Requirement
  96. func (a ByKey) Len() int { return len(a) }
  97. func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  98. func (a ByKey) Less(i, j int) bool { return a[i].key < a[j].key }
  99. // Requirement contains values, a key, and an operator that relates the key and values.
  100. // The zero value of Requirement is invalid.
  101. // Requirement implements both set based match and exact match
  102. // Requirement should be initialized via NewRequirement constructor for creating a valid Requirement.
  103. // +k8s:deepcopy-gen=true
  104. type Requirement struct {
  105. key string
  106. operator selection.Operator
  107. // In huge majority of cases we have at most one value here.
  108. // It is generally faster to operate on a single-element slice
  109. // than on a single-element map, so we have a slice here.
  110. strValues []string
  111. }
  112. // NewRequirement is the constructor for a Requirement.
  113. // If any of these rules is violated, an error is returned:
  114. // (1) The operator can only be In, NotIn, Equals, DoubleEquals, NotEquals, Exists, or DoesNotExist.
  115. // (2) If the operator is In or NotIn, the values set must be non-empty.
  116. // (3) If the operator is Equals, DoubleEquals, or NotEquals, the values set must contain one value.
  117. // (4) If the operator is Exists or DoesNotExist, the value set must be empty.
  118. // (5) If the operator is Gt or Lt, the values set must contain only one value, which will be interpreted as an integer.
  119. // (6) The key is invalid due to its length, or sequence
  120. // of characters. See validateLabelKey for more details.
  121. //
  122. // The empty string is a valid value in the input values set.
  123. // Returned error, if not nil, is guaranteed to be an aggregated field.ErrorList
  124. func NewRequirement(key string, op selection.Operator, vals []string, opts ...field.PathOption) (*Requirement, error) {
  125. var allErrs field.ErrorList
  126. path := field.ToPath(opts...)
  127. if err := validateLabelKey(key, path.Child("key")); err != nil {
  128. allErrs = append(allErrs, err)
  129. }
  130. valuePath := path.Child("values")
  131. switch op {
  132. case selection.In, selection.NotIn:
  133. if len(vals) == 0 {
  134. allErrs = append(allErrs, field.Invalid(valuePath, vals, "for 'in', 'notin' operators, values set can't be empty"))
  135. }
  136. case selection.Equals, selection.DoubleEquals, selection.NotEquals:
  137. if len(vals) != 1 {
  138. allErrs = append(allErrs, field.Invalid(valuePath, vals, "exact-match compatibility requires one single value"))
  139. }
  140. case selection.Exists, selection.DoesNotExist:
  141. if len(vals) != 0 {
  142. allErrs = append(allErrs, field.Invalid(valuePath, vals, "values set must be empty for exists and does not exist"))
  143. }
  144. case selection.GreaterThan, selection.LessThan:
  145. if len(vals) != 1 {
  146. allErrs = append(allErrs, field.Invalid(valuePath, vals, "for 'Gt', 'Lt' operators, exactly one value is required"))
  147. }
  148. for i := range vals {
  149. if _, err := strconv.ParseInt(vals[i], 10, 64); err != nil {
  150. allErrs = append(allErrs, field.Invalid(valuePath.Index(i), vals[i], "for 'Gt', 'Lt' operators, the value must be an integer"))
  151. }
  152. }
  153. default:
  154. allErrs = append(allErrs, field.NotSupported(path.Child("operator"), op, validRequirementOperators))
  155. }
  156. for i := range vals {
  157. if err := validateLabelValue(key, vals[i], valuePath.Index(i)); err != nil {
  158. allErrs = append(allErrs, err)
  159. }
  160. }
  161. return &Requirement{key: key, operator: op, strValues: vals}, allErrs.ToAggregate()
  162. }
  163. func (r *Requirement) hasValue(value string) bool {
  164. for i := range r.strValues {
  165. if r.strValues[i] == value {
  166. return true
  167. }
  168. }
  169. return false
  170. }
  171. // Matches returns true if the Requirement matches the input Labels.
  172. // There is a match in the following cases:
  173. // (1) The operator is Exists and Labels has the Requirement's key.
  174. // (2) The operator is In, Labels has the Requirement's key and Labels'
  175. // value for that key is in Requirement's value set.
  176. // (3) The operator is NotIn, Labels has the Requirement's key and
  177. // Labels' value for that key is not in Requirement's value set.
  178. // (4) The operator is DoesNotExist or NotIn and Labels does not have the
  179. // Requirement's key.
  180. // (5) The operator is GreaterThanOperator or LessThanOperator, and Labels has
  181. // the Requirement's key and the corresponding value satisfies mathematical inequality.
  182. func (r *Requirement) Matches(ls Labels) bool {
  183. switch r.operator {
  184. case selection.In, selection.Equals, selection.DoubleEquals:
  185. if !ls.Has(r.key) {
  186. return false
  187. }
  188. return r.hasValue(ls.Get(r.key))
  189. case selection.NotIn, selection.NotEquals:
  190. if !ls.Has(r.key) {
  191. return true
  192. }
  193. return !r.hasValue(ls.Get(r.key))
  194. case selection.Exists:
  195. return ls.Has(r.key)
  196. case selection.DoesNotExist:
  197. return !ls.Has(r.key)
  198. case selection.GreaterThan, selection.LessThan:
  199. if !ls.Has(r.key) {
  200. return false
  201. }
  202. lsValue, err := strconv.ParseInt(ls.Get(r.key), 10, 64)
  203. if err != nil {
  204. klog.V(10).Infof("ParseInt failed for value %+v in label %+v, %+v", ls.Get(r.key), ls, err)
  205. return false
  206. }
  207. // There should be only one strValue in r.strValues, and can be converted to an integer.
  208. if len(r.strValues) != 1 {
  209. klog.V(10).Infof("Invalid values count %+v of requirement %#v, for 'Gt', 'Lt' operators, exactly one value is required", len(r.strValues), r)
  210. return false
  211. }
  212. var rValue int64
  213. for i := range r.strValues {
  214. rValue, err = strconv.ParseInt(r.strValues[i], 10, 64)
  215. if err != nil {
  216. klog.V(10).Infof("ParseInt failed for value %+v in requirement %#v, for 'Gt', 'Lt' operators, the value must be an integer", r.strValues[i], r)
  217. return false
  218. }
  219. }
  220. return (r.operator == selection.GreaterThan && lsValue > rValue) || (r.operator == selection.LessThan && lsValue < rValue)
  221. default:
  222. return false
  223. }
  224. }
  225. // Key returns requirement key
  226. func (r *Requirement) Key() string {
  227. return r.key
  228. }
  229. // Operator returns requirement operator
  230. func (r *Requirement) Operator() selection.Operator {
  231. return r.operator
  232. }
  233. // Values returns requirement values
  234. func (r *Requirement) Values() sets.String {
  235. ret := sets.String{}
  236. for i := range r.strValues {
  237. ret.Insert(r.strValues[i])
  238. }
  239. return ret
  240. }
  241. // Equal checks the equality of requirement.
  242. func (r Requirement) Equal(x Requirement) bool {
  243. if r.key != x.key {
  244. return false
  245. }
  246. if r.operator != x.operator {
  247. return false
  248. }
  249. return cmp.Equal(r.strValues, x.strValues)
  250. }
  251. // Empty returns true if the internalSelector doesn't restrict selection space
  252. func (s internalSelector) Empty() bool {
  253. if s == nil {
  254. return true
  255. }
  256. return len(s) == 0
  257. }
  258. // String returns a human-readable string that represents this
  259. // Requirement. If called on an invalid Requirement, an error is
  260. // returned. See NewRequirement for creating a valid Requirement.
  261. func (r *Requirement) String() string {
  262. var sb strings.Builder
  263. sb.Grow(
  264. // length of r.key
  265. len(r.key) +
  266. // length of 'r.operator' + 2 spaces for the worst case ('in' and 'notin')
  267. len(r.operator) + 2 +
  268. // length of 'r.strValues' slice times. Heuristically 5 chars per word
  269. +5*len(r.strValues))
  270. if r.operator == selection.DoesNotExist {
  271. sb.WriteString("!")
  272. }
  273. sb.WriteString(r.key)
  274. switch r.operator {
  275. case selection.Equals:
  276. sb.WriteString("=")
  277. case selection.DoubleEquals:
  278. sb.WriteString("==")
  279. case selection.NotEquals:
  280. sb.WriteString("!=")
  281. case selection.In:
  282. sb.WriteString(" in ")
  283. case selection.NotIn:
  284. sb.WriteString(" notin ")
  285. case selection.GreaterThan:
  286. sb.WriteString(">")
  287. case selection.LessThan:
  288. sb.WriteString("<")
  289. case selection.Exists, selection.DoesNotExist:
  290. return sb.String()
  291. }
  292. switch r.operator {
  293. case selection.In, selection.NotIn:
  294. sb.WriteString("(")
  295. }
  296. if len(r.strValues) == 1 {
  297. sb.WriteString(r.strValues[0])
  298. } else { // only > 1 since == 0 prohibited by NewRequirement
  299. // normalizes value order on output, without mutating the in-memory selector representation
  300. // also avoids normalization when it is not required, and ensures we do not mutate shared data
  301. sb.WriteString(strings.Join(safeSort(r.strValues), ","))
  302. }
  303. switch r.operator {
  304. case selection.In, selection.NotIn:
  305. sb.WriteString(")")
  306. }
  307. return sb.String()
  308. }
  309. // safeSort sorts input strings without modification
  310. func safeSort(in []string) []string {
  311. if sort.StringsAreSorted(in) {
  312. return in
  313. }
  314. out := make([]string, len(in))
  315. copy(out, in)
  316. sort.Strings(out)
  317. return out
  318. }
  319. // Add adds requirements to the selector. It copies the current selector returning a new one
  320. func (s internalSelector) Add(reqs ...Requirement) Selector {
  321. var ret internalSelector
  322. for ix := range s {
  323. ret = append(ret, s[ix])
  324. }
  325. for _, r := range reqs {
  326. ret = append(ret, r)
  327. }
  328. sort.Sort(ByKey(ret))
  329. return ret
  330. }
  331. // Matches for a internalSelector returns true if all
  332. // its Requirements match the input Labels. If any
  333. // Requirement does not match, false is returned.
  334. func (s internalSelector) Matches(l Labels) bool {
  335. for ix := range s {
  336. if matches := s[ix].Matches(l); !matches {
  337. return false
  338. }
  339. }
  340. return true
  341. }
  342. func (s internalSelector) Requirements() (Requirements, bool) { return Requirements(s), true }
  343. // String returns a comma-separated string of all
  344. // the internalSelector Requirements' human-readable strings.
  345. func (s internalSelector) String() string {
  346. var reqs []string
  347. for ix := range s {
  348. reqs = append(reqs, s[ix].String())
  349. }
  350. return strings.Join(reqs, ",")
  351. }
  352. // RequiresExactMatch introspects whether a given selector requires a single specific field
  353. // to be set, and if so returns the value it requires.
  354. func (s internalSelector) RequiresExactMatch(label string) (value string, found bool) {
  355. for ix := range s {
  356. if s[ix].key == label {
  357. switch s[ix].operator {
  358. case selection.Equals, selection.DoubleEquals, selection.In:
  359. if len(s[ix].strValues) == 1 {
  360. return s[ix].strValues[0], true
  361. }
  362. }
  363. return "", false
  364. }
  365. }
  366. return "", false
  367. }
  368. // Token represents constant definition for lexer token
  369. type Token int
  370. const (
  371. // ErrorToken represents scan error
  372. ErrorToken Token = iota
  373. // EndOfStringToken represents end of string
  374. EndOfStringToken
  375. // ClosedParToken represents close parenthesis
  376. ClosedParToken
  377. // CommaToken represents the comma
  378. CommaToken
  379. // DoesNotExistToken represents logic not
  380. DoesNotExistToken
  381. // DoubleEqualsToken represents double equals
  382. DoubleEqualsToken
  383. // EqualsToken represents equal
  384. EqualsToken
  385. // GreaterThanToken represents greater than
  386. GreaterThanToken
  387. // IdentifierToken represents identifier, e.g. keys and values
  388. IdentifierToken
  389. // InToken represents in
  390. InToken
  391. // LessThanToken represents less than
  392. LessThanToken
  393. // NotEqualsToken represents not equal
  394. NotEqualsToken
  395. // NotInToken represents not in
  396. NotInToken
  397. // OpenParToken represents open parenthesis
  398. OpenParToken
  399. )
  400. // string2token contains the mapping between lexer Token and token literal
  401. // (except IdentifierToken, EndOfStringToken and ErrorToken since it makes no sense)
  402. var string2token = map[string]Token{
  403. ")": ClosedParToken,
  404. ",": CommaToken,
  405. "!": DoesNotExistToken,
  406. "==": DoubleEqualsToken,
  407. "=": EqualsToken,
  408. ">": GreaterThanToken,
  409. "in": InToken,
  410. "<": LessThanToken,
  411. "!=": NotEqualsToken,
  412. "notin": NotInToken,
  413. "(": OpenParToken,
  414. }
  415. // ScannedItem contains the Token and the literal produced by the lexer.
  416. type ScannedItem struct {
  417. tok Token
  418. literal string
  419. }
  420. // isWhitespace returns true if the rune is a space, tab, or newline.
  421. func isWhitespace(ch byte) bool {
  422. return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'
  423. }
  424. // isSpecialSymbol detects if the character ch can be an operator
  425. func isSpecialSymbol(ch byte) bool {
  426. switch ch {
  427. case '=', '!', '(', ')', ',', '>', '<':
  428. return true
  429. }
  430. return false
  431. }
  432. // Lexer represents the Lexer struct for label selector.
  433. // It contains necessary informationt to tokenize the input string
  434. type Lexer struct {
  435. // s stores the string to be tokenized
  436. s string
  437. // pos is the position currently tokenized
  438. pos int
  439. }
  440. // read returns the character currently lexed
  441. // increment the position and check the buffer overflow
  442. func (l *Lexer) read() (b byte) {
  443. b = 0
  444. if l.pos < len(l.s) {
  445. b = l.s[l.pos]
  446. l.pos++
  447. }
  448. return b
  449. }
  450. // unread 'undoes' the last read character
  451. func (l *Lexer) unread() {
  452. l.pos--
  453. }
  454. // scanIDOrKeyword scans string to recognize literal token (for example 'in') or an identifier.
  455. func (l *Lexer) scanIDOrKeyword() (tok Token, lit string) {
  456. var buffer []byte
  457. IdentifierLoop:
  458. for {
  459. switch ch := l.read(); {
  460. case ch == 0:
  461. break IdentifierLoop
  462. case isSpecialSymbol(ch) || isWhitespace(ch):
  463. l.unread()
  464. break IdentifierLoop
  465. default:
  466. buffer = append(buffer, ch)
  467. }
  468. }
  469. s := string(buffer)
  470. if val, ok := string2token[s]; ok { // is a literal token?
  471. return val, s
  472. }
  473. return IdentifierToken, s // otherwise is an identifier
  474. }
  475. // scanSpecialSymbol scans string starting with special symbol.
  476. // special symbol identify non literal operators. "!=", "==", "="
  477. func (l *Lexer) scanSpecialSymbol() (Token, string) {
  478. lastScannedItem := ScannedItem{}
  479. var buffer []byte
  480. SpecialSymbolLoop:
  481. for {
  482. switch ch := l.read(); {
  483. case ch == 0:
  484. break SpecialSymbolLoop
  485. case isSpecialSymbol(ch):
  486. buffer = append(buffer, ch)
  487. if token, ok := string2token[string(buffer)]; ok {
  488. lastScannedItem = ScannedItem{tok: token, literal: string(buffer)}
  489. } else if lastScannedItem.tok != 0 {
  490. l.unread()
  491. break SpecialSymbolLoop
  492. }
  493. default:
  494. l.unread()
  495. break SpecialSymbolLoop
  496. }
  497. }
  498. if lastScannedItem.tok == 0 {
  499. return ErrorToken, fmt.Sprintf("error expected: keyword found '%s'", buffer)
  500. }
  501. return lastScannedItem.tok, lastScannedItem.literal
  502. }
  503. // skipWhiteSpaces consumes all blank characters
  504. // returning the first non blank character
  505. func (l *Lexer) skipWhiteSpaces(ch byte) byte {
  506. for {
  507. if !isWhitespace(ch) {
  508. return ch
  509. }
  510. ch = l.read()
  511. }
  512. }
  513. // Lex returns a pair of Token and the literal
  514. // literal is meaningfull only for IdentifierToken token
  515. func (l *Lexer) Lex() (tok Token, lit string) {
  516. switch ch := l.skipWhiteSpaces(l.read()); {
  517. case ch == 0:
  518. return EndOfStringToken, ""
  519. case isSpecialSymbol(ch):
  520. l.unread()
  521. return l.scanSpecialSymbol()
  522. default:
  523. l.unread()
  524. return l.scanIDOrKeyword()
  525. }
  526. }
  527. // Parser data structure contains the label selector parser data structure
  528. type Parser struct {
  529. l *Lexer
  530. scannedItems []ScannedItem
  531. position int
  532. path *field.Path
  533. }
  534. // ParserContext represents context during parsing:
  535. // some literal for example 'in' and 'notin' can be
  536. // recognized as operator for example 'x in (a)' but
  537. // it can be recognized as value for example 'value in (in)'
  538. type ParserContext int
  539. const (
  540. // KeyAndOperator represents key and operator
  541. KeyAndOperator ParserContext = iota
  542. // Values represents values
  543. Values
  544. )
  545. // lookahead func returns the current token and string. No increment of current position
  546. func (p *Parser) lookahead(context ParserContext) (Token, string) {
  547. tok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal
  548. if context == Values {
  549. switch tok {
  550. case InToken, NotInToken:
  551. tok = IdentifierToken
  552. }
  553. }
  554. return tok, lit
  555. }
  556. // consume returns current token and string. Increments the position
  557. func (p *Parser) consume(context ParserContext) (Token, string) {
  558. p.position++
  559. tok, lit := p.scannedItems[p.position-1].tok, p.scannedItems[p.position-1].literal
  560. if context == Values {
  561. switch tok {
  562. case InToken, NotInToken:
  563. tok = IdentifierToken
  564. }
  565. }
  566. return tok, lit
  567. }
  568. // scan runs through the input string and stores the ScannedItem in an array
  569. // Parser can now lookahead and consume the tokens
  570. func (p *Parser) scan() {
  571. for {
  572. token, literal := p.l.Lex()
  573. p.scannedItems = append(p.scannedItems, ScannedItem{token, literal})
  574. if token == EndOfStringToken {
  575. break
  576. }
  577. }
  578. }
  579. // parse runs the left recursive descending algorithm
  580. // on input string. It returns a list of Requirement objects.
  581. func (p *Parser) parse() (internalSelector, error) {
  582. p.scan() // init scannedItems
  583. var requirements internalSelector
  584. for {
  585. tok, lit := p.lookahead(Values)
  586. switch tok {
  587. case IdentifierToken, DoesNotExistToken:
  588. r, err := p.parseRequirement()
  589. if err != nil {
  590. return nil, fmt.Errorf("unable to parse requirement: %v", err)
  591. }
  592. requirements = append(requirements, *r)
  593. t, l := p.consume(Values)
  594. switch t {
  595. case EndOfStringToken:
  596. return requirements, nil
  597. case CommaToken:
  598. t2, l2 := p.lookahead(Values)
  599. if t2 != IdentifierToken && t2 != DoesNotExistToken {
  600. return nil, fmt.Errorf("found '%s', expected: identifier after ','", l2)
  601. }
  602. default:
  603. return nil, fmt.Errorf("found '%s', expected: ',' or 'end of string'", l)
  604. }
  605. case EndOfStringToken:
  606. return requirements, nil
  607. default:
  608. return nil, fmt.Errorf("found '%s', expected: !, identifier, or 'end of string'", lit)
  609. }
  610. }
  611. }
  612. func (p *Parser) parseRequirement() (*Requirement, error) {
  613. key, operator, err := p.parseKeyAndInferOperator()
  614. if err != nil {
  615. return nil, err
  616. }
  617. if operator == selection.Exists || operator == selection.DoesNotExist { // operator found lookahead set checked
  618. return NewRequirement(key, operator, []string{}, field.WithPath(p.path))
  619. }
  620. operator, err = p.parseOperator()
  621. if err != nil {
  622. return nil, err
  623. }
  624. var values sets.String
  625. switch operator {
  626. case selection.In, selection.NotIn:
  627. values, err = p.parseValues()
  628. case selection.Equals, selection.DoubleEquals, selection.NotEquals, selection.GreaterThan, selection.LessThan:
  629. values, err = p.parseExactValue()
  630. }
  631. if err != nil {
  632. return nil, err
  633. }
  634. return NewRequirement(key, operator, values.List(), field.WithPath(p.path))
  635. }
  636. // parseKeyAndInferOperator parses literals.
  637. // in case of no operator '!, in, notin, ==, =, !=' are found
  638. // the 'exists' operator is inferred
  639. func (p *Parser) parseKeyAndInferOperator() (string, selection.Operator, error) {
  640. var operator selection.Operator
  641. tok, literal := p.consume(Values)
  642. if tok == DoesNotExistToken {
  643. operator = selection.DoesNotExist
  644. tok, literal = p.consume(Values)
  645. }
  646. if tok != IdentifierToken {
  647. err := fmt.Errorf("found '%s', expected: identifier", literal)
  648. return "", "", err
  649. }
  650. if err := validateLabelKey(literal, p.path); err != nil {
  651. return "", "", err
  652. }
  653. if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {
  654. if operator != selection.DoesNotExist {
  655. operator = selection.Exists
  656. }
  657. }
  658. return literal, operator, nil
  659. }
  660. // parseOperator returns operator and eventually matchType
  661. // matchType can be exact
  662. func (p *Parser) parseOperator() (op selection.Operator, err error) {
  663. tok, lit := p.consume(KeyAndOperator)
  664. switch tok {
  665. // DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator
  666. case InToken:
  667. op = selection.In
  668. case EqualsToken:
  669. op = selection.Equals
  670. case DoubleEqualsToken:
  671. op = selection.DoubleEquals
  672. case GreaterThanToken:
  673. op = selection.GreaterThan
  674. case LessThanToken:
  675. op = selection.LessThan
  676. case NotInToken:
  677. op = selection.NotIn
  678. case NotEqualsToken:
  679. op = selection.NotEquals
  680. default:
  681. return "", fmt.Errorf("found '%s', expected: '=', '!=', '==', 'in', notin'", lit)
  682. }
  683. return op, nil
  684. }
  685. // parseValues parses the values for set based matching (x,y,z)
  686. func (p *Parser) parseValues() (sets.String, error) {
  687. tok, lit := p.consume(Values)
  688. if tok != OpenParToken {
  689. return nil, fmt.Errorf("found '%s' expected: '('", lit)
  690. }
  691. tok, lit = p.lookahead(Values)
  692. switch tok {
  693. case IdentifierToken, CommaToken:
  694. s, err := p.parseIdentifiersList() // handles general cases
  695. if err != nil {
  696. return s, err
  697. }
  698. if tok, _ = p.consume(Values); tok != ClosedParToken {
  699. return nil, fmt.Errorf("found '%s', expected: ')'", lit)
  700. }
  701. return s, nil
  702. case ClosedParToken: // handles "()"
  703. p.consume(Values)
  704. return sets.NewString(""), nil
  705. default:
  706. return nil, fmt.Errorf("found '%s', expected: ',', ')' or identifier", lit)
  707. }
  708. }
  709. // parseIdentifiersList parses a (possibly empty) list of
  710. // of comma separated (possibly empty) identifiers
  711. func (p *Parser) parseIdentifiersList() (sets.String, error) {
  712. s := sets.NewString()
  713. for {
  714. tok, lit := p.consume(Values)
  715. switch tok {
  716. case IdentifierToken:
  717. s.Insert(lit)
  718. tok2, lit2 := p.lookahead(Values)
  719. switch tok2 {
  720. case CommaToken:
  721. continue
  722. case ClosedParToken:
  723. return s, nil
  724. default:
  725. return nil, fmt.Errorf("found '%s', expected: ',' or ')'", lit2)
  726. }
  727. case CommaToken: // handled here since we can have "(,"
  728. if s.Len() == 0 {
  729. s.Insert("") // to handle (,
  730. }
  731. tok2, _ := p.lookahead(Values)
  732. if tok2 == ClosedParToken {
  733. s.Insert("") // to handle ,) Double "" removed by StringSet
  734. return s, nil
  735. }
  736. if tok2 == CommaToken {
  737. p.consume(Values)
  738. s.Insert("") // to handle ,, Double "" removed by StringSet
  739. }
  740. default: // it can be operator
  741. return s, fmt.Errorf("found '%s', expected: ',', or identifier", lit)
  742. }
  743. }
  744. }
  745. // parseExactValue parses the only value for exact match style
  746. func (p *Parser) parseExactValue() (sets.String, error) {
  747. s := sets.NewString()
  748. tok, _ := p.lookahead(Values)
  749. if tok == EndOfStringToken || tok == CommaToken {
  750. s.Insert("")
  751. return s, nil
  752. }
  753. tok, lit := p.consume(Values)
  754. if tok == IdentifierToken {
  755. s.Insert(lit)
  756. return s, nil
  757. }
  758. return nil, fmt.Errorf("found '%s', expected: identifier", lit)
  759. }
  760. // Parse takes a string representing a selector and returns a selector
  761. // object, or an error. This parsing function differs from ParseSelector
  762. // as they parse different selectors with different syntaxes.
  763. // The input will cause an error if it does not follow this form:
  764. //
  765. // <selector-syntax> ::= <requirement> | <requirement> "," <selector-syntax>
  766. // <requirement> ::= [!] KEY [ <set-based-restriction> | <exact-match-restriction> ]
  767. // <set-based-restriction> ::= "" | <inclusion-exclusion> <value-set>
  768. // <inclusion-exclusion> ::= <inclusion> | <exclusion>
  769. // <exclusion> ::= "notin"
  770. // <inclusion> ::= "in"
  771. // <value-set> ::= "(" <values> ")"
  772. // <values> ::= VALUE | VALUE "," <values>
  773. // <exact-match-restriction> ::= ["="|"=="|"!="] VALUE
  774. //
  775. // KEY is a sequence of one or more characters following [ DNS_SUBDOMAIN "/" ] DNS_LABEL. Max length is 63 characters.
  776. // VALUE is a sequence of zero or more characters "([A-Za-z0-9_-\.])". Max length is 63 characters.
  777. // Delimiter is white space: (' ', '\t')
  778. // Example of valid syntax:
  779. // "x in (foo,,baz),y,z notin ()"
  780. //
  781. // Note:
  782. // (1) Inclusion - " in " - denotes that the KEY exists and is equal to any of the
  783. // VALUEs in its requirement
  784. // (2) Exclusion - " notin " - denotes that the KEY is not equal to any
  785. // of the VALUEs in its requirement or does not exist
  786. // (3) The empty string is a valid VALUE
  787. // (4) A requirement with just a KEY - as in "y" above - denotes that
  788. // the KEY exists and can be any VALUE.
  789. // (5) A requirement with just !KEY requires that the KEY not exist.
  790. //
  791. func Parse(selector string, opts ...field.PathOption) (Selector, error) {
  792. parsedSelector, err := parse(selector, field.ToPath(opts...))
  793. if err == nil {
  794. return parsedSelector, nil
  795. }
  796. return nil, err
  797. }
  798. // parse parses the string representation of the selector and returns the internalSelector struct.
  799. // The callers of this method can then decide how to return the internalSelector struct to their
  800. // callers. This function has two callers now, one returns a Selector interface and the other
  801. // returns a list of requirements.
  802. func parse(selector string, path *field.Path) (internalSelector, error) {
  803. p := &Parser{l: &Lexer{s: selector, pos: 0}, path: path}
  804. items, err := p.parse()
  805. if err != nil {
  806. return nil, err
  807. }
  808. sort.Sort(ByKey(items)) // sort to grant determistic parsing
  809. return internalSelector(items), err
  810. }
  811. func validateLabelKey(k string, path *field.Path) *field.Error {
  812. if errs := validation.IsQualifiedName(k); len(errs) != 0 {
  813. return field.Invalid(path, k, strings.Join(errs, "; "))
  814. }
  815. return nil
  816. }
  817. func validateLabelValue(k, v string, path *field.Path) *field.Error {
  818. if errs := validation.IsValidLabelValue(v); len(errs) != 0 {
  819. return field.Invalid(path.Key(k), v, strings.Join(errs, "; "))
  820. }
  821. return nil
  822. }
  823. // SelectorFromSet returns a Selector which will match exactly the given Set. A
  824. // nil and empty Sets are considered equivalent to Everything().
  825. // It does not perform any validation, which means the server will reject
  826. // the request if the Set contains invalid values.
  827. func SelectorFromSet(ls Set) Selector {
  828. return SelectorFromValidatedSet(ls)
  829. }
  830. // ValidatedSelectorFromSet returns a Selector which will match exactly the given Set. A
  831. // nil and empty Sets are considered equivalent to Everything().
  832. // The Set is validated client-side, which allows to catch errors early.
  833. func ValidatedSelectorFromSet(ls Set) (Selector, error) {
  834. if ls == nil || len(ls) == 0 {
  835. return internalSelector{}, nil
  836. }
  837. requirements := make([]Requirement, 0, len(ls))
  838. for label, value := range ls {
  839. r, err := NewRequirement(label, selection.Equals, []string{value})
  840. if err != nil {
  841. return nil, err
  842. }
  843. requirements = append(requirements, *r)
  844. }
  845. // sort to have deterministic string representation
  846. sort.Sort(ByKey(requirements))
  847. return internalSelector(requirements), nil
  848. }
  849. // SelectorFromValidatedSet returns a Selector which will match exactly the given Set.
  850. // A nil and empty Sets are considered equivalent to Everything().
  851. // It assumes that Set is already validated and doesn't do any validation.
  852. func SelectorFromValidatedSet(ls Set) Selector {
  853. if ls == nil || len(ls) == 0 {
  854. return internalSelector{}
  855. }
  856. requirements := make([]Requirement, 0, len(ls))
  857. for label, value := range ls {
  858. requirements = append(requirements, Requirement{key: label, operator: selection.Equals, strValues: []string{value}})
  859. }
  860. // sort to have deterministic string representation
  861. sort.Sort(ByKey(requirements))
  862. return internalSelector(requirements)
  863. }
  864. // ParseToRequirements takes a string representing a selector and returns a list of
  865. // requirements. This function is suitable for those callers that perform additional
  866. // processing on selector requirements.
  867. // See the documentation for Parse() function for more details.
  868. // TODO: Consider exporting the internalSelector type instead.
  869. func ParseToRequirements(selector string, opts ...field.PathOption) ([]Requirement, error) {
  870. return parse(selector, field.ToPath(opts...))
  871. }