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