Skip to content

Commit

Permalink
Implement native object reference fetching
Browse files Browse the repository at this point in the history
Signed-off-by: Danil-Grigorev <danil.grigorev@suse.com>
  • Loading branch information
Danil-Grigorev committed Jun 5, 2024
1 parent 6ce3978 commit 3650406
Show file tree
Hide file tree
Showing 2 changed files with 205 additions and 4 deletions.
203 changes: 199 additions & 4 deletions kube-client/src/client/client_ext.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::{Client, Error, Result};
use k8s_openapi::api::core::v1::Namespace as k8sNs;
use k8s_openapi::{
api::core::v1::{Namespace as k8sNs, ObjectReference},
apimachinery::pkg::apis::meta::v1::OwnerReference,
};
use kube_core::{
object::ObjectList,
params::{GetParams, ListParams},
Expand Down Expand Up @@ -42,9 +45,72 @@ pub struct Cluster;
/// You can create this directly, or convert `From` a `String` / `&str`, or `TryFrom` an `k8s_openapi::api::core::v1::Namespace`
pub struct Namespace(String);

/// Referenced object name resolution
pub trait Reference<K>: ObjectUrl<K> {
fn name(&self) -> Option<&str>;
}

/// Ref provides a resolvable reference to an arbitrary object
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Ref<K: Resource> {
/// Type of the underlying object
pub dyntype: K::DynamicType,

/// Object reference
pub object_ref: ObjectReference,
}

impl<K> Ref<K>
where
K: Resource,
K::DynamicType: Default,
{
/// Construct a new Ref<K> from ObjectReference
pub fn new(object_ref: Option<ObjectReference>) -> Self {
Self {
object_ref: Self::resolve_ref(object_ref).unwrap_or_default(),
dyntype: K::DynamicType::default(),

Check warning on line 72 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L72

Added line #L72 was not covered by tests
}
}

/// Construct a new Ref<K> from OwnerReference
pub fn owner(owner: Option<OwnerReference>, ns: Option<String>) -> Self {

Check warning on line 77 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L77

Added line #L77 was not covered by tests
Self {
object_ref: Self::resolve_owner_ref(owner, ns).unwrap_or_default(),
dyntype: K::DynamicType::default(),

Check warning on line 80 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L79-L80

Added lines #L79 - L80 were not covered by tests
}
}

/// Perform validation on the owner reference against expected type
pub fn resolve_owner_ref(owner: Option<OwnerReference>, ns: Option<String>) -> Option<ObjectReference> {
let owner = owner?;

Check warning on line 86 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L85-L86

Added lines #L85 - L86 were not covered by tests
Self::resolve_ref(
ObjectReference {
name: owner.name.into(),
namespace: ns,
uid: owner.uid.into(),
api_version: owner.api_version.into(),
kind: owner.kind.into(),
..Default::default()

Check warning on line 94 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L88-L94

Added lines #L88 - L94 were not covered by tests
}
.into(),

Check warning on line 96 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L96

Added line #L96 was not covered by tests
)
}

/// Perform validation of the reference against the expected resource type
pub fn resolve_ref(object_ref: Option<ObjectReference>) -> Option<ObjectReference> {
let object_ref = object_ref?;
let api_version = object_ref.api_version.clone()?;
let kind = object_ref.kind.clone()?;
let valid = api_version == K::api_version(&K::DynamicType::default())
&& kind == K::kind(&K::DynamicType::default());
valid.then_some(object_ref)
}
}

/// Scopes for `unstable-client` [`Client#impl-Client`] extension methods
pub mod scope {
pub use super::{Cluster, Namespace};
pub use super::{Cluster, Namespace, Ref};
}

// All objects can be listed cluster-wide
Expand Down Expand Up @@ -93,6 +159,26 @@ where
}
}

impl<K> ObjectUrl<K> for Ref<K>
where
K: Resource,
K::DynamicType: Default,
{
fn url_path(&self) -> String {
K::url_path(&K::DynamicType::default(), self.object_ref.namespace.as_deref())
}
}

impl<K> Reference<K> for Ref<K>
where
K: Resource,
K::DynamicType: Default,
{
fn name(&self) -> Option<&str> {
self.object_ref.name.as_deref()
}
}

// can be created from a complete native object
impl TryFrom<&k8sNs> for Namespace {
type Error = NamespaceError;
Expand Down Expand Up @@ -184,6 +270,59 @@ impl Client {
self.request::<K>(req).await
}

/// Fetch a single instance of a `Resource` from a provided object reference.
///
/// ```no_run
/// # use k8s_openapi::api::rbac::v1::ClusterRole;
/// # use k8s_openapi::api::core::v1::Service;
/// # use k8s_openapi::api::core::v1::ObjectReference;
/// # use k8s_openapi::api::core::v1::{Node, Pod};
/// # use kube::client::scope::Ref;
/// # use kube::{Resource, ResourceExt, api::GetParams};
/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
/// # let client: kube::Client = todo!();
/// // cluster scoped
/// let cr: ClusterRole = client.fetch(&Ref::new(ObjectReference{
/// api_version: Some("rbac.authorization.k8s.io/v1".to_string()),
/// kind: Some("ClusterRole".to_string()),
/// name: Some("cluster-admin".to_string()),
/// ..Default::default()
/// }.into())).await?;
/// assert_eq!(cr.name_unchecked(), "cluster-admin");
/// // namespace scoped
/// let svc: Service = client.fetch(&Ref::new(ObjectReference{
/// api_version: Some("v1".to_string()),
/// kind: Some("Service".to_string()),
/// name: Some("kubernetes".to_string()),
/// namespace: Some("default".to_string()),
/// ..Default::default()
/// }.into())).await?;
/// assert_eq!(svc.name_unchecked(), "kubernetes");
/// // Fetch an owner of the resource
/// let pod: Pod = todo!();
/// let owner = pod
/// .owner_references()
/// .to_vec()
/// .into_iter()
/// .find(|r| r.kind == Node::kind(&()));
/// let node: Node = client.fetch(&Ref::owner(owner, None)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn fetch<K>(&self, reference: &impl Reference<K>) -> Result<K>
where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
{
self.get(
reference
.name()

Check warning on line 319 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L319

Added line #L319 was not covered by tests
.ok_or(Error::RefResolve("Reference is empty".to_string()))?,
reference,

Check warning on line 321 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L321

Added line #L321 was not covered by tests
)
.await
}

/// List instances of a `Resource` implementing type `K` at the specified scope.
///
/// ```no_run
Expand Down Expand Up @@ -219,10 +358,10 @@ impl Client {
#[cfg(test)]
mod test {
use super::{
scope::{Cluster, Namespace},
scope::{Cluster, Namespace, Ref},
Client, ListParams,
};
use kube_core::ResourceExt;
use kube_core::{Resource, ResourceExt};

#[tokio::test]
#[ignore = "needs cluster (will list/get namespaces, pods, jobs, svcs, clusterroles)"]
Expand Down Expand Up @@ -256,4 +395,60 @@ mod test {

Ok(())
}

#[tokio::test]
#[ignore = "needs cluster (will get svcs, clusterroles, pods, nodes)"]
async fn client_ext_fetch_ref_pods_svcs() -> Result<(), Box<dyn std::error::Error>> {
use k8s_openapi::api::{
core::v1::{Node, ObjectReference, Pod, Service},
rbac::v1::ClusterRole,
};

let client = Client::try_default().await?;
// namespaced fetch
let svc: Service = client
.fetch(&Ref::new(
ObjectReference {
kind: Some(Service::kind(&()).into()),
api_version: Some(Service::api_version(&()).into()),
name: Some("kubernetes".into()),
namespace: Some("default".into()),
..Default::default()
}
.into(),
))
.await?;
assert_eq!(svc.name_unchecked(), "kubernetes");
// global fetch
let ca: ClusterRole = client
.fetch(&Ref::new(
ObjectReference {
kind: Some(ClusterRole::kind(&()).into()),
api_version: Some(ClusterRole::api_version(&()).into()),
name: Some("cluster-admin".into()),
..Default::default()
}
.into(),
))
.await?;
assert_eq!(ca.name_unchecked(), "cluster-admin");

let kube_system: Namespace = "kube-system".into();
for pod in client
.list::<Pod>(
&ListParams::default().labels("component=kube-apiserver"),
&kube_system,
)
.await?
{
let owner = pod

Check warning on line 444 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L444

Added line #L444 was not covered by tests
.owner_references()
.to_vec()
.into_iter()
.find(|r| r.kind == Node::kind(&()));
let _: Node = client.fetch(&Ref::owner(owner, None)).await?;

Check warning on line 449 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L448-L449

Added lines #L448 - L449 were not covered by tests
}

Ok(())
}
}
6 changes: 6 additions & 0 deletions kube-client/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ pub enum Error {
#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
#[error("auth error: {0}")]
Auth(#[source] crate::client::AuthError),

/// Error resolving resource reference
#[cfg(feature = "unstable-client")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-client")))]
#[error("Reference resolve error: {0}")]
RefResolve(String),
}

#[derive(Error, Debug)]
Expand Down

0 comments on commit 3650406

Please sign in to comment.