kube_client/api/mod.rs
1//! API helpers for structured interaction with the Kubernetes API
2
3mod core_methods;
4#[cfg(feature = "ws")] mod remote_command;
5use std::fmt::Debug;
6
7#[cfg(feature = "ws")]
8#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
9pub use remote_command::{AttachedProcess, TerminalSize};
10#[cfg(feature = "ws")] mod portforward;
11#[cfg(feature = "ws")]
12#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
13pub use portforward::Portforwarder;
14
15mod subresource;
16#[cfg(feature = "ws")]
17#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
18pub use subresource::{Attach, AttachParams, Execute, Portforward};
19pub use subresource::{Ephemeral, Evict, EvictParams, Log, LogParams, Resize, ScaleSpec, ScaleStatus};
20
21mod util;
22
23pub mod entry;
24
25// Re-exports from kube-core
26#[cfg(feature = "admission")]
27#[cfg_attr(docsrs, doc(cfg(feature = "admission")))]
28pub use kube_core::admission;
29pub(crate) use kube_core::params;
30use kube_core::{DynamicResourceScope, NamespaceResourceScope, NamespaceScope, discovery::Scope};
31pub use kube_core::{
32 Resource, ResourceExt,
33 dynamic::{ApiResource, DynamicObject},
34 gvk::{GroupVersionKind, GroupVersionResource},
35 metadata::{ListMeta, ObjectMeta, PartialObjectMeta, PartialObjectMetaExt, TypeMeta},
36 object::{NotUsed, Object, ObjectList},
37 request::Request,
38 watch::WatchEvent,
39};
40pub use params::{
41 DeleteParams, GetParams, ListParams, Patch, PatchParams, PostParams, Preconditions, PropagationPolicy,
42 ValidationDirective, VersionMatch, WatchParams,
43};
44
45use crate::Client;
46/// The generic Api abstraction
47///
48/// This abstracts over a [`Request`] and a type `K` so that
49/// we get automatic serialization/deserialization on the api calls
50/// implemented by the dynamic [`Resource`].
51#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
52#[derive(Clone)]
53pub struct Api<K> {
54 /// The request builder object with its resource dependent url
55 pub(crate) request: Request,
56 /// The client to use (from this library)
57 pub(crate) client: Client,
58 namespace: Option<String>,
59 /// The type-erased resource, kept so that [`Api::constrain`] can rebuild the url through
60 /// [`Resource::url_path`] rather than editing the finished one
61 ///
62 /// Erased for the same reason `metadata_api` is a bool: a non-generic field needs no bound on
63 /// the struct.
64 resource: ApiResource,
65 /// The [`Scope`] of the kind, when it is known
66 ///
67 /// Only [`Api::dynamic`] is told one; the other constructors leave it `None`, which makes
68 /// [`Api::constrain`] apply a namespace unconditionally.
69 scope: Option<Scope>,
70 /// Whether requests should use metadata-only Accept headers
71 /// (cached from `K::metadata_api()` at construction so that `impl<K> Api<K>`
72 /// method blocks don't have to tighten to `K: Resource`).
73 pub(crate) metadata_api: bool,
74 /// Note: Using `iter::Empty` over `PhantomData`, because we never actually keep any
75 /// `K` objects, so `Empty` better models our constraints (in particular, `Empty<K>`
76 /// is `Send`, even if `K` may not be).
77 pub(crate) _phantom: std::iter::Empty<K>,
78}
79
80/// Api constructors for Resource implementors with custom DynamicTypes
81///
82/// This generally means resources created via [`DynamicObject`](crate::api::DynamicObject).
83impl<K: Resource> Api<K> {
84 /// Return a reference to the namespace of this [`Api`] instance, if any
85 pub fn namespace(&self) -> Option<&str> {
86 self.namespace.as_deref()
87 }
88
89 /// Cluster level resources, or resources viewed across all namespaces
90 ///
91 /// This function accepts `K::DynamicType` so it can be used with dynamic resources.
92 ///
93 /// # Warning
94 ///
95 /// This variant **can only `list` and `watch` namespaced resources** and is commonly used with a `watcher`.
96 /// If you need to create/patch/replace/get on a namespaced resource, you need a separate `Api::namespaced`.
97 pub fn all_with(client: Client, dyntype: &K::DynamicType) -> Self {
98 let url = K::url_path(dyntype, None);
99 Self {
100 client,
101 request: Request::new(url),
102 namespace: None,
103 resource: ApiResource::erase::<K>(dyntype),
104 scope: None,
105 metadata_api: K::metadata_api(),
106 _phantom: std::iter::empty(),
107 }
108 }
109
110 /// Namespaced resource within a given namespace
111 ///
112 /// This function accepts `K::DynamicType` so it can be used with dynamic resources.
113 pub fn namespaced_with(client: Client, ns: &str, dyntype: &K::DynamicType) -> Self
114 where
115 K: Resource<Scope = DynamicResourceScope>,
116 {
117 // the dyntype carries no scope; `Api::dynamic` takes one explicitly instead
118 let url = K::url_path(dyntype, Some(ns));
119 Self {
120 client,
121 request: Request::new(url),
122 namespace: Some(ns.to_string()),
123 resource: ApiResource::erase::<K>(dyntype),
124 scope: None,
125 metadata_api: K::metadata_api(),
126 _phantom: std::iter::empty(),
127 }
128 }
129
130 /// Namespaced resource within the default namespace
131 ///
132 /// This function accepts `K::DynamicType` so it can be used with dynamic resources.
133 ///
134 /// The namespace is either configured on `context` in the kubeconfig
135 /// or falls back to `default` when running locally, and it's using the service account's
136 /// namespace when deployed in-cluster.
137 pub fn default_namespaced_with(client: Client, dyntype: &K::DynamicType) -> Self
138 where
139 K: Resource<Scope = DynamicResourceScope>,
140 {
141 let ns = client.default_namespace().to_string();
142 Self::namespaced_with(client, &ns, dyntype)
143 }
144
145 /// Resource of a kind only known at runtime, remembering its [`Scope`]
146 ///
147 /// The url starts out cluster wide, exactly as [`all_with`](Api::all_with) builds it, and the
148 /// [`Scope`] is kept so that [`constrain`](Api::constrain) can apply a namespace the way
149 /// `kubectl -n` does: to a namespaced kind, but not to a cluster scoped one.
150 ///
151 /// ```no_run
152 /// # use kube::{Api, Client, api::{ApiResource, DynamicObject}, discovery::Scope};
153 /// # use k8s_openapi::api::core::v1::Pod;
154 /// # let client: Client = todo!();
155 /// let ar = ApiResource::erase::<Pod>(&());
156 /// let api: Api<DynamicObject> = Api::dynamic(client, &ar, &Scope::Namespaced);
157 /// assert_eq!(api.resource_url(), "/api/v1/pods");
158 /// ```
159 ///
160 /// The [`Scope`] usually arrives from discovery, on the [`ApiCapabilities`] handed back next
161 /// to the [`ApiResource`], but any source works, e.g. a [`CustomResourceDefinition`]'s
162 /// `spec.scope`.
163 ///
164 /// # Warning
165 ///
166 /// A cluster wide url **can only `list` and `watch`** a namespaced kind, as with
167 /// [`Api::all_with`]. The other verbs need a [`constrain`](Api::constrain) first.
168 ///
169 /// [`Scope`]: crate::discovery::Scope
170 /// [`ApiResource`]: crate::discovery::ApiResource
171 /// [`ApiCapabilities`]: crate::discovery::ApiCapabilities
172 /// [`CustomResourceDefinition`]: k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition
173 pub fn dynamic(client: Client, dyntype: &K::DynamicType, scope: &Scope) -> Self
174 where
175 K: Resource<DynamicType = ApiResource, Scope = DynamicResourceScope>,
176 {
177 // the scope has to be passed in because it cannot be read off the dyntype, which is what
178 // the TODO on `namespaced_with` was asking for
179 Self {
180 scope: Some(scope.clone()),
181 ..Self::all_with(client, dyntype)
182 }
183 }
184
185 /// Constrain this [`Api`] to a new namespace
186 ///
187 /// Allows changing the tracked namespace for a namespace scoped [`Api`], without building a
188 /// second one:
189 ///
190 /// ```no_run
191 /// # use kube::{Api, Client};
192 /// # use k8s_openapi::api::core::v1::Pod;
193 /// # let client: Client = todo!();
194 /// let pods: Api<Pod> = Api::namespaced(client, "ns1").constrain("ns2");
195 /// assert_eq!(pods.resource_url(), "/api/v1/namespaces/ns2/pods");
196 /// ```
197 ///
198 /// A cluster scoped kind has no namespace to track, so it does not get the method:
199 ///
200 /// ```compile_fail
201 /// # use kube::{Api, Client};
202 /// # use k8s_openapi::api::core::v1::Node;
203 /// # let client: Client = todo!();
204 /// let nodes: Api<Node> = Api::all(client).constrain("ns1"); // resource not namespaced!
205 /// ```
206 ///
207 /// A dynamic kind can only be found to be cluster scoped at runtime, and an [`Api`] from
208 /// [`Api::dynamic`] knows its [`Scope`], so this is a no-op there rather than a compile
209 /// error, mirroring `kubectl get nodes -n whatever`.
210 ///
211 /// Widen back to every namespace with [`unconstrain`](Api::unconstrain), which an empty `ns`
212 /// also does.
213 ///
214 /// [`Scope`]: crate::discovery::Scope
215 #[must_use]
216 pub fn constrain(mut self, ns: &str) -> Self
217 where
218 K::Scope: NamespaceScope,
219 {
220 if self.scope == Some(Scope::Cluster) {
221 return self;
222 }
223 self.namespace = (!ns.is_empty()).then(|| ns.to_string());
224 // the stored resource is the erased dyntype, so this is `Resource::url_path` on its
225 // canonical carrier - the same string `K::url_path` would build
226 self.request = Request::new(DynamicObject::url_path(&self.resource, self.namespace.as_deref()));
227 self
228 }
229
230 /// Widen this [`Api`] back to every namespace
231 ///
232 /// The inverse of [`constrain`](Api::constrain), leaving the [`Api`] as [`Api::all`] builds
233 /// it, which for a namespaced kind **can only `list` and `watch`**.
234 ///
235 /// ```no_run
236 /// # use kube::{Api, Client};
237 /// # use k8s_openapi::api::core::v1::Pod;
238 /// # let client: Client = todo!();
239 /// let pods: Api<Pod> = Api::namespaced(client, "ns1").unconstrain();
240 /// assert_eq!(pods.resource_url(), "/api/v1/pods");
241 /// ```
242 #[must_use]
243 pub fn unconstrain(mut self) -> Self
244 where
245 K::Scope: NamespaceScope,
246 {
247 self.namespace = None;
248 self.request = Request::new(DynamicObject::url_path(&self.resource, None));
249 self
250 }
251
252 /// Constrain this [`Api`] to the [`Client`]'s default namespace
253 ///
254 /// The kubectl equivalent of passing no `-n` at all. A shorthand for
255 /// `api.constrain(client.default_namespace())`
256 #[must_use]
257 pub fn constrain_default(self) -> Self
258 where
259 K::Scope: NamespaceScope,
260 {
261 let ns = self.client.default_namespace().to_string();
262 self.constrain(&ns)
263 }
264
265 /// Consume self and return the [`Client`]
266 pub fn into_client(self) -> Client {
267 self.into()
268 }
269
270 /// Return a reference to the current resource url path
271 pub fn resource_url(&self) -> &str {
272 &self.request.url_path
273 }
274}
275
276/// Api constructors for Resource implementors with Default DynamicTypes
277///
278/// This generally means structs implementing `k8s_openapi::Resource`.
279impl<K: Resource> Api<K>
280where
281 <K as Resource>::DynamicType: Default,
282{
283 /// Cluster level resources, or resources viewed across all namespaces
284 ///
285 /// Namespace scoped resource allowing querying across all namespaces:
286 ///
287 /// ```no_run
288 /// # use kube::{Api, Client};
289 /// # let client: Client = todo!();
290 /// use k8s_openapi::api::core::v1::Pod;
291 /// let api: Api<Pod> = Api::all(client);
292 /// ```
293 ///
294 /// Cluster scoped resources also use this entrypoint:
295 ///
296 /// ```no_run
297 /// # use kube::{Api, Client};
298 /// # let client: Client = todo!();
299 /// use k8s_openapi::api::core::v1::Node;
300 /// let api: Api<Node> = Api::all(client);
301 /// ```
302 ///
303 /// # Warning
304 ///
305 /// This variant **can only `list` and `watch` namespaced resources** and is commonly used with a `watcher`.
306 /// If you need to create/patch/replace/get on a namespaced resource, you need a separate `Api::namespaced`.
307 pub fn all(client: Client) -> Self {
308 Self::all_with(client, &K::DynamicType::default())
309 }
310
311 /// Namespaced resource within a given namespace
312 ///
313 /// ```no_run
314 /// # use kube::{Api, Client};
315 /// # let client: Client = todo!();
316 /// use k8s_openapi::api::core::v1::Pod;
317 /// let api: Api<Pod> = Api::namespaced(client, "default");
318 /// ```
319 ///
320 /// This will ONLY work on namespaced resources as set by `Scope`:
321 ///
322 /// ```compile_fail
323 /// # use kube::{Api, Client};
324 /// # let client: Client = todo!();
325 /// use k8s_openapi::api::core::v1::Node;
326 /// let api: Api<Node> = Api::namespaced(client, "default"); // resource not namespaced!
327 /// ```
328 ///
329 /// For dynamic type information, use [`Api::namespaced_with`] variants.
330 pub fn namespaced(client: Client, ns: &str) -> Self
331 where
332 K: Resource<Scope = NamespaceResourceScope>,
333 {
334 let dyntype = K::DynamicType::default();
335 let url = K::url_path(&dyntype, Some(ns));
336 Self {
337 client,
338 request: Request::new(url),
339 namespace: Some(ns.to_string()),
340 resource: ApiResource::erase::<K>(&dyntype),
341 scope: None,
342 metadata_api: K::metadata_api(),
343 _phantom: std::iter::empty(),
344 }
345 }
346
347 /// Namespaced resource within the default namespace
348 ///
349 /// The namespace is either configured on `context` in the kubeconfig
350 /// or falls back to `default` when running locally, and it's using the service account's
351 /// namespace when deployed in-cluster.
352 ///
353 /// ```no_run
354 /// # use kube::{Api, Client};
355 /// # let client: Client = todo!();
356 /// use k8s_openapi::api::core::v1::Pod;
357 /// let api: Api<Pod> = Api::default_namespaced(client);
358 /// ```
359 ///
360 /// This will ONLY work on namespaced resources as set by `Scope`:
361 ///
362 /// ```compile_fail
363 /// # use kube::{Api, Client};
364 /// # let client: Client = todo!();
365 /// use k8s_openapi::api::core::v1::Node;
366 /// let api: Api<Node> = Api::default_namespaced(client); // resource not namespaced!
367 /// ```
368 pub fn default_namespaced(client: Client) -> Self
369 where
370 K: Resource<Scope = NamespaceResourceScope>,
371 {
372 let ns = client.default_namespace().to_string();
373 Self::namespaced(client, &ns)
374 }
375}
376
377impl<K> From<Api<K>> for Client {
378 fn from(api: Api<K>) -> Self {
379 api.client
380 }
381}
382
383impl<K> Debug for Api<K> {
384 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385 // Intentionally destructuring, to cause compile errors when new fields are added
386 let Self {
387 request,
388 client: _,
389 namespace,
390 resource: _,
391 scope,
392 metadata_api: _,
393 _phantom,
394 } = self;
395 f.debug_struct("Api")
396 .field("request", &request)
397 .field("client", &"...")
398 .field("namespace", &namespace)
399 .field("scope", &scope)
400 .finish()
401 }
402}
403
404/// Sanity test on scope restrictions
405#[cfg(test)]
406mod test {
407 use crate::{Api, Client, client::Body};
408 use k8s_openapi::api::core::v1 as corev1;
409
410 use http::{Request, Response};
411 use tower_test::mock;
412
413 #[tokio::test]
414 async fn scopes_should_allow_correct_interface() {
415 let (mock_service, _handle) = mock::pair::<Request<Body>, Response<Body>>();
416 let client = Client::new(mock_service, "default");
417
418 let _: Api<corev1::Node> = Api::all(client.clone());
419 let _: Api<corev1::Pod> = Api::default_namespaced(client.clone());
420 let _: Api<corev1::PersistentVolume> = Api::all(client.clone());
421 let _: Api<corev1::ConfigMap> = Api::namespaced(client, "default");
422 }
423
424 // deliberately not "default", so the client default is distinguishable from a literal
425 fn mock_client() -> Client {
426 let (mock_service, _handle) = mock::pair::<Request<Body>, Response<Body>>();
427 Client::new(mock_service, "kube-rs-test")
428 }
429
430 // The (scope x constraint) matrix, since the scope is what decides whether `constrain`
431 // applies at all.
432 #[tokio::test]
433 async fn constrain_applies_only_to_namespaced_kinds() {
434 use crate::api::{ApiResource, DynamicObject};
435 use k8s_openapi::api::apps::v1 as appsv1;
436 use kube_core::discovery::Scope;
437
438 let client = mock_client();
439 let dynamic = |ar, scope| Api::<DynamicObject>::dynamic(client.clone(), ar, scope);
440 let cm = ApiResource::erase::<corev1::ConfigMap>(&());
441 let deploy = ApiResource::erase::<appsv1::Deployment>(&());
442 let node = ApiResource::erase::<corev1::Node>(&());
443
444 // a namespaced kind starts cluster wide, and `constrain` narrows it
445 let api = dynamic(&cm, &Scope::Namespaced);
446 assert_eq!(api.namespace(), None);
447 assert_eq!(api.resource_url(), "/api/v1/configmaps");
448 let api = api.constrain("ns1");
449 assert_eq!(api.namespace(), Some("ns1"));
450 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns1/configmaps");
451
452 // constraining again replaces the namespace rather than nesting it
453 let api = api.constrain("ns2");
454 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns2/configmaps");
455
456 // `unconstrain` widens back, and an empty namespace lands in the same place
457 assert_eq!(api.clone().unconstrain().resource_url(), "/api/v1/configmaps");
458 let api = api.constrain("");
459 assert_eq!(api.namespace(), None);
460 assert_eq!(api.resource_url(), "/api/v1/configmaps");
461
462 // a non-core group has a longer prefix to splice into
463 assert_eq!(
464 dynamic(&deploy, &Scope::Namespaced)
465 .constrain("ns1")
466 .resource_url(),
467 "/apis/apps/v1/namespaces/ns1/deployments"
468 );
469
470 // `constrain_default` picks the namespace off the client the Api already holds
471 let api = dynamic(&cm, &Scope::Namespaced).constrain_default();
472 assert_eq!(api.namespace(), Some("kube-rs-test"));
473 assert_eq!(api.resource_url(), "/api/v1/namespaces/kube-rs-test/configmaps");
474
475 // a cluster scoped kind drops the constraint, as `kubectl get nodes -n whatever` does
476 for api in [
477 dynamic(&node, &Scope::Cluster),
478 dynamic(&node, &Scope::Cluster).constrain("ns1"),
479 dynamic(&node, &Scope::Cluster).constrain_default(),
480 ] {
481 assert_eq!(api.namespace(), None);
482 assert_eq!(api.resource_url(), "/api/v1/nodes");
483 }
484 }
485
486 // A typed namespaced kind is statically namespaced, so `constrain` is just a namespace
487 // switch on it, and a cluster scoped one does not get the method at all (doc `compile_fail`).
488 #[tokio::test]
489 async fn constrain_switches_namespaces_on_typed_apis() {
490 let client = mock_client();
491
492 let api: Api<corev1::ConfigMap> = Api::namespaced(client.clone(), "ns1").constrain("ns2");
493 assert_eq!(api.namespace(), Some("ns2"));
494 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns2/configmaps");
495
496 // narrowing an `all` Api is the same move in the other direction
497 let api: Api<corev1::Pod> = Api::all(client.clone()).constrain("ns1");
498 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns1/pods");
499
500 let api: Api<corev1::Pod> = Api::all(client).constrain_default();
501 assert_eq!(api.resource_url(), "/api/v1/namespaces/kube-rs-test/pods");
502
503 // and `unconstrain` is the way back, as an empty namespace still is
504 let api: Api<corev1::Pod> = api.unconstrain();
505 assert_eq!(api.namespace(), None);
506 assert_eq!(api.resource_url(), "/api/v1/pods");
507 }
508
509 // Without a scope there is nothing to consult, so the namespace is applied rather than
510 // silently dropped - which also means it can rewrite what `namespaced_with` built.
511 #[tokio::test]
512 async fn constrain_applies_unconditionally_without_a_known_scope() {
513 use crate::api::{ApiResource, DynamicObject};
514
515 let client = mock_client();
516 let cm = ApiResource::erase::<corev1::ConfigMap>(&());
517
518 let api: Api<DynamicObject> = Api::all_with(client.clone(), &cm).constrain("ns1");
519 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns1/configmaps");
520
521 let api: Api<DynamicObject> = Api::namespaced_with(client, "ns1", &cm).constrain("ns2");
522 assert_eq!(api.resource_url(), "/api/v1/namespaces/ns2/configmaps");
523 }
524}