1use core::fmt;
3use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, LabelSelectorRequirement};
4use serde::{Deserialize, Serialize};
5use std::{
6 cmp::PartialEq,
7 collections::{BTreeMap, BTreeSet},
8 fmt::Display,
9 iter::FromIterator,
10 option::IntoIter,
11};
12use thiserror::Error;
13
14mod private {
15 pub trait Sealed {}
16 impl Sealed for super::Expression {}
17 impl Sealed for super::Selector {}
18}
19
20#[derive(Debug, Error)]
21#[error("failed to parse value as expression: {0}")]
22pub struct ParseExpressionError(pub String);
24
25type Expressions = Vec<Expression>;
27
28pub trait SelectorExt: private::Sealed {
30 type Search;
32
33 fn matches(&self, on: &Self::Search) -> bool;
46}
47
48#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
50pub enum Expression {
51 In(String, BTreeSet<String>),
61
62 NotIn(String, BTreeSet<String>),
72
73 Equal(String, String),
81
82 NotEqual(String, String),
90
91 Exists(String),
99
100 DoesNotExist(String),
108}
109
110#[derive(Clone, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
114pub struct Selector(Expressions);
115
116impl Selector {
117 fn from_expressions(exprs: Expressions) -> Self {
119 Self(exprs)
120 }
121
122 fn from_map(map: BTreeMap<String, String>) -> Self {
124 Self(map.into_iter().map(|(k, v)| Expression::Equal(k, v)).collect())
125 }
126
127 pub fn selects_all(&self) -> bool {
129 self.0.is_empty()
130 }
131
132 pub fn extend(&mut self, exprs: impl IntoIterator<Item = Expression>) -> &mut Self {
150 self.0.extend(exprs);
151 self
152 }
153}
154
155impl SelectorExt for Selector {
156 type Search = BTreeMap<String, String>;
157
158 fn matches(&self, labels: &BTreeMap<String, String>) -> bool {
160 for expr in self.0.iter() {
161 if !expr.matches(labels) {
162 return false;
163 }
164 }
165 true
166 }
167}
168
169impl SelectorExt for Expression {
170 type Search = BTreeMap<String, String>;
171
172 fn matches(&self, labels: &BTreeMap<String, String>) -> bool {
173 match self {
174 Expression::In(key, values) => match labels.get(key) {
175 Some(v) => values.contains(v),
176 None => false,
177 },
178 Expression::NotIn(key, values) => match labels.get(key) {
179 Some(v) => !values.contains(v),
180 None => true,
181 },
182 Expression::Exists(key) => labels.contains_key(key),
183 Expression::DoesNotExist(key) => !labels.contains_key(key),
184 Expression::Equal(key, value) => labels.get(key) == Some(value),
185 Expression::NotEqual(key, value) => labels.get(key) != Some(value),
186 }
187 }
188}
189
190impl Display for Expression {
191 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 match self {
194 Expression::In(key, values) => {
195 write!(
196 f,
197 "{key} in ({})",
198 values.iter().cloned().collect::<Vec<_>>().join(",")
199 )
200 }
201 Expression::NotIn(key, values) => {
202 write!(
203 f,
204 "{key} notin ({})",
205 values.iter().cloned().collect::<Vec<_>>().join(",")
206 )
207 }
208 Expression::Equal(key, value) => write!(f, "{key}={value}"),
209 Expression::NotEqual(key, value) => write!(f, "{key}!={value}"),
210 Expression::Exists(key) => write!(f, "{key}"),
211 Expression::DoesNotExist(key) => write!(f, "!{key}"),
212 }
213 }
214}
215
216impl Display for Selector {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 let selectors: Vec<String> = self.0.iter().map(|e| e.to_string()).collect();
220 write!(f, "{}", selectors.join(","))
221 }
222}
223impl IntoIterator for Expression {
226 type IntoIter = IntoIter<Self::Item>;
227 type Item = Self;
228
229 fn into_iter(self) -> Self::IntoIter {
230 Some(self).into_iter()
231 }
232}
233
234impl IntoIterator for Selector {
235 type IntoIter = std::vec::IntoIter<Self::Item>;
236 type Item = Expression;
237
238 fn into_iter(self) -> Self::IntoIter {
239 self.0.into_iter()
240 }
241}
242
243impl FromIterator<(String, String)> for Selector {
244 fn from_iter<T: IntoIterator<Item = (String, String)>>(iter: T) -> Self {
245 Self::from_map(iter.into_iter().collect())
246 }
247}
248
249impl FromIterator<(&'static str, &'static str)> for Selector {
250 fn from_iter<T: IntoIterator<Item = (&'static str, &'static str)>>(iter: T) -> Self {
258 Self::from_map(
259 iter.into_iter()
260 .map(|(k, v)| (k.to_string(), v.to_string()))
261 .collect(),
262 )
263 }
264}
265
266impl FromIterator<Expression> for Selector {
267 fn from_iter<T: IntoIterator<Item = Expression>>(iter: T) -> Self {
268 Self::from_expressions(iter.into_iter().collect())
269 }
270}
271
272impl From<Expression> for Selector {
273 fn from(value: Expression) -> Self {
274 Self(vec![value])
275 }
276}
277
278impl TryFrom<LabelSelector> for Selector {
279 type Error = ParseExpressionError;
280
281 fn try_from(value: LabelSelector) -> Result<Self, Self::Error> {
282 let expressions = match value.match_expressions {
283 Some(requirements) => requirements.into_iter().map(TryInto::try_into).collect(),
284 None => Ok(vec![]),
285 }?;
286 let mut equality: Selector = value
287 .match_labels
288 .map(|labels| labels.into_iter().collect())
289 .unwrap_or_default();
290 equality.extend(expressions);
291 Ok(equality)
292 }
293}
294
295impl TryFrom<LabelSelectorRequirement> for Expression {
296 type Error = ParseExpressionError;
297
298 fn try_from(requirement: LabelSelectorRequirement) -> Result<Self, Self::Error> {
299 let key = requirement.key;
300 let values = requirement.values.map(|values| values.into_iter().collect());
301 match requirement.operator.as_str() {
302 "In" => match values {
303 Some(values) => Ok(Expression::In(key, values)),
304 None => Err(ParseExpressionError(
305 "Expected values for In operator, got none".into(),
306 )),
307 },
308 "NotIn" => match values {
309 Some(values) => Ok(Expression::NotIn(key, values)),
310 None => Err(ParseExpressionError(
311 "Expected values for NotIn operator, got none".into(),
312 )),
313 },
314 "Exists" => Ok(Expression::Exists(key)),
315 "DoesNotExist" => Ok(Expression::DoesNotExist(key)),
316 "" => Err(ParseExpressionError("Missing expression operator".into())),
317 _ => Err(ParseExpressionError("Invalid expression operator".into())),
318 }
319 }
320}
321
322impl From<Selector> for LabelSelector {
323 fn from(value: Selector) -> Self {
324 let mut equality = vec![];
325 let mut expressions = vec![];
326 for expr in value.0 {
327 match expr {
328 Expression::In(key, values) => expressions.push(LabelSelectorRequirement {
329 key,
330 operator: "In".into(),
331 values: Some(values.into_iter().collect()),
332 }),
333 Expression::NotIn(key, values) => expressions.push(LabelSelectorRequirement {
334 key,
335 operator: "NotIn".into(),
336 values: Some(values.into_iter().collect()),
337 }),
338 Expression::Equal(key, value) => equality.push((key, value)),
339 Expression::NotEqual(key, value) => expressions.push(LabelSelectorRequirement {
340 key,
341 operator: "NotIn".into(),
342 values: Some(vec![value]),
343 }),
344 Expression::Exists(key) => expressions.push(LabelSelectorRequirement {
345 key,
346 operator: "Exists".into(),
347 values: None,
348 }),
349 Expression::DoesNotExist(key) => expressions.push(LabelSelectorRequirement {
350 key,
351 operator: "DoesNotExist".into(),
352 values: None,
353 }),
354 }
355 }
356
357 LabelSelector {
358 match_labels: (!equality.is_empty()).then_some(equality.into_iter().collect()),
359 match_expressions: (!expressions.is_empty()).then_some(expressions),
360 }
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use std::iter::FromIterator;
368
369 #[test]
370 fn test_raw_matches() {
371 for (selector, label_selector, labels, matches, msg) in &[
372 (
373 Selector::default(),
374 LabelSelector::default(),
375 Default::default(),
376 true,
377 "empty match",
378 ),
379 (
380 Selector::from_iter(Some(("foo", "bar"))),
381 LabelSelector {
382 match_labels: Some([("foo".into(), "bar".into())].into()),
383 match_expressions: Default::default(),
384 },
385 [("foo".to_string(), "bar".to_string())].into(),
386 true,
387 "exact label match",
388 ),
389 (
390 Selector::from_iter(Some(("foo", "bar"))),
391 LabelSelector {
392 match_labels: Some([("foo".to_string(), "bar".to_string())].into()),
393 match_expressions: None,
394 },
395 [
396 ("foo".to_string(), "bar".to_string()),
397 ("bah".to_string(), "baz".to_string()),
398 ]
399 .into(),
400 true,
401 "sufficient label match",
402 ),
403 (
404 Selector::from_iter(Some(Expression::In(
405 "foo".into(),
406 Some("bar".to_string()).into_iter().collect(),
407 ))),
408 LabelSelector {
409 match_labels: None,
410 match_expressions: Some(vec![LabelSelectorRequirement {
411 key: "foo".into(),
412 operator: "In".to_string(),
413 values: Some(vec!["bar".into()]),
414 }]),
415 },
416 [
417 ("foo".to_string(), "bar".to_string()),
418 ("bah".to_string(), "baz".to_string()),
419 ]
420 .into(),
421 true,
422 "In expression match",
423 ),
424 (
425 Selector::from_iter(Some(Expression::Equal(
426 "foo".into(),
427 Some("bar".to_string()).into_iter().collect(),
428 ))),
429 LabelSelector {
430 match_labels: Some([("foo".into(), "bar".into())].into()),
431 match_expressions: None,
432 },
433 [
434 ("foo".to_string(), "bar".to_string()),
435 ("bah".to_string(), "baz".to_string()),
436 ]
437 .into(),
438 true,
439 "Equal expression match",
440 ),
441 (
442 Selector::from_iter(Some(Expression::NotEqual(
443 "foo".into(),
444 Some("bar".to_string()).into_iter().collect(),
445 ))),
446 LabelSelector {
447 match_labels: None,
448 match_expressions: Some(vec![LabelSelectorRequirement {
449 key: "foo".into(),
450 operator: "NotIn".into(),
451 values: Some(vec!["bar".into()]),
452 }]),
453 },
454 [
455 ("foo".to_string(), "bar".to_string()),
456 ("bah".to_string(), "baz".to_string()),
457 ]
458 .into(),
459 false,
460 "NotEqual expression match",
461 ),
462 (
463 Selector::from_iter(Some(Expression::In(
464 "foo".into(),
465 Some("bar".to_string()).into_iter().collect(),
466 ))),
467 LabelSelector {
468 match_labels: None,
469 match_expressions: Some(vec![LabelSelectorRequirement {
470 key: "foo".into(),
471 operator: "In".into(),
472 values: Some(vec!["bar".into()]),
473 }]),
474 },
475 [
476 ("foo".to_string(), "bar".to_string()),
477 ("bah".to_string(), "baz".to_string()),
478 ]
479 .into(),
480 true,
481 "In expression match",
482 ),
483 (
484 Selector::from_iter(Some(Expression::NotIn(
485 "foo".into(),
486 Some("quux".to_string()).into_iter().collect(),
487 ))),
488 LabelSelector {
489 match_labels: None,
490 match_expressions: Some(vec![LabelSelectorRequirement {
491 key: "foo".into(),
492 operator: "NotIn".into(),
493 values: Some(vec!["quux".into()]),
494 }]),
495 },
496 [
497 ("foo".to_string(), "bar".to_string()),
498 ("bah".to_string(), "baz".to_string()),
499 ]
500 .into(),
501 true,
502 "NotIn expression match",
503 ),
504 (
505 Selector::from_iter(Some(Expression::NotIn(
506 "foo".into(),
507 Some("bar".to_string()).into_iter().collect(),
508 ))),
509 LabelSelector {
510 match_labels: None,
511 match_expressions: Some(vec![LabelSelectorRequirement {
512 key: "foo".into(),
513 operator: "NotIn".into(),
514 values: Some(vec!["bar".into()]),
515 }]),
516 },
517 [
518 ("foo".to_string(), "bar".to_string()),
519 ("bah".to_string(), "baz".to_string()),
520 ]
521 .into(),
522 false,
523 "NotIn expression non-match",
524 ),
525 (
526 Selector(vec![
527 Expression::Equal("foo".to_string(), "bar".to_string()),
528 Expression::In("bah".into(), Some("bar".to_string()).into_iter().collect()),
529 ]),
530 LabelSelector {
531 match_labels: Some([("foo".into(), "bar".into())].into()),
532 match_expressions: Some(vec![LabelSelectorRequirement {
533 key: "bah".into(),
534 operator: "In".into(),
535 values: Some(vec!["bar".into()]),
536 }]),
537 },
538 [
539 ("foo".to_string(), "bar".to_string()),
540 ("bah".to_string(), "baz".to_string()),
541 ]
542 .into(),
543 false,
544 "matches labels but not expressions",
545 ),
546 (
547 Selector(vec![
548 Expression::Equal("foo".to_string(), "bar".to_string()),
549 Expression::In("bah".into(), Some("bar".to_string()).into_iter().collect()),
550 ]),
551 LabelSelector {
552 match_labels: Some([("foo".into(), "bar".into())].into()),
553 match_expressions: Some(vec![LabelSelectorRequirement {
554 key: "bah".into(),
555 operator: "In".into(),
556 values: Some(vec!["bar".into()]),
557 }]),
558 },
559 [
560 ("foo".to_string(), "bar".to_string()),
561 ("bah".to_string(), "bar".to_string()),
562 ]
563 .into(),
564 true,
565 "matches both labels and expressions",
566 ),
567 ] {
568 assert_eq!(selector.matches(labels), *matches, "{}", msg);
569 let converted: LabelSelector = selector.clone().into();
570 assert_eq!(&converted, label_selector);
571 let converted_selector: Selector = converted.try_into().unwrap();
572 assert_eq!(
573 converted_selector.matches(labels),
574 *matches,
575 "After conversion: {}",
576 msg
577 );
578 }
579 }
580
581 #[test]
582 fn test_label_selector_matches() {
583 let selector: Selector = LabelSelector {
584 match_expressions: Some(vec![
585 LabelSelectorRequirement {
586 key: "foo".into(),
587 operator: "In".into(),
588 values: Some(vec!["bar".into()]),
589 },
590 LabelSelectorRequirement {
591 key: "foo".into(),
592 operator: "NotIn".into(),
593 values: Some(vec!["baz".into()]),
594 },
595 LabelSelectorRequirement {
596 key: "foo".into(),
597 operator: "Exists".into(),
598 values: None,
599 },
600 LabelSelectorRequirement {
601 key: "baz".into(),
602 operator: "DoesNotExist".into(),
603 values: None,
604 },
605 ]),
606 match_labels: Some([("foo".into(), "bar".into())].into()),
607 }
608 .try_into()
609 .unwrap();
610 assert!(selector.matches(&[("foo".into(), "bar".into())].into()));
611 assert!(!selector.matches(&Default::default()));
612 }
613
614 #[test]
615 fn test_to_string() {
616 let selector = Selector(vec![
617 Expression::In("foo".into(), ["bar".into(), "baz".into()].into()),
618 Expression::NotIn("foo".into(), ["bar".into(), "baz".into()].into()),
619 Expression::Equal("foo".into(), "bar".into()),
620 Expression::NotEqual("foo".into(), "bar".into()),
621 Expression::Exists("foo".into()),
622 Expression::DoesNotExist("foo".into()),
623 ])
624 .to_string();
625
626 assert_eq!(
627 selector,
628 "foo in (bar,baz),foo notin (bar,baz),foo=bar,foo!=bar,foo,!foo"
629 )
630 }
631}