Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store: Allow namespaced ObjectRefs to cluster-scoped objects #294

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions kube-runtime/src/reflector/object_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,23 @@ use std::{fmt::Debug, hash::Hash};
/// ```
pub struct ObjectRef<K: RuntimeResource> {
kind: K::State,
/// The name of the object
pub name: String,
/// The namespace of the object
///
/// May only be `None` if the kind is cluster-scoped (not located in a namespace).
/// Note that it *is* acceptable for an `ObjectRef` to a cluster-scoped resource to
/// have a namespace. These are, however, not considered equal:
///
/// ```
/// # use kube_runtime::reflector::ObjectRef;
/// # use k8s_openapi::api::core::v1::ConfigMap;
/// assert_ne!(ObjectRef::<ConfigMap>::new("foo"), ObjectRef::new("foo").within("bar"));
/// ```
pub namespace: Option<String>,
}

impl<K: Meta> ObjectRef<K> {
impl<K: Resource> ObjectRef<K> {
#[must_use]
pub fn new(name: &str) -> Self {
Self {
Expand All @@ -42,7 +54,10 @@ impl<K: Meta> ObjectRef<K> {
}

#[must_use]
pub fn from_obj(obj: &K) -> Self {
pub fn from_obj(obj: &K) -> Self
where
K: Meta,
{
Self {
kind: (),
name: obj.name(),
Expand Down
92 changes: 90 additions & 2 deletions kube-runtime/src/reflector/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,27 @@ pub struct Store<K: 'static + Resource> {
impl<K: 'static + Clone + Resource> Store<K> {
/// Retrieve a `clone()` of the entry referred to by `key`, if it is in the cache.
///
/// `key.namespace` is ignored for cluster-scoped resources.
///
/// Note that this is a cache and may be stale. Deleted objects may still exist in the cache
/// despite having been deleted in the cluster, and new objects may not yet exist in the cache.
/// If any of these are a problem for you then you should abort your reconciler and retry later.
/// If you use `kube_rt::controller` then you can do this by returning an error and specifying a
/// reasonable `error_policy`.
#[must_use]
pub fn get(&self, key: &ObjectRef<K>) -> Option<K> {
// Clone to let go of the entry lock ASAP
self.store.get(key).map(|entry| entry.value().clone())
self.store
.get(key)
// Try to erase the namespace and try again, in case the object is cluster-scoped
.or_else(|| {
self.store.get(&{
let mut cluster_key = key.clone();
cluster_key.namespace = None;
cluster_key
})
})
// Clone to let go of the entry lock ASAP
.map(|entry| entry.value().clone())
}

/// Return a full snapshot of the current values
Expand All @@ -84,3 +96,79 @@ impl<K: 'static + Clone + Resource> Store<K> {
self.store.iter().map(|eg| eg.value().clone()).collect()
}
}

#[cfg(test)]
mod tests {
use super::Writer;
use crate::{reflector::ObjectRef, watcher};
use k8s_openapi::api::core::v1::ConfigMap;
use kube::api::ObjectMeta;

#[test]
fn should_allow_getting_namespaced_object_by_namespaced_ref() {
let cm = ConfigMap {
metadata: ObjectMeta {
name: Some("obj".to_string()),
namespace: Some("ns".to_string()),
..ObjectMeta::default()
},
..ConfigMap::default()
};
let mut store_w = Writer::default();
store_w.apply_watcher_event(&watcher::Event::Applied(cm.clone()));
let store = store_w.as_reader();
assert_eq!(store.get(&ObjectRef::from_obj(&cm)), Some(cm));
}

#[test]
fn should_not_allow_getting_namespaced_object_by_clusterscoped_ref() {
let cm = ConfigMap {
metadata: ObjectMeta {
name: Some("obj".to_string()),
namespace: Some("ns".to_string()),
..ObjectMeta::default()
},
..ConfigMap::default()
};
let mut cluster_cm = cm.clone();
cluster_cm.metadata.namespace = None;
let mut store_w = Writer::default();
store_w.apply_watcher_event(&watcher::Event::Applied(cm.clone()));
let store = store_w.as_reader();
assert_eq!(store.get(&ObjectRef::from_obj(&cluster_cm)), None);
}

#[test]
fn should_allow_getting_clusterscoped_object_by_clusterscoped_ref() {
let cm = ConfigMap {
metadata: ObjectMeta {
name: Some("obj".to_string()),
namespace: None,
..ObjectMeta::default()
},
..ConfigMap::default()
};
let mut store_w = Writer::default();
store_w.apply_watcher_event(&watcher::Event::Applied(cm.clone()));
let store = store_w.as_reader();
assert_eq!(store.get(&ObjectRef::from_obj(&cm)), Some(cm));
}

#[test]
fn should_allow_getting_clusterscoped_object_by_namespaced_ref() {
let cm = ConfigMap {
metadata: ObjectMeta {
name: Some("obj".to_string()),
namespace: None,
..ObjectMeta::default()
},
..ConfigMap::default()
};
let mut nsed_cm = cm.clone();
nsed_cm.metadata.namespace = Some("ns".to_string());
let mut store_w = Writer::default();
store_w.apply_watcher_event(&watcher::Event::Applied(cm.clone()));
let store = store_w.as_reader();
assert_eq!(store.get(&ObjectRef::from_obj(&nsed_cm)), Some(cm));
}
}