selector.go 26 KB

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