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 <[email protected]>
  • Loading branch information
Danil-Grigorev committed Jun 6, 2024
1 parent 5aa8f83 commit 3aad40b
Show file tree
Hide file tree
Showing 2 changed files with 192 additions and 3 deletions.
189 changes: 186 additions & 3 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,92 @@ 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 ObjectRef<K>: ObjectUrl<K> {
fn name(&self) -> Option<&str>;
}

/// Reference resolver for a specified namespace
pub trait NamespacedRef<K>: ObjectRef<K> {
/// Resolve reference in the provided namespace
fn within(&self, namespace: String) -> impl ObjectRef<K>;
}

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

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

impl<K> NamespacedRef<K> for ObjectReference
where
K: Resource,
K::DynamicType: Default,
K::Scope: NamespaceScope,
{
fn within(&self, namespace: String) -> impl ObjectRef<K> {

Check warning on line 85 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

Added line #L85 was not covered by tests
Self {
namespace: namespace.into(),

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L87 was not covered by tests
..self.clone()
}
}
}

impl<K> ObjectUrl<K> for OwnerReference
where
K: Resource,
K::DynamicType: Default,
{
fn url_path(&self) -> String {
K::url_path(&K::DynamicType::default(), None)

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

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L98-L99

Added lines #L98 - L99 were not covered by tests
}
}

impl<K> ObjectRef<K> for OwnerReference
where
K: Resource,
K::DynamicType: Default,
{
fn name(&self) -> Option<&str> {
self.name.as_str().into()

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

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L108-L109

Added lines #L108 - L109 were not covered by tests
}
}

impl<K> NamespacedRef<K> for OwnerReference
where
K: Resource,
K::DynamicType: Default,
K::Scope: NamespaceScope,
{
fn within(&self, namespace: String) -> impl ObjectRef<K> {

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L119 was not covered by tests
ObjectReference {
namespace: namespace.into(),
name: self.name.clone().into(),
uid: self.uid.clone().into(),
api_version: Some(K::api_version(&Default::default()).into()),
kind: Some(K::kind(&Default::default()).into()),

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

View check run for this annotation

Codecov / codecov/patch

kube-client/src/client/client_ext.rs#L121-L125

Added lines #L121 - L125 were not covered by tests
..Default::default()
}
}
}

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

// All objects can be listed cluster-wide
Expand Down Expand Up @@ -184,6 +270,52 @@ 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::{Resource, ResourceExt, api::GetParams};
/// # use kube::client::scope::NamespacedRef;
/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
/// # let client: kube::Client = todo!();
/// // cluster scoped
/// let cr: ClusterRole = todo!();
/// let cr: ClusterRole = client.fetch(&cr.object_ref(&())).await?;
/// assert_eq!(cr.name_unchecked(), "cluster-admin");
/// // namespace scoped
/// let svc: Service = todo!();
/// let svc: Service = client.fetch(&svc.object_ref(&())).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(&()))
/// .ok_or("Not Found")?;
/// let node: Node = client.fetch(&owner).await?;
/// let node: Pod = client.fetch(&owner.within("ns".into())).await?;
/// # Ok(())
/// # }
/// ```
pub async fn fetch<K>(&self, reference: &impl ObjectRef<K>) -> Result<K>
where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
{
self.get(
reference
.name()

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

View check run for this annotation

Codecov / codecov/patch

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

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

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

View check run for this annotation

Codecov / codecov/patch

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

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

/// List instances of a `Resource` implementing type `K` at the specified scope.
///
/// ```no_run
Expand Down Expand Up @@ -222,7 +354,7 @@ mod test {
scope::{Cluster, Namespace},
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 +388,55 @@ 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(&ObjectReference {
kind: Some(Service::kind(&()).into()),
api_version: Some(Service::api_version(&()).into()),
name: Some("kubernetes".into()),
namespace: Some("default".into()),
..Default::default()
})
.await?;
assert_eq!(svc.name_unchecked(), "kubernetes");
// global fetch
let ca: ClusterRole = client
.fetch(&ObjectReference {
kind: Some(ClusterRole::kind(&()).into()),
api_version: Some(ClusterRole::api_version(&()).into()),
name: Some("cluster-admin".into()),
..Default::default()
})
.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 431 in kube-client/src/client/client_ext.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L431 was not covered by tests
.owner_references()
.to_vec()
.into_iter()
.find(|r| r.kind == Node::kind(&()))

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L435 was not covered by tests
.ok_or("Not found")?;
let _: Node = client.fetch(&owner).await?;

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L437 was 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 3aad40b

Please sign in to comment.