1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Kube is an umbrella-crate for interacting with [Kubernetes](http://kubernetes.io) in Rust.
//!
//! # Overview
//!
//! Kube contains a Kubernetes client, a controller runtime, a custom resource derive, and various tooling
//! required for building applications or controllers that interact with Kubernetes.
//!
//! The main modules are:
//!
//! - [`client`](crate::client) with the Kubernetes [`Client`](crate::Client) and its layers
//! - [`config`](crate::config) for cluster [`Config`](crate::Config)
//! - [`api`](crate::api) with the generic Kubernetes [`Api`](crate::Api)
//! - [`derive`](kube_derive) with the [`CustomResource`](crate::CustomResource) derive for building controllers types
//! - [`runtime`](crate::runtime) with a [`Controller`](crate::runtime::Controller) / [`watcher`](crate::runtime::watcher()) / [`reflector`](crate::runtime::reflector::reflector) / [`Store`](crate::runtime::reflector::Store)
//! - [`core`](crate::core) with generics from `apimachinery`
//!
//! You can use each of these as you need with the help of the [exported features](https://github.com/kube-rs/kube-rs/blob/master/kube/Cargo.toml#L18).
//!
//! # Using the Client
//! ```no_run
//! use futures::{StreamExt, TryStreamExt};
//! use kube::{Client, api::{Api, ResourceExt, ListParams, PostParams}};
//! use k8s_openapi::api::core::v1::Pod;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Infer the runtime environment and try to create a Kubernetes Client
//!     let client = Client::try_default().await?;
//!
//!     // Read pods in the configured namespace into the typed interface from k8s-openapi
//!     let pods: Api<Pod> = Api::default_namespaced(client);
//!     for p in pods.list(&ListParams::default()).await? {
//!         println!("found pod {}", p.name());
//!     }
//!     Ok(())
//! }
//! ```
//!
//! For details, see:
//!
//! - [`Client`](crate::client) for the extensible Kubernetes client
//! - [`Api`](crate::Api) for the generic api methods available on Kubernetes resources
//! - [k8s-openapi](https://docs.rs/k8s-openapi/*/k8s_openapi/) for documentation about the generated Kubernetes types
//!
//! # Using the Runtime with the Derive macro
//!
//! ```no_run
//! use schemars::JsonSchema;
//! use serde::{Deserialize, Serialize};
//! use serde_json::json;
//! use validator::Validate;
//! use futures::{StreamExt, TryStreamExt};
//! use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition;
//! use kube::{
//!     api::{Api, DeleteParams, ListParams, PatchParams, Patch, ResourceExt},
//!     core::CustomResourceExt,
//!     Client, CustomResource,
//!     runtime::{watcher, utils::try_flatten_applied, wait::{conditions, await_condition}},
//! };
//!
//! // Our custom resource
//! #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, Validate, JsonSchema)]
//! #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)]
//! pub struct FooSpec {
//!     info: String,
//!     #[validate(length(min = 3))]
//!     name: String,
//!     replicas: i32,
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = Client::try_default().await?;
//!     let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
//!
//!     // Apply the CRD so users can create Foo instances in Kubernetes
//!     crds.patch("foos.clux.dev",
//!         &PatchParams::apply("my_manager"),
//!         &Patch::Apply(Foo::crd())
//!     ).await?;
//!
//!     // Wait for the CRD to be ready
//!     tokio::time::timeout(
//!         std::time::Duration::from_secs(10),
//!         await_condition(crds, "foos.clux.dev", conditions::is_crd_established())
//!     ).await?;
//!
//!     // Watch for changes to foos in the configured namespace
//!     let foos: Api<Foo> = Api::default_namespaced(client.clone());
//!     let lp = ListParams::default();
//!     let mut apply_stream = try_flatten_applied(watcher(foos, lp)).boxed();
//!     while let Some(f) = apply_stream.try_next().await? {
//!         println!("saw apply to {}", f.name());
//!     }
//!     Ok(())
//! }
//! ```
//!
//! For details, see:
//!
//! - [`CustomResource`](crate::CustomResource) for documentation how to configure custom resources
//! - [`runtime::watcher`](crate::runtime::watcher()) for how to long-running watches work and why you want to use this over [`Api::watch`](crate::Api::watch)
//! - [`runtime`](crate::runtime) for abstractions that help with more complicated Kubernetes application
//!
//! # Examples
//! A large list of complete, runnable examples with explainations are available in the [examples folder](https://github.com/kube-rs/kube-rs/tree/master/examples).
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
#![forbid(unsafe_code)]

macro_rules! cfg_client {
    ($($item:item)*) => {
        $(
            #[cfg_attr(docsrs, doc(cfg(feature = "client")))]
            #[cfg(feature = "client")]
            $item
        )*
    }
}
macro_rules! cfg_config {
    ($($item:item)*) => {
        $(
            #[cfg_attr(docsrs, doc(cfg(feature = "config")))]
            #[cfg(feature = "config")]
            $item
        )*
    }
}

macro_rules! cfg_error {
    ($($item:item)*) => {
        $(
            #[cfg_attr(docsrs, doc(cfg(any(feature = "config", feature = "client"))))]
            #[cfg(any(feature = "config", feature = "client"))]
            $item
        )*
    }
}

cfg_client! {
    pub use kube_client::api;
    pub use kube_client::discovery;
    pub use kube_client::client;

    #[doc(inline)]
    pub use api::Api;
    #[doc(inline)]
    pub use client::Client;
    #[doc(inline)]
    pub use discovery::Discovery;
}

cfg_config! {
    pub use kube_client::config;
    #[doc(inline)]
    pub use config::Config;
}

cfg_error! {
    pub use kube_client::error;
    #[doc(inline)] pub use error::Error;
    /// Convient alias for `Result<T, Error>`
    pub type Result<T, E = Error> = std::result::Result<T, E>;
}

/// Re-exports from [`kube-derive`](kube_derive)
#[cfg(feature = "derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use kube_derive::CustomResource;

/// Re-exports from [`kube-runtime`](kube_runtime)
#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
#[doc(inline)]
pub use kube_runtime as runtime;

pub use crate::core::{CustomResourceExt, Resource, ResourceExt};
/// Re-exports from [`kube_core`](kube_core)
#[doc(inline)]
pub use kube_core as core;

// Tests that require a cluster and the complete feature set
// Can be run with `cargo test -p kube --lib --features=runtime,derive -- --ignored`
#[cfg(test)]
#[cfg(all(feature = "derive", feature = "client"))]
mod test {
    use crate::{
        api::{DeleteParams, Patch, PatchParams},
        Api, Client, CustomResourceExt, Resource, ResourceExt,
    };
    use kube_derive::CustomResource;
    use schemars::JsonSchema;
    use serde::{Deserialize, Serialize};

    #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)]
    #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)]
    #[kube(status = "FooStatus")]
    #[kube(scale = r#"{"specReplicasPath":".spec.replicas", "statusReplicasPath":".status.replicas"}"#)]
    #[kube(crates(kube_core = "crate::core"))] // for dev-dep test structure
    pub struct FooSpec {
        name: String,
        info: Option<String>,
        replicas: isize,
    }

    #[derive(Deserialize, Serialize, Clone, Debug, Default, JsonSchema)]
    pub struct FooStatus {
        is_bad: bool,
        replicas: isize,
    }

    #[tokio::test]
    #[ignore] // needs kubeconfig
    async fn custom_resource_generates_correct_core_structs() {
        use crate::core::{ApiResource, DynamicObject, GroupVersionKind};
        let client = Client::try_default().await.unwrap();

        let gvk = GroupVersionKind::gvk("clux.dev", "v1", "Foo");
        let api_resource = ApiResource::from_gvk(&gvk);
        let a1: Api<DynamicObject> = Api::namespaced_with(client.clone(), "myns", &api_resource);
        let a2: Api<Foo> = Api::namespaced(client, "myns");

        // make sure they return the same url_path through their impls
        assert_eq!(a1.resource_url(), a2.resource_url());
    }

    use k8s_openapi::{
        api::core::v1::ConfigMap,
        apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition,
    };
    #[tokio::test]
    #[ignore] // needs cluster (creates + patches foo crd)
    #[cfg(all(feature = "derive", feature = "runtime"))]
    async fn derived_resource_queriable_and_has_subresources() -> Result<(), Box<dyn std::error::Error>> {
        use crate::runtime::wait::{await_condition, conditions};

        use serde_json::json;
        let client = Client::try_default().await?;
        let ssapply = PatchParams::apply("kube").force();
        let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
        // Server-side apply CRD and wait for it to get ready
        crds.patch("foos.clux.dev", &ssapply, &Patch::Apply(Foo::crd()))
            .await?;
        let establish = await_condition(crds.clone(), "foos.clux.dev", conditions::is_crd_established());
        let _ = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await?;

        // Use it
        let foos: Api<Foo> = Api::default_namespaced(client.clone());
        // Apply from generated struct
        {
            let foo = Foo::new("baz", FooSpec {
                name: "baz".into(),
                info: Some("old baz".into()),
                replicas: 1,
            });
            let o = foos.patch("baz", &ssapply, &Patch::Apply(&foo)).await?;
            assert_eq!(o.spec.name, "baz");
            let oref = o.object_ref(&());
            assert_eq!(oref.name.unwrap(), "baz");
            assert_eq!(oref.uid, o.uid());
        }
        // Apply from partial json!
        {
            let patch = json!({
                "apiVersion": "clux.dev/v1",
                "kind": "Foo",
                "spec": {
                    "name": "foo",
                    "replicas": 2
                }
            });
            let o = foos.patch("baz", &ssapply, &Patch::Apply(patch)).await?;
            assert_eq!(o.spec.replicas, 2);
        }
        // check subresource
        {
            assert_eq!(foos.get_scale("baz").await?.spec.unwrap().replicas, Some(2));
            assert!(foos.get_status("baz").await?.status.is_none()); // nothing has set this
        }
        // set status subresource
        {
            let fs = serde_json::json!({"status": FooStatus { is_bad: false, replicas: 1 }});
            let o = foos
                .patch_status("baz", &Default::default(), &Patch::Merge(&fs))
                .await?;
            assert!(o.status.is_some());
        }
        // set scale subresource
        {
            let fs = serde_json::json!({"spec": { "replicas": 3 }});
            let o = foos
                .patch_scale("baz", &Default::default(), &Patch::Merge(&fs))
                .await?;
            assert_eq!(o.status.unwrap().replicas, 1); // something needs to set the status for this
            assert_eq!(o.spec.unwrap().replicas.unwrap(), 3); // what we asked for got updated
        }

        // cleanup
        foos.delete_collection(&DeleteParams::default(), &Default::default())
            .await?;
        crds.delete("foos.clux.dev", &DeleteParams::default()).await?;
        Ok(())
    }

    #[tokio::test]
    #[ignore] // needs cluster (lists pods)
    async fn custom_serialized_objects_are_queryable_and_iterable() -> Result<(), Box<dyn std::error::Error>>
    {
        use crate::core::{
            object::{HasSpec, HasStatus, NotUsed, Object},
            ApiResource,
        };
        use k8s_openapi::api::core::v1::Pod;
        #[derive(Clone, Deserialize, Debug)]
        struct PodSpecSimple {
            containers: Vec<ContainerSimple>,
        }
        #[derive(Clone, Deserialize, Debug)]
        struct ContainerSimple {
            #[allow(dead_code)]
            image: String,
        }
        type PodSimple = Object<PodSpecSimple, NotUsed>;

        // use known type information from pod (can also use discovery for this)
        let ar = ApiResource::erase::<Pod>(&());

        let client = Client::try_default().await?;
        let api: Api<PodSimple> = Api::default_namespaced_with(client, &ar);
        let mut list = api.list(&Default::default()).await?;
        // check we can mutably iterate over ObjectList
        for pod in &mut list {
            pod.spec_mut().containers = vec![];
            *pod.status_mut() = None;
            pod.annotations_mut()
                .entry("kube-seen".to_string())
                .or_insert_with(|| "yes".to_string());
            pod.labels_mut()
                .entry("kube.rs".to_string())
                .or_insert_with(|| "hello".to_string());
            pod.finalizers_mut().push("kube-finalizer".to_string());
            // NB: we are **not** pushing these back upstream - (Api::apply or Api::replace needed for it)
        }
        // check we can iterate over ObjectList normally - and check the mutations worked
        for pod in list {
            assert!(pod.annotations().get("kube-seen").is_some());
            assert!(pod.labels().get("kube.rs").is_some());
            assert!(pod.finalizers().contains(&"kube-finalizer".to_string()));
            assert!(pod.spec().containers.is_empty());
        }
        Ok(())
    }

    #[tokio::test]
    #[ignore] // needs cluster (fetches api resources, and lists all)
    #[cfg(all(feature = "derive"))]
    async fn derived_resources_discoverable() -> Result<(), Box<dyn std::error::Error>> {
        use crate::{
            core::{DynamicObject, GroupVersion, GroupVersionKind},
            discovery::{self, verbs, Discovery, Scope},
            runtime::wait::{await_condition, conditions},
        };

        #[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)]
        #[kube(group = "kube.rs", version = "v1", kind = "TestCr", namespaced)]
        #[kube(crates(kube_core = "crate::core"))] // for dev-dep test structure
        struct TestCrSpec {}

        let client = Client::try_default().await?;

        // install crd is installed
        let crds: Api<CustomResourceDefinition> = Api::all(client.clone());
        let ssapply = PatchParams::apply("kube").force();
        crds.patch("testcrs.kube.rs", &ssapply, &Patch::Apply(TestCr::crd()))
            .await?;
        let establish = await_condition(crds.clone(), "testcrs.kube.rs", conditions::is_crd_established());
        let _ = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await?;

        // create partial information for it to discover
        let gvk = GroupVersionKind::gvk("kube.rs", "v1", "TestCr");
        let gv = GroupVersion::gv("kube.rs", "v1");

        // discover by both (recommended kind on groupversion) and (pinned gvk) and they should equal
        let apigroup = discovery::oneshot::pinned_group(&client, &gv).await?;
        let (ar1, caps1) = apigroup.recommended_kind("TestCr").unwrap();
        let (ar2, caps2) = discovery::pinned_kind(&client, &gvk).await?;
        assert_eq!(caps1.operations.len(), caps2.operations.len());
        assert_eq!(ar1, ar2);
        assert_eq!(DynamicObject::api_version(&ar2), "kube.rs/v1");

        // run (almost) full discovery
        let discovery = Discovery::new(client.clone())
            // skip something in discovery (clux.dev crd being mutated in other tests)
            .exclude(&["rbac.authorization.k8s.io", "clux.dev"])
            .run()
            .await?;

        // check our custom resource first by resolving within groups
        assert!(discovery.has_group("kube.rs"));
        let (ar, _caps) = discovery.resolve_gvk(&gvk).unwrap();
        assert_eq!(ar.group, gvk.group);
        assert_eq!(ar.version, gvk.version);
        assert_eq!(ar.kind, gvk.kind);

        // check all non-excluded groups that are iterable
        for group in discovery.groups() {
            for (ar, caps) in group.recommended_resources() {
                if !caps.supports_operation(verbs::LIST) {
                    continue;
                }
                let api: Api<DynamicObject> = if caps.scope == Scope::Namespaced {
                    Api::default_namespaced_with(client.clone(), &ar)
                } else {
                    Api::all_with(client.clone(), &ar)
                };
                api.list(&Default::default()).await?;
            }
        }

        // cleanup
        crds.delete("testcrs.kube.rs", &DeleteParams::default()).await?;
        Ok(())
    }

    #[tokio::test]
    #[ignore] // needs cluster (will create await a pod)
    #[cfg(all(feature = "runtime"))]
    async fn pod_can_await_conditions() -> Result<(), Box<dyn std::error::Error>> {
        use crate::{
            api::{DeleteParams, PostParams},
            runtime::wait::{await_condition, conditions, delete::delete_and_finalize, Condition},
            Api, Client,
        };
        use k8s_openapi::api::core::v1::Pod;
        use std::time::Duration;
        use tokio::time::timeout;

        let client = Client::try_default().await?;
        let pods: Api<Pod> = Api::default_namespaced(client);

        // create busybox pod that's alive for at most 20s
        let data: Pod = serde_json::from_value(serde_json::json!({
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "name": "busybox-kube4",
                "labels": { "app": "kube-rs-test" },
            },
            "spec": {
                "terminationGracePeriodSeconds": 1,
                "restartPolicy": "Never",
                "containers": [{
                  "name": "busybox",
                  "image": "busybox:1.34.1",
                  "command": ["sh", "-c", "sleep 20"],
                }],
            }
        }))?;

        let pp = PostParams::default();
        assert_eq!(data.name(), pods.create(&pp, &data).await?.name());

        // Watch it phase for a few seconds
        let is_running = await_condition(pods.clone(), "busybox-kube4", conditions::is_pod_running());
        let _ = timeout(Duration::from_secs(15), is_running).await?;

        // Verify we can get it
        let pod = pods.get("busybox-kube4").await?;
        assert_eq!(pod.spec.as_ref().unwrap().containers[0].name, "busybox");

        // Wait for a more complicated condition: ContainersReady AND Initialized
        // TODO: remove these once we can write these functions generically
        fn is_each_container_ready() -> impl Condition<Pod> {
            |obj: Option<&Pod>| {
                if let Some(o) = obj {
                    if let Some(s) = &o.status {
                        if let Some(conds) = &s.conditions {
                            if let Some(pcond) = conds.iter().find(|c| c.type_ == "ContainersReady") {
                                return pcond.status == "True";
                            }
                        }
                    }
                }
                false
            }
        }
        let is_fully_ready = await_condition(
            pods.clone(),
            "busybox-kube4",
            conditions::is_pod_running().and(is_each_container_ready()),
        );
        let _ = timeout(Duration::from_secs(10), is_fully_ready).await?;

        // Delete it - and wait for deletion to complete
        let dp = DeleteParams::default();
        delete_and_finalize(pods.clone(), "busybox-kube4", &dp).await?;

        // verify it is properly gone
        assert!(pods.get("busybox-kube4").await.is_err());

        Ok(())
    }

    #[tokio::test]
    #[ignore] // needs cluster (lists cms)
    async fn api_get_opt_handles_404() -> Result<(), Box<dyn std::error::Error>> {
        let client = Client::try_default().await?;
        let api = Api::<ConfigMap>::default_namespaced(client);
        assert_eq!(
            api.get_opt("this-cm-does-not-exist-ajklisdhfqkljwhreq").await?,
            None
        );
        Ok(())
    }
}