Skip to main content

kube_client/client/
client_ext.rs

1use crate::{Client, Error, Result};
2use k8s_openapi::{
3    api::core::v1::{LocalObjectReference, Namespace as k8sNs, ObjectReference},
4    apimachinery::pkg::apis::meta::v1::OwnerReference,
5};
6use kube_core::{
7    ApiResource, ClusterResourceScope, DynamicObject, DynamicResourceScope, NamespaceScope, Resource,
8    object::ObjectList,
9    params::{GetParams, ListParams},
10    request::Request,
11};
12use serde::{Serialize, de::DeserializeOwned};
13use std::fmt::Debug;
14
15/// A marker trait to indicate cluster-wide operations are available
16trait ClusterScope {}
17
18// k8s_openapi scopes get implementations for free
19impl ClusterScope for ClusterResourceScope {}
20// our DynamicResourceScope can masquerade as either, NamespaceScope being the kube_core one
21impl ClusterScope for DynamicResourceScope {}
22
23/// How to get the url for a collection
24///
25/// Pick one of `kube::client::Cluster` or `kube::client::Namespace`.
26pub trait CollectionUrl<K> {
27    fn url_path(&self) -> String;
28}
29
30/// How to get the url for an object
31///
32/// Pick one of `kube::client::Cluster` or `kube::client::Namespace`.
33pub trait ObjectUrl<K> {
34    fn url_path(&self) -> String;
35}
36
37/// Marker type for cluster level queries
38#[derive(Debug, Clone)]
39pub struct Cluster;
40/// Namespace newtype for namespace level queries
41///
42/// You can create this directly, or convert `From` a `String` / `&str`, or `TryFrom` an `k8s_openapi::api::core::v1::Namespace`
43#[derive(Debug, Clone)]
44pub struct Namespace(String);
45
46/// Referenced object name resolution
47pub trait ObjectRef<K>: ObjectUrl<K> {
48    fn name(&self) -> Option<&str>;
49}
50
51/// Reference resolver for a specified namespace
52pub trait NamespacedRef<K> {
53    /// Resolve reference in the provided namespace
54    fn within(&self, namespace: impl Into<Option<String>>) -> impl ObjectRef<K>;
55}
56
57impl<K> ObjectUrl<K> for ObjectReference
58where
59    K: Resource,
60{
61    fn url_path(&self) -> String {
62        DynamicObject::url_path(
63            &ApiResource::from_gvk(&self.clone().into()),
64            self.namespace.as_deref(),
65        )
66    }
67}
68
69impl<K> ObjectRef<K> for ObjectReference
70where
71    K: Resource,
72{
73    fn name(&self) -> Option<&str> {
74        self.name.as_deref()
75    }
76}
77
78impl<K> NamespacedRef<K> for ObjectReference
79where
80    K: Resource,
81    K::Scope: NamespaceScope,
82{
83    fn within(&self, namespace: impl Into<Option<String>>) -> impl ObjectRef<K> {
84        Self {
85            namespace: namespace.into(),
86            ..self.clone()
87        }
88    }
89}
90
91impl<K> ObjectUrl<K> for OwnerReference
92where
93    K: Resource,
94    K::Scope: ClusterScope,
95{
96    fn url_path(&self) -> String {
97        DynamicObject::url_path(&ApiResource::from_gvk(&self.clone().into()), None)
98    }
99}
100
101impl<K> ObjectRef<K> for OwnerReference
102where
103    K: Resource,
104    K::Scope: ClusterScope,
105{
106    fn name(&self) -> Option<&str> {
107        self.name.as_str().into()
108    }
109}
110
111impl<K> NamespacedRef<K> for OwnerReference
112where
113    K: Resource,
114    K::Scope: NamespaceScope,
115{
116    fn within(&self, namespace: impl Into<Option<String>>) -> impl ObjectRef<K> {
117        ObjectReference {
118            api_version: self.api_version.clone().into(),
119            namespace: namespace.into(),
120            name: self.name.clone().into(),
121            uid: self.uid.clone().into(),
122            kind: self.kind.clone().into(),
123            ..Default::default()
124        }
125    }
126}
127
128impl<K> NamespacedRef<K> for LocalObjectReference
129where
130    K: Resource,
131    K::DynamicType: Default,
132    K::Scope: NamespaceScope,
133{
134    fn within(&self, namespace: impl Into<Option<String>>) -> impl ObjectRef<K> {
135        let dt = Default::default();
136        ObjectReference {
137            api_version: K::api_version(&dt).to_string().into(),
138            namespace: namespace.into(),
139            name: Some(self.name.clone()),
140            kind: K::kind(&dt).to_string().into(),
141            ..Default::default()
142        }
143    }
144}
145
146/// Scopes for `unstable-client` [`Client#impl-Client`] extension methods
147pub mod scope {
148    pub use super::{Cluster, Namespace, NamespacedRef};
149}
150
151// All objects can be listed cluster-wide
152impl<K> CollectionUrl<K> for Cluster
153where
154    K: Resource,
155    K::DynamicType: Default,
156{
157    fn url_path(&self) -> String {
158        K::url_path(&K::DynamicType::default(), None)
159    }
160}
161
162// Only cluster-scoped objects can be named globally
163impl<K> ObjectUrl<K> for Cluster
164where
165    K: Resource,
166    K::DynamicType: Default,
167    K::Scope: ClusterScope,
168{
169    fn url_path(&self) -> String {
170        K::url_path(&K::DynamicType::default(), None)
171    }
172}
173
174// Only namespaced objects can be accessed via namespace
175impl<K> CollectionUrl<K> for Namespace
176where
177    K: Resource,
178    K::DynamicType: Default,
179    K::Scope: NamespaceScope,
180{
181    fn url_path(&self) -> String {
182        K::url_path(&K::DynamicType::default(), Some(&self.0))
183    }
184}
185
186impl<K> ObjectUrl<K> for Namespace
187where
188    K: Resource,
189    K::DynamicType: Default,
190    K::Scope: NamespaceScope,
191{
192    fn url_path(&self) -> String {
193        K::url_path(&K::DynamicType::default(), Some(&self.0))
194    }
195}
196
197// can be created from a complete native object
198impl TryFrom<&k8sNs> for Namespace {
199    type Error = NamespaceError;
200
201    fn try_from(ns: &k8sNs) -> Result<Namespace, Self::Error> {
202        if let Some(n) = &ns.meta().name {
203            Ok(Namespace(n.to_owned()))
204        } else {
205            Err(NamespaceError::MissingName)
206        }
207    }
208}
209// and from literals + owned strings
210impl From<&str> for Namespace {
211    fn from(ns: &str) -> Namespace {
212        Namespace(ns.to_owned())
213    }
214}
215impl From<String> for Namespace {
216    fn from(ns: String) -> Namespace {
217        Namespace(ns)
218    }
219}
220
221#[derive(thiserror::Error, Debug)]
222/// Failures to infer a namespace
223pub enum NamespaceError {
224    /// MissingName
225    #[error("Missing Namespace Name")]
226    MissingName,
227}
228
229/// Generic client extensions for the `unstable-client` feature
230///
231/// These methods allow users to query across a wide-array of resources without needing
232/// to explicitly create an [`Api`](crate::Api) for each one of them.
233///
234/// ## Usage
235/// 1. Create a [`Client`]
236/// 2. Specify the [`scope`] you are querying at via [`Cluster`] or [`Namespace`] as args
237/// 3. Specify the resource type you are using for serialization (e.g. a top level k8s-openapi type)
238///
239/// ## Example
240///
241/// ```no_run
242/// # use k8s_openapi::api::core::v1::{Pod, Service};
243/// # use kube::client::scope::{Namespace, Cluster};
244/// # use kube::prelude::*;
245/// # use kube::api::ListParams;
246/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
247/// # let client: kube::Client = todo!();
248/// let lp = ListParams::default();
249/// // List at Cluster level for Pod resource:
250/// for pod in client.list::<Pod>(&lp, &Cluster).await? {
251///     println!("Found pod {} in {}", pod.name_any(), pod.namespace().unwrap());
252/// }
253/// // Namespaced Get for Service resource:
254/// let svc = client.get::<Service>("kubernetes", &Namespace::from("default")).await?;
255/// assert_eq!(svc.name_unchecked(), "kubernetes");
256/// # Ok(())
257/// # }
258/// ```
259impl Client {
260    /// Get a single instance of a `Resource` implementing type `K` at the specified scope.
261    ///
262    /// ```no_run
263    /// # use k8s_openapi::api::rbac::v1::ClusterRole;
264    /// # use k8s_openapi::api::core::v1::Service;
265    /// # use kube::client::scope::{Namespace, Cluster};
266    /// # use kube::prelude::*;
267    /// # use kube::api::GetParams;
268    /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
269    /// # let client: kube::Client = todo!();
270    /// let cr = client.get::<ClusterRole>("cluster-admin", &Cluster).await?;
271    /// assert_eq!(cr.name_unchecked(), "cluster-admin");
272    /// let svc = client.get::<Service>("kubernetes", &Namespace::from("default")).await?;
273    /// assert_eq!(svc.name_unchecked(), "kubernetes");
274    /// # Ok(())
275    /// # }
276    /// ```
277    pub async fn get<K>(&self, name: &str, scope: &impl ObjectUrl<K>) -> Result<K>
278    where
279        K: Resource + Serialize + DeserializeOwned + Clone + Debug,
280        <K as Resource>::DynamicType: Default,
281    {
282        let mut req = Request::new(scope.url_path())
283            .get(name, &GetParams::default())
284            .map_err(Error::BuildRequest)?;
285        req.extensions_mut().insert("get");
286        self.request::<K>(req).await
287    }
288
289    /// Fetch a single instance of a `Resource` from a provided object reference.
290    ///
291    /// ```no_run
292    /// # use k8s_openapi::api::rbac::v1::ClusterRole;
293    /// # use k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference;
294    /// # use k8s_openapi::api::core::v1::{ObjectReference, LocalObjectReference};
295    /// # use k8s_openapi::api::core::v1::{Node, Pod, Service, Secret};
296    /// # use kube::client::scope::NamespacedRef;
297    /// # use kube::api::GetParams;
298    /// # use kube::prelude::*;
299    /// # use kube::api::DynamicObject;
300    /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
301    /// # let client: kube::Client = todo!();
302    /// // cluster scoped
303    /// let cr: ClusterRole = todo!();
304    /// let cr: ClusterRole = client.fetch(&cr.object_ref(&())).await?;
305    /// assert_eq!(cr.name_unchecked(), "cluster-admin");
306    /// // namespace scoped
307    /// let svc: Service = todo!();
308    /// let svc: Service = client.fetch(&svc.object_ref(&())).await?;
309    /// assert_eq!(svc.name_unchecked(), "kubernetes");
310    /// // Fetch an owner of the resource
311    /// let pod: Pod = todo!();
312    /// let owner = pod
313    ///     .owner_references()
314    ///     .to_vec()
315    ///     .into_iter()
316    ///     .find(|r| r.kind == Node::kind(&()))
317    ///     .ok_or("Not Found")?;
318    /// let node: Node = client.fetch(&owner).await?;
319    /// // Namespace scoped objects require namespace
320    /// let pod: Pod = client.fetch(&owner.within("ns".to_string())).await?;
321    /// // Fetch dynamic object to resolve type later
322    /// let dynamic: DynamicObject = client.fetch(&owner.within("ns".to_string())).await?;
323    /// // Fetch using local object reference
324    /// let secret_ref = pod
325    ///     .spec
326    ///     .unwrap_or_default()
327    ///     .image_pull_secrets
328    ///     .unwrap_or_default()
329    ///     .get(0)
330    ///     .unwrap_or(&LocalObjectReference{name: "pull_secret".into()});
331    /// let secret: Secret = client.fetch(&secret_ref.within(pod.namespace())).await?;
332    /// # Ok(())
333    /// # }
334    /// ```
335    pub async fn fetch<K>(&self, reference: &impl ObjectRef<K>) -> Result<K>
336    where
337        K: Resource + Serialize + DeserializeOwned + Clone + Debug,
338    {
339        let mut req = Request::new(reference.url_path())
340            .get(
341                reference
342                    .name()
343                    .ok_or(Error::RefResolve("Reference is empty".to_string()))?,
344                &GetParams::default(),
345            )
346            .map_err(Error::BuildRequest)?;
347        req.extensions_mut().insert("get");
348        self.request::<K>(req).await
349    }
350
351    /// List instances of a `Resource` implementing type `K` at the specified scope.
352    ///
353    /// ```no_run
354    /// # use k8s_openapi::api::core::v1::Pod;
355    /// # use k8s_openapi::api::core::v1::Service;
356    /// # use kube::client::scope::{Namespace, Cluster};
357    /// # use kube::prelude::*;
358    /// # use kube::api::ListParams;
359    /// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
360    /// # let client: kube::Client = todo!();
361    /// let lp = ListParams::default();
362    /// for pod in client.list::<Pod>(&lp, &Cluster).await? {
363    ///     println!("Found pod {} in {}", pod.name_any(), pod.namespace().unwrap());
364    /// }
365    /// for svc in client.list::<Service>(&lp, &Namespace::from("default")).await? {
366    ///     println!("Found service {}", svc.name_any());
367    /// }
368    /// # Ok(())
369    /// # }
370    /// ```
371    pub async fn list<K>(&self, lp: &ListParams, scope: &impl CollectionUrl<K>) -> Result<ObjectList<K>>
372    where
373        K: Resource + Serialize + DeserializeOwned + Clone + Debug,
374        <K as Resource>::DynamicType: Default,
375    {
376        let mut req = Request::new(scope.url_path())
377            .list(lp)
378            .map_err(Error::BuildRequest)?;
379        req.extensions_mut().insert("list");
380        self.request::<ObjectList<K>>(req).await
381    }
382}
383
384#[cfg(test)]
385mod test {
386    use crate::{
387        Client,
388        client::{
389            client_ext::NamespacedRef as _,
390            scope::{Cluster, Namespace},
391        },
392    };
393
394    use super::ListParams;
395    use k8s_openapi::api::core::v1::LocalObjectReference;
396    use kube_core::{DynamicObject, Resource as _, ResourceExt as _};
397
398    #[tokio::test]
399    #[ignore = "needs cluster (will list/get namespaces, pods, jobs, svcs, clusterroles)"]
400    async fn client_ext_list_get_pods_svcs() -> Result<(), Box<dyn std::error::Error>> {
401        use k8s_openapi::api::{
402            batch::v1::Job,
403            core::v1::{Namespace as k8sNs, Pod, Service},
404            rbac::v1::ClusterRole,
405        };
406
407        let client = Client::try_default().await?;
408        let lp = ListParams::default();
409        // cluster-scoped list
410        for ns in client.list::<k8sNs>(&lp, &Cluster).await? {
411            // namespaced list
412            for p in client.list::<Pod>(&lp, &Namespace::try_from(&ns)?).await? {
413                println!("Found pod {} in {}", p.name_any(), ns.name_any());
414            }
415        }
416        // across-namespace list
417        for j in client.list::<Job>(&lp, &Cluster).await? {
418            println!("Found job {} in {}", j.name_any(), j.namespace().unwrap());
419        }
420        // namespaced get
421        let default: Namespace = "default".into();
422        let svc = client.get::<Service>("kubernetes", &default).await?;
423        assert_eq!(svc.name_unchecked(), "kubernetes");
424        // global get
425        let ca = client.get::<ClusterRole>("cluster-admin", &Cluster).await?;
426        assert_eq!(ca.name_unchecked(), "cluster-admin");
427
428        Ok(())
429    }
430
431    #[tokio::test]
432    #[ignore = "needs cluster (will get svcs, clusterroles, pods, nodes)"]
433    async fn client_ext_fetch_ref_pods_svcs() -> Result<(), Box<dyn std::error::Error>> {
434        use k8s_openapi::api::{
435            core::v1::{Node, ObjectReference, Pod, Service},
436            rbac::v1::ClusterRole,
437        };
438
439        let client = Client::try_default().await?;
440        // namespaced fetch
441        let svc: Service = client
442            .fetch(&ObjectReference {
443                kind: Some(Service::kind(&()).into()),
444                api_version: Some(Service::api_version(&()).into()),
445                name: Some("kubernetes".into()),
446                namespace: Some("default".into()),
447                ..Default::default()
448            })
449            .await?;
450        assert_eq!(svc.name_unchecked(), "kubernetes");
451        // global fetch
452        let ca: ClusterRole = client
453            .fetch(&ObjectReference {
454                kind: Some(ClusterRole::kind(&()).into()),
455                api_version: Some(ClusterRole::api_version(&()).into()),
456                name: Some("cluster-admin".into()),
457                ..Default::default()
458            })
459            .await?;
460        assert_eq!(ca.name_unchecked(), "cluster-admin");
461        // namespaced fetch untyped
462        let svc: DynamicObject = client.fetch(&svc.object_ref(&())).await?;
463        assert_eq!(svc.name_unchecked(), "kubernetes");
464        // global fetch untyped
465        let ca: DynamicObject = client.fetch(&ca.object_ref(&())).await?;
466        assert_eq!(ca.name_unchecked(), "cluster-admin");
467
468        // Fetch using local object reference
469        let svc: Service = client
470            .fetch(&LocalObjectReference { name: svc.name_any() }.within(svc.namespace()))
471            .await?;
472        assert_eq!(svc.name_unchecked(), "kubernetes");
473
474        let kube_system: Namespace = "kube-system".into();
475        for pod in client
476            .list::<Pod>(
477                &ListParams::default().labels("component=kube-apiserver"),
478                &kube_system,
479            )
480            .await?
481        {
482            let owner = pod
483                .owner_references()
484                .iter()
485                .find(|r| r.kind == Node::kind(&()))
486                .ok_or("Not found")?;
487            let _: Node = client.fetch(owner).await?;
488        }
489
490        Ok(())
491    }
492
493    #[tokio::test]
494    #[ignore = "needs cluster (will get svcs, clusterroles, pods, nodes)"]
495    async fn fetch_fails() -> Result<(), Box<dyn std::error::Error>> {
496        use crate::error::Error;
497        use k8s_openapi::api::core::v1::{ObjectReference, Pod, Service};
498
499        let client = Client::try_default().await?;
500        // namespaced fetch
501        let svc: Service = client
502            .fetch(&ObjectReference {
503                kind: Some(Service::kind(&()).into()),
504                api_version: Some(Service::api_version(&()).into()),
505                name: Some("kubernetes".into()),
506                namespace: Some("default".into()),
507                ..Default::default()
508            })
509            .await?;
510        let err = client.fetch::<Pod>(&svc.object_ref(&())).await.unwrap_err();
511        assert!(matches!(err, Error::SerdeError(_)));
512        assert_eq!(err.to_string(), "Error deserializing response: invalid value: string \"Service\", expected Pod at line 1 column 17".to_string());
513
514        let obj: DynamicObject = client.fetch(&svc.object_ref(&())).await?;
515        let err = obj.try_parse::<Pod>().unwrap_err();
516        assert_eq!(err.to_string(), "failed to parse this DynamicObject into a Resource: invalid value: string \"Service\", expected Pod".to_string());
517
518        Ok(())
519    }
520}