selector.go 25 KB

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