Skip to main content

kube_runtime/
wait.rs

1//! Waits for objects to reach desired states
2use std::{future, pin::pin};
3
4use futures::TryStreamExt;
5use kube_client::{Api, Resource};
6use serde::de::DeserializeOwned;
7use std::fmt::Debug;
8use thiserror::Error;
9
10use crate::watcher::{self, watch_object};
11
12/// Errors from `await_condition`
13#[derive(Debug, Error)]
14pub enum Error {
15    /// The underlying watcher failed to probe the stream
16    #[error("failed to probe for whether the condition is fulfilled yet: {0}")]
17    ProbeFailed(#[source] watcher::Error),
18}
19
20/// Watch an object, and wait for some condition `cond` to return `true`.
21///
22/// `cond` is passed `Some` if the object is found, otherwise `None`.
23///
24/// The object is returned when the condition is fulfilled.
25///
26/// # Caveats
27///
28/// Keep in mind that the condition is typically fulfilled by an external service, which might not even be available. `await_condition`
29/// does *not* automatically add a timeout. If this is desired, wrap it in [`tokio::time::timeout`].
30///
31/// # Errors
32///
33/// Fails if the type is not known to the Kubernetes API, or if the [`Api`] does not have
34/// permission to `watch` and `list` it.
35///
36/// Does *not* fail if the object is not found.
37///
38/// # Usage
39///
40/// ```
41/// use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition;
42/// use kube::{Api, runtime::wait::{await_condition, conditions}};
43/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
44/// # let client: kube::Client = todo!();
45///
46/// let crds: Api<CustomResourceDefinition> = Api::all(client);
47/// // .. create or apply a crd here ..
48/// let establish = await_condition(crds, "foos.clux.dev", conditions::is_crd_established());
49/// let _ = tokio::time::timeout(std::time::Duration::from_secs(10), establish).await?;
50/// # Ok(())
51/// # }
52/// ```
53#[allow(clippy::missing_panics_doc)] // watch never actually terminates, expect cannot fail
54pub async fn await_condition<K>(api: Api<K>, name: &str, cond: impl Condition<K>) -> Result<Option<K>, Error>
55where
56    K: Clone + Debug + Send + DeserializeOwned + Resource + 'static,
57{
58    // Skip updates until the condition is satisfied.
59    let mut stream = pin!(watch_object(api, name).try_skip_while(|obj| {
60        let matches = cond.matches_object(obj.as_ref());
61        future::ready(Ok(!matches))
62    }));
63
64    // Then take the first update that satisfies the condition.
65    let obj = stream
66        .try_next()
67        .await
68        .map_err(Error::ProbeFailed)?
69        .expect("stream must not terminate");
70    Ok(obj)
71}
72
73/// A trait for condition functions to be used by [`await_condition`]
74///
75/// Note that this is auto-implemented for functions of type `fn(Option<&K>) -> bool`.
76///
77/// # Usage
78///
79/// ```
80/// use kube::runtime::wait::Condition;
81/// use k8s_openapi::api::core::v1::Pod;
82/// fn my_custom_condition(my_cond: &str) -> impl Condition<Pod> + '_ {
83///     move |obj: Option<&Pod>| {
84///         if let Some(pod) = &obj
85///             && let Some(status) = &pod.status
86///             && let Some(conds) = &status.conditions
87///             && let Some(pcond) = conds.iter().find(|c| c.type_ == my_cond)
88///         {
89///             return pcond.status == "True";
90///         }
91///         false
92///     }
93/// }
94/// ```
95pub trait Condition<K> {
96    /// The main trait condition that must be implemented
97    fn matches_object(&self, obj: Option<&K>) -> bool;
98
99    /// Returns a `Condition` that holds if `self` does not
100    ///
101    /// # Usage
102    ///
103    /// ```
104    /// # use kube_runtime::wait::Condition;
105    /// let condition: fn(Option<&()>) -> bool = |_| true;
106    /// assert!(condition.matches_object(None));
107    /// assert!(!condition.not().matches_object(None));
108    /// ```
109    fn not(self) -> conditions::Not<Self>
110    where
111        Self: Sized,
112    {
113        conditions::Not(self)
114    }
115
116    /// Returns a `Condition` that holds if `self` and `other` both do
117    ///
118    /// # Usage
119    ///
120    /// ```
121    /// # use kube_runtime::wait::Condition;
122    /// let cond_false: fn(Option<&()>) -> bool = |_| false;
123    /// let cond_true: fn(Option<&()>) -> bool = |_| true;
124    /// assert!(!cond_false.and(cond_false).matches_object(None));
125    /// assert!(!cond_false.and(cond_true).matches_object(None));
126    /// assert!(!cond_true.and(cond_false).matches_object(None));
127    /// assert!(cond_true.and(cond_true).matches_object(None));
128    /// ```
129    fn and<Other: Condition<K>>(self, other: Other) -> conditions::And<Self, Other>
130    where
131        Self: Sized,
132    {
133        conditions::And(self, other)
134    }
135
136    /// Returns a `Condition` that holds if either `self` or `other` does
137    ///
138    /// # Usage
139    ///
140    /// ```
141    /// # use kube_runtime::wait::Condition;
142    /// let cond_false: fn(Option<&()>) -> bool = |_| false;
143    /// let cond_true: fn(Option<&()>) -> bool = |_| true;
144    /// assert!(!cond_false.or(cond_false).matches_object(None));
145    /// assert!(cond_false.or(cond_true).matches_object(None));
146    /// assert!(cond_true.or(cond_false).matches_object(None));
147    /// assert!(cond_true.or(cond_true).matches_object(None));
148    /// ```
149    fn or<Other: Condition<K>>(self, other: Other) -> conditions::Or<Self, Other>
150    where
151        Self: Sized,
152    {
153        conditions::Or(self, other)
154    }
155}
156
157impl<K, F: Fn(Option<&K>) -> bool> Condition<K> for F {
158    fn matches_object(&self, obj: Option<&K>) -> bool {
159        (self)(obj)
160    }
161}
162
163/// Common conditions to wait for
164pub mod conditions {
165    pub use super::Condition;
166    use std::collections::BTreeMap;
167
168    use k8s_openapi::{
169        api::{
170            apps::v1::Deployment,
171            batch::v1::Job,
172            core::v1::{Container, ContainerStatus, Pod, Service},
173            networking::v1::Ingress,
174        },
175        apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition,
176        apimachinery::pkg::api::resource::Quantity,
177    };
178    use kube_client::Resource;
179
180    /// An await condition that returns `true` once the object has been deleted.
181    ///
182    /// An object is considered to be deleted if the object can no longer be found, or if its
183    /// [`uid`](kube_client::api::ObjectMeta#structfield.uid) changes. This means that an object is considered to be deleted even if we miss
184    /// the deletion event and the object is recreated in the meantime.
185    #[must_use]
186    pub fn is_deleted<K: Resource>(uid: &str) -> impl Condition<K> + '_ {
187        move |obj: Option<&K>| {
188            // NB: Object not found implies success.
189            obj.is_none_or(
190                // Object is found, but a changed uid would mean that it was deleted and recreated
191                |obj| obj.meta().uid.as_deref() != Some(uid),
192            )
193        }
194    }
195
196    /// An await condition that returns `true` once the object has been created.
197    ///
198    /// This is the counterpart to [`is_deleted`](super::conditions::is_deleted).
199    #[must_use]
200    pub fn is_created<K: Resource>() -> impl Condition<K> {
201        |obj: Option<&K>| obj.is_some()
202    }
203
204    /// An await condition for `CustomResourceDefinition` that returns `true` once it has been accepted and established
205    ///
206    /// Note that this condition only guarantees you that you can use `Api<CustomResourceDefinition>` when it is ready.
207    /// It usually takes extra time for Discovery to notice the custom resource, and there is no condition for this.
208    #[must_use]
209    pub fn is_crd_established() -> impl Condition<CustomResourceDefinition> {
210        |obj: Option<&CustomResourceDefinition>| {
211            if let Some(o) = obj
212                && let Some(s) = &o.status
213                && let Some(conds) = &s.conditions
214                && let Some(pcond) = conds.iter().find(|c| c.type_ == "Established")
215            {
216                return pcond.status == "True";
217            }
218            false
219        }
220    }
221
222    /// An await condition for `Pod` that returns `true` once it is running
223    #[must_use]
224    pub fn is_pod_running() -> impl Condition<Pod> {
225        |obj: Option<&Pod>| {
226            if let Some(pod) = &obj
227                && let Some(status) = &pod.status
228                && let Some(phase) = &status.phase
229            {
230                return phase == "Running";
231            }
232            false
233        }
234    }
235
236    // Kubernetes quantities have at most three decimal places and a maximum value that fits in
237    // i64. Scaling them to millis therefore fits in i128 and gives us one exact representation.
238    fn quantity_in_millis(quantity: &Quantity) -> Option<i128> {
239        let number_end = quantity
240            .0
241            .find(|character: char| !character.is_ascii_digit() && !matches!(character, '.' | '+' | '-'))
242            .unwrap_or(quantity.0.len());
243        let (number, suffix) = quantity.0.split_at(number_end);
244        let fractional_digits = match number.split_once('.') {
245            Some((_, fraction)) if !fraction.contains('.') => i32::try_from(fraction.len()).ok()?,
246            Some(_) => return None,
247            None => 0,
248        };
249        let mut mantissa = number.replace('.', "").parse::<i128>().ok()?;
250        let (decimal_exponent, binary_multiplier) = match suffix {
251            "" => (0, 1),
252            "m" => (-3, 1),
253            "k" | "K" => (3, 1),
254            "M" => (6, 1),
255            "G" => (9, 1),
256            "T" => (12, 1),
257            "P" => (15, 1),
258            "E" => (18, 1),
259            "Ki" => (0, 1_i128 << 10),
260            "Mi" => (0, 1_i128 << 20),
261            "Gi" => (0, 1_i128 << 30),
262            "Ti" => (0, 1_i128 << 40),
263            "Pi" => (0, 1_i128 << 50),
264            "Ei" => (0, 1_i128 << 60),
265            _ => {
266                let exponent = suffix.strip_prefix(['e', 'E'])?.parse::<i32>().ok()?;
267                (exponent, 1)
268            }
269        };
270
271        mantissa = mantissa.checked_mul(binary_multiplier)?;
272        if mantissa == 0 {
273            return Some(0);
274        }
275        let scale = decimal_exponent.checked_add(3)?.checked_sub(fractional_digits)?;
276
277        if scale >= 0 {
278            mantissa.checked_mul(10_i128.checked_pow(scale.unsigned_abs())?)
279        } else {
280            let divisor = 10_i128.checked_pow(scale.unsigned_abs())?;
281            (mantissa % divisor == 0).then_some(mantissa / divisor)
282        }
283    }
284
285    fn quantities_match(left: &Quantity, right: &Quantity) -> bool {
286        left == right
287            || matches!(
288                (quantity_in_millis(left), quantity_in_millis(right)),
289                (Some(left), Some(right)) if left == right
290            )
291    }
292
293    fn resource_maps_match(
294        spec: Option<&BTreeMap<String, Quantity>>,
295        status: Option<&BTreeMap<String, Quantity>>,
296    ) -> bool {
297        match (spec, status) {
298            (None, None) => true,
299            (Some(spec), Some(status)) => {
300                spec.len() == status.len()
301                    && spec.iter().all(|(name, quantity)| {
302                        status
303                            .get(name)
304                            .is_some_and(|actual| quantities_match(quantity, actual))
305                    })
306            }
307            _ => false,
308        }
309    }
310
311    fn container_resources_match(container: &Container, container_statuses: &[ContainerStatus]) -> bool {
312        container_statuses
313            .iter()
314            .find(|status| status.name == container.name)
315            .is_some_and(|status| {
316                let spec_resources = container.resources.as_ref();
317                let status_resources = status.resources.as_ref();
318                let requests_match = resource_maps_match(
319                    spec_resources.and_then(|resources| resources.requests.as_ref()),
320                    status_resources.and_then(|resources| resources.requests.as_ref()),
321                );
322                let limits_match = resource_maps_match(
323                    spec_resources.and_then(|resources| resources.limits.as_ref()),
324                    status_resources.and_then(|resources| resources.limits.as_ref()),
325                );
326
327                requests_match && limits_match
328            })
329    }
330
331    /// An await condition for `Pod` that returns `true` once an in-place resize operation has completed
332    ///
333    /// A resize is considered complete when every regular container and every restartable init
334    /// container has matching `resources` in its corresponding status (both `requests` and
335    /// `limits`), and neither `PodResizePending` nor `PodResizeInProgress` is present.
336    ///
337    /// Comparing resources prevents an early success before the kubelet creates resize conditions.
338    /// Requiring resize conditions to be absent prevents success when desired resources are changed
339    /// back while a resize is still in progress.
340    ///
341    /// See: <https://kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources/#pod-resize-status>
342    ///
343    /// Note: if the resize is rejected as `Infeasible` (e.g. exceeds node capacity),
344    /// spec and status will never converge and this condition will never return `true`.
345    /// Always wrap with [`tokio::time::timeout`].
346    ///
347    /// Resource quantities with fractional bytes, such as `0.1Gi`, may not converge if the
348    /// kubelet rounds the applied value. Avoid fractional byte values when resizing memory.
349    #[must_use]
350    pub fn is_pod_resized() -> impl Condition<Pod> {
351        |obj: Option<&Pod>| {
352            if let Some(pod) = obj
353                && let Some(status) = &pod.status
354                && let Some(spec) = &pod.spec
355                && let Some(container_statuses) = &status.container_statuses
356            {
357                let has_resize_condition = status.conditions.as_deref().is_some_and(|conditions| {
358                    conditions.iter().any(|condition| {
359                        matches!(
360                            condition.type_.as_str(),
361                            "PodResizePending" | "PodResizeInProgress"
362                        )
363                    })
364                });
365
366                if has_resize_condition {
367                    return false;
368                }
369
370                let containers_ready = spec
371                    .containers
372                    .iter()
373                    .all(|container| container_resources_match(container, container_statuses));
374
375                let init_container_statuses = status.init_container_statuses.as_deref().unwrap_or_default();
376                let init_containers_ready = spec
377                    .init_containers
378                    .as_deref()
379                    .unwrap_or_default()
380                    .iter()
381                    .filter(|container| container.restart_policy.as_deref() == Some("Always"))
382                    .all(|container| container_resources_match(container, init_container_statuses));
383
384                return containers_ready && init_containers_ready;
385            }
386            false
387        }
388    }
389
390    /// An await condition for `Job` that returns `true` once it is completed
391    #[must_use]
392    pub fn is_job_completed() -> impl Condition<Job> {
393        |obj: Option<&Job>| {
394            if let Some(job) = &obj
395                && let Some(s) = &job.status
396                && let Some(conds) = &s.conditions
397                && let Some(pcond) = conds.iter().find(|c| c.type_ == "Complete")
398            {
399                return pcond.status == "True";
400            }
401            false
402        }
403    }
404
405    /// An await condition for `Deployment` that returns `true` once the latest deployment has completed
406    ///
407    /// This looks for the condition that Kubernetes sets for completed deployments:
408    /// <https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#complete-deployment>
409    #[must_use]
410    pub fn is_deployment_completed() -> impl Condition<Deployment> {
411        |obj: Option<&Deployment>| {
412            if let Some(depl) = &obj
413                && let Some(s) = &depl.status
414                && let Some(conds) = &s.conditions
415                && let Some(dcond) = conds.iter().find(|c| {
416                    k8s_openapi::k8s_if_ge_1_37! {
417                        c.type_.as_deref() == Some("Progressing")
418                            && c.reason.as_deref() == Some("NewReplicaSetAvailable")
419                    }
420                    k8s_openapi::k8s_if_le_1_36! {
421                        c.type_ == "Progressing" && c.reason == Some("NewReplicaSetAvailable".to_string())
422                    }
423                })
424            {
425                k8s_openapi::k8s_if_ge_1_37! {
426                  return dcond.status.as_deref() == Some("True");
427                }
428                k8s_openapi::k8s_if_le_1_36! {
429                  return dcond.status == "True";
430                }
431            }
432            false
433        }
434    }
435
436    /// An await condition for `Service`s of type `LoadBalancer` that returns `true` once the backing load balancer has an external IP or hostname
437    #[must_use]
438    pub fn is_service_loadbalancer_provisioned() -> impl Condition<Service> {
439        |obj: Option<&Service>| {
440            if let Some(svc) = &obj
441                && let Some(spec) = &svc.spec
442            {
443                // ignore services that are not type LoadBalancer (return true immediately)
444                if spec.type_ != Some("LoadBalancer".to_string()) {
445                    return true;
446                }
447                // carry on if this is a LoadBalancer service
448                if let Some(s) = &svc.status
449                    && let Some(lbs) = &s.load_balancer
450                    && let Some(ings) = &lbs.ingress
451                {
452                    return ings.iter().all(|ip| ip.ip.is_some() || ip.hostname.is_some());
453                }
454            }
455            false
456        }
457    }
458
459    /// An await condition for `Ingress` that returns `true` once the backing load balancer has an external IP or hostname
460    #[must_use]
461    pub fn is_ingress_provisioned() -> impl Condition<Ingress> {
462        |obj: Option<&Ingress>| {
463            if let Some(ing) = &obj
464                && let Some(s) = &ing.status
465                && let Some(lbs) = &s.load_balancer
466                && let Some(ings) = &lbs.ingress
467            {
468                return ings.iter().all(|ip| ip.ip.is_some() || ip.hostname.is_some());
469            }
470            false
471        }
472    }
473
474    /// See [`Condition::not`]
475    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
476    pub struct Not<A>(pub(super) A);
477    impl<A: Condition<K>, K> Condition<K> for Not<A> {
478        fn matches_object(&self, obj: Option<&K>) -> bool {
479            !self.0.matches_object(obj)
480        }
481    }
482
483    /// See [`Condition::and`]
484    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
485    pub struct And<A, B>(pub(super) A, pub(super) B);
486    impl<A, B, K> Condition<K> for And<A, B>
487    where
488        A: Condition<K>,
489        B: Condition<K>,
490    {
491        fn matches_object(&self, obj: Option<&K>) -> bool {
492            self.0.matches_object(obj) && self.1.matches_object(obj)
493        }
494    }
495
496    /// See [`Condition::or`]
497    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
498    pub struct Or<A, B>(pub(super) A, pub(super) B);
499    impl<A, B, K> Condition<K> for Or<A, B>
500    where
501        A: Condition<K>,
502        B: Condition<K>,
503    {
504        fn matches_object(&self, obj: Option<&K>) -> bool {
505            self.0.matches_object(obj) || self.1.matches_object(obj)
506        }
507    }
508
509    mod tests {
510        #[test]
511        /// pass when CRD is established
512        fn crd_established_ok() {
513            use super::{Condition, is_crd_established};
514
515            let crd = r#"
516                apiVersion: apiextensions.k8s.io/v1
517                kind: CustomResourceDefinition
518                metadata:
519                  name: testthings.kube.rs
520                spec:
521                  group: kube.rs
522                  names:
523                    categories: []
524                    kind: TestThing
525                    plural: testthings
526                    shortNames: []
527                    singular: testthing
528                  scope: Namespaced
529                  versions:
530                    - additionalPrinterColumns: []
531                      name: v1
532                      schema:
533                        openAPIV3Schema:
534                          type: object
535                          x-kubernetes-preserve-unknown-fields: true
536                      served: true
537                      storage: true
538                status:
539                  acceptedNames:
540                    kind: TestThing
541                    listKind: TestThingList
542                    plural: testthings
543                    singular: testthing
544                  conditions:
545                    - lastTransitionTime: "2025-03-06T03:10:03Z"
546                      message: no conflicts found
547                      reason: NoConflicts
548                      status: "True"
549                      type: NamesAccepted
550                    - lastTransitionTime: "2025-03-06T03:10:03Z"
551                      message: the initial names have been accepted
552                      reason: InitialNamesAccepted
553                      status: "True"
554                      type: Established
555                storedVersions:
556                  - v1
557            "#;
558
559            let c = serde_saphyr::from_str(crd).unwrap();
560            assert!(is_crd_established().matches_object(Some(&c)))
561        }
562
563        #[test]
564        /// fail when CRD is not yet ready
565        fn crd_established_fail() {
566            use super::{Condition, is_crd_established};
567
568            let crd = r#"
569                apiVersion: apiextensions.k8s.io/v1
570                kind: CustomResourceDefinition
571                metadata:
572                  name: testthings.kube.rs
573                spec:
574                  group: kube.rs
575                  names:
576                    categories: []
577                    kind: TestThing
578                    plural: testthings
579                    shortNames: []
580                    singular: testthing
581                  scope: Namespaced
582                  versions:
583                    - additionalPrinterColumns: []
584                      name: v1
585                      schema:
586                        openAPIV3Schema:
587                          type: object
588                          x-kubernetes-preserve-unknown-fields: true
589                      served: true
590                      storage: true
591                status:
592                  acceptedNames:
593                    kind: TestThing
594                    listKind: TestThingList
595                    plural: testthings
596                    singular: testthing
597                  conditions:
598                    - lastTransitionTime: "2025-03-06T03:10:03Z"
599                      message: no conflicts found
600                      reason: NoConflicts
601                      status: "True"
602                      type: NamesAccepted
603                    - lastTransitionTime: "2025-03-06T03:10:03Z"
604                      message: the initial names have been accepted
605                      reason: InitialNamesAccepted
606                      status: "False"
607                      type: Established
608                storedVersions:
609                  - v1
610            "#;
611
612            let c = serde_saphyr::from_str(crd).unwrap();
613            assert!(!is_crd_established().matches_object(Some(&c)))
614        }
615
616        #[test]
617        /// fail when CRD does not exist
618        fn crd_established_missing() {
619            use super::{Condition, is_crd_established};
620
621            assert!(!is_crd_established().matches_object(None))
622        }
623
624        #[test]
625        /// pass when pod is running
626        fn pod_running_ok() {
627            use super::{Condition, is_pod_running};
628
629            let pod = r#"
630                apiVersion: v1
631                kind: Pod
632                metadata:
633                  namespace: default
634                  name: testpod
635                spec:
636                  containers:
637                    - name: testcontainer
638                      image: alpine
639                      command: [ sleep ]
640                      args: [ "100000" ]
641                status:
642                  conditions:
643                    - lastProbeTime: null
644                      lastTransitionTime: "2025-03-06T03:53:07Z"
645                      status: "True"
646                      type: PodReadyToStartContainers
647                    - lastProbeTime: null
648                      lastTransitionTime: "2025-03-06T03:52:58Z"
649                      status: "True"
650                      type: Initialized
651                    - lastProbeTime: null
652                      lastTransitionTime: "2025-03-06T03:53:24Z"
653                      status: "True"
654                      type: Ready
655                    - lastProbeTime: null
656                      lastTransitionTime: "2025-03-06T03:53:24Z"
657                      status: "True"
658                      type: ContainersReady
659                    - lastProbeTime: null
660                      lastTransitionTime: "2025-03-06T03:52:58Z"
661                      status: "True"
662                      type: PodScheduled
663                  containerStatuses:
664                    - containerID: containerd://598323380ae59d60c1ab98f9091c94659137a976d52136a8083775d47fea5875
665                      image: docker.io/library/alpine:latest
666                      imageID: docker.io/library/alpine@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
667                      lastState: {}
668                      name: testcontainer
669                      ready: true
670                      restartCount: 0
671                      started: true
672                      state:
673                        running:
674                          startedAt: "2025-03-06T03:59:20Z"
675                  phase: Running
676                  qosClass: Burstable
677            "#;
678
679            let p = serde_saphyr::from_str(pod).unwrap();
680            assert!(is_pod_running().matches_object(Some(&p)))
681        }
682
683        #[test]
684        /// fail if pod is unschedulable
685        fn pod_running_unschedulable() {
686            use super::{Condition, is_pod_running};
687
688            let pod = r#"
689                apiVersion: v1
690                kind: Pod
691                metadata:
692                  namespace: default
693                  name: testpod
694                spec:
695                  containers:
696                    - name: testcontainer
697                      image: alpine
698                      command: [ sleep ]
699                      args: [ "100000" ]
700                status:
701                  conditions:
702                    - lastProbeTime: null
703                      lastTransitionTime: "2025-03-06T03:52:25Z"
704                      message: '0/1 nodes are available: 1 node(s) were unschedulable. preemption: 0/1 nodes are available: 1 Preemption is not helpful for scheduling.'
705                      reason: Unschedulable
706                      status: "False"
707                      type: PodScheduled
708                  phase: Pending
709                  qosClass: Burstable
710            "#;
711
712            let p = serde_saphyr::from_str(pod).unwrap();
713            assert!(!is_pod_running().matches_object(Some(&p)))
714        }
715
716        #[test]
717        /// fail if pod does not exist
718        fn pod_running_missing() {
719            use super::{Condition, is_pod_running};
720
721            assert!(!is_pod_running().matches_object(None))
722        }
723
724        #[test]
725        fn pod_resize_equivalent_quantities_match() {
726            use k8s_openapi::apimachinery::pkg::api::resource::Quantity;
727
728            use super::quantities_match;
729
730            let quantity = |value: &str| Quantity(value.to_string());
731
732            for (left, right) in [
733                ("268435456", "256Mi"),
734                ("1e0", "1"),
735                ("0.2", "200m"),
736                ("1024", "1Ki"),
737                ("1e3", "1k"),
738                ("0.1Gi", "107374182.4"),
739            ] {
740                assert!(quantities_match(&quantity(left), &quantity(right)));
741            }
742            assert!(!quantities_match(&quantity("268435455"), &quantity("256Mi")));
743            assert!(!quantities_match(&quantity("0.1Gi"), &quantity("107374183")));
744        }
745
746        #[test]
747        /// pass when spec and status resources match (resize complete)
748        fn pod_resized_complete() {
749            use super::{Condition, is_pod_resized};
750
751            let pod = r#"
752                apiVersion: v1
753                kind: Pod
754                metadata:
755                  name: resize-demo
756                  namespace: default
757                spec:
758                  containers:
759                  - name: app
760                    image: alpine:3.23
761                    resources:
762                      requests:
763                        cpu: "200m"
764                        memory: "256Mi"
765                      limits:
766                        cpu: "400m"
767                        memory: "512Mi"
768                status:
769                  phase: Running
770                  containerStatuses:
771                  - name: app
772                    image: alpine:3.23
773                    resources:
774                      requests:
775                        cpu: "200m"
776                        memory: "256Mi"
777                      limits:
778                        cpu: "400m"
779                        memory: "512Mi"
780            "#;
781
782            let p = serde_saphyr::from_str(pod).unwrap();
783            assert!(is_pod_resized().matches_object(Some(&p)))
784        }
785
786        #[cfg(test)]
787        fn pod_with_matching_resources_and_condition(condition_type: &str, status: &str) -> super::Pod {
788            let pod = format!(
789                r#"
790                apiVersion: v1
791                kind: Pod
792                metadata:
793                  name: resize-demo
794                  namespace: default
795                spec:
796                  containers:
797                  - name: app
798                    image: alpine:3.23
799                    resources:
800                      requests:
801                        cpu: "200m"
802                        memory: "256Mi"
803                      limits:
804                        cpu: "400m"
805                        memory: "512Mi"
806                status:
807                  conditions:
808                  - type: {condition_type}
809                    status: "{status}"
810                  containerStatuses:
811                  - name: app
812                    image: alpine:3.23
813                    resources:
814                      requests:
815                        cpu: "200m"
816                        memory: "256Mi"
817                      limits:
818                        cpu: "400m"
819                        memory: "512Mi"
820                "#
821            );
822
823            serde_saphyr::from_str(&pod).unwrap()
824        }
825
826        #[test]
827        /// fail while a resize condition is present, even when resources match
828        fn pod_resize_condition_present() {
829            use super::{Condition, is_pod_resized};
830
831            for (condition_type, status) in [("PodResizePending", "False"), ("PodResizeInProgress", "True")] {
832                let p = pod_with_matching_resources_and_condition(condition_type, status);
833                assert!(
834                    !is_pod_resized().matches_object(Some(&p)),
835                    "{condition_type} with status {status} must block resize completion"
836                );
837            }
838        }
839
840        #[test]
841        /// pass when resources match and only unrelated conditions are present
842        fn pod_resize_unrelated_condition() {
843            use super::{Condition, is_pod_resized};
844
845            let p = pod_with_matching_resources_and_condition("Ready", "True");
846            assert!(is_pod_resized().matches_object(Some(&p)));
847        }
848
849        #[test]
850        /// pass when spec and status resources use equivalent quantity formats
851        fn pod_resized_equivalent_quantity_formats() {
852            use super::{Condition, is_pod_resized};
853
854            let pod = r#"
855                apiVersion: v1
856                kind: Pod
857                metadata:
858                  name: resize-demo
859                  namespace: default
860                spec:
861                  containers:
862                  - name: app
863                    image: nginx:stable-alpine
864                    resources:
865                      requests:
866                        cpu: "1e0"
867                      limits:
868                        memory: "268435456"
869                status:
870                  phase: Running
871                  containerStatuses:
872                  - name: app
873                    image: nginx:stable-alpine
874                    resources:
875                      requests:
876                        cpu: "1"
877                      limits:
878                        memory: "256Mi"
879            "#;
880
881            let p = serde_saphyr::from_str(pod).unwrap();
882            assert!(is_pod_resized().matches_object(Some(&p)))
883        }
884
885        #[test]
886        /// pass when containers have no resources defined
887        fn pod_resized_no_resources() {
888            use super::{Condition, is_pod_resized};
889
890            let pod = r"
891                apiVersion: v1
892                kind: Pod
893                metadata:
894                  name: resize-demo
895                  namespace: default
896                spec:
897                  containers:
898                  - name: app
899                    image: alpine:3.23
900                status:
901                  phase: Running
902                  containerStatuses:
903                  - name: app
904                    image: alpine:3.23
905            ";
906
907            let p = serde_saphyr::from_str(pod).unwrap();
908            assert!(is_pod_resized().matches_object(Some(&p)))
909        }
910
911        #[test]
912        /// fail if pod does not exist
913        fn pod_resized_missing() {
914            use super::{Condition, is_pod_resized};
915
916            assert!(!is_pod_resized().matches_object(None))
917        }
918
919        #[test]
920        /// fail when spec resources differ from status (resize in progress)
921        fn pod_resize_in_progress() {
922            use super::{Condition, is_pod_resized};
923
924            let pod = r#"
925                apiVersion: v1
926                kind: Pod
927                metadata:
928                  name: resize-demo
929                  namespace: default
930                spec:
931                  containers:
932                  - name: app
933                    image: alpine:3.23
934                    resources:
935                      requests:
936                        cpu: "200m"
937                        memory: "256Mi"
938                      limits:
939                        cpu: "400m"
940                        memory: "512Mi"
941                status:
942                  phase: Running
943                  containerStatuses:
944                  - name: app
945                    image: alpine:3.23
946                    resources:
947                      requests:
948                        cpu: "100m"
949                        memory: "128Mi"
950                      limits:
951                        cpu: "200m"
952                        memory: "256Mi"
953            "#;
954
955            let p = serde_saphyr::from_str(pod).unwrap();
956            assert!(!is_pod_resized().matches_object(Some(&p)))
957        }
958
959        #[test]
960        /// fail when only limits differ (partial resize)
961        fn pod_resize_limits_differ() {
962            use super::{Condition, is_pod_resized};
963
964            let pod = r#"
965                apiVersion: v1
966                kind: Pod
967                metadata:
968                  name: resize-demo
969                  namespace: default
970                spec:
971                  containers:
972                  - name: app
973                    image: alpine:3.23
974                    resources:
975                      requests:
976                        cpu: "200m"
977                      limits:
978                        cpu: "400m"
979                status:
980                  phase: Running
981                  containerStatuses:
982                  - name: app
983                    image: alpine:3.23
984                    resources:
985                      requests:
986                        cpu: "200m"
987                      limits:
988                        cpu: "200m"
989            "#;
990
991            let p = serde_saphyr::from_str(pod).unwrap();
992            assert!(!is_pod_resized().matches_object(Some(&p)))
993        }
994
995        #[test]
996        /// fail when container status is missing for a spec container
997        fn pod_resize_missing_container_status() {
998            use super::{Condition, is_pod_resized};
999
1000            let pod = r#"
1001                apiVersion: v1
1002                kind: Pod
1003                metadata:
1004                  name: resize-demo
1005                  namespace: default
1006                spec:
1007                  containers:
1008                  - name: app
1009                    image: alpine:3.23
1010                    resources:
1011                      requests:
1012                        cpu: "200m"
1013                status:
1014                  phase: Running
1015                  containerStatuses:
1016                  - name: other
1017                    image: alpine:3.23
1018            "#;
1019
1020            let p = serde_saphyr::from_str(pod).unwrap();
1021            assert!(!is_pod_resized().matches_object(Some(&p)))
1022        }
1023
1024        #[test]
1025        /// fail when a restartable init container status is missing
1026        fn pod_resize_missing_restartable_init_container_status() {
1027            use super::{Condition, is_pod_resized};
1028
1029            let pod = r#"
1030                apiVersion: v1
1031                kind: Pod
1032                metadata:
1033                  name: resize-demo
1034                  namespace: default
1035                spec:
1036                  initContainers:
1037                  - name: sidecar
1038                    image: nginx:stable-alpine
1039                    restartPolicy: Always
1040                    resources:
1041                      requests:
1042                        cpu: "200m"
1043                  containers:
1044                  - name: app
1045                    image: nginx:stable-alpine
1046                    resources:
1047                      requests:
1048                        cpu: "200m"
1049                status:
1050                  phase: Running
1051                  containerStatuses:
1052                  - name: app
1053                    image: nginx:stable-alpine
1054                    resources:
1055                      requests:
1056                        cpu: "200m"
1057            "#;
1058
1059            let p = serde_saphyr::from_str(pod).unwrap();
1060            assert!(!is_pod_resized().matches_object(Some(&p)))
1061        }
1062
1063        #[test]
1064        /// pass when a restartable init container has matching resources
1065        fn pod_resize_restartable_init_container_complete() {
1066            use super::{Condition, is_pod_resized};
1067
1068            let pod = r#"
1069                apiVersion: v1
1070                kind: Pod
1071                metadata:
1072                  name: resize-demo
1073                  namespace: default
1074                spec:
1075                  initContainers:
1076                  - name: sidecar
1077                    image: nginx:stable-alpine
1078                    restartPolicy: Always
1079                    resources:
1080                      requests:
1081                        cpu: "200m"
1082                      limits:
1083                        cpu: "400m"
1084                  containers:
1085                  - name: app
1086                    image: nginx:stable-alpine
1087                    resources:
1088                      requests:
1089                        cpu: "200m"
1090                status:
1091                  phase: Running
1092                  initContainerStatuses:
1093                  - name: sidecar
1094                    image: nginx:stable-alpine
1095                    resources:
1096                      requests:
1097                        cpu: "200m"
1098                      limits:
1099                        cpu: "400m"
1100                  containerStatuses:
1101                  - name: app
1102                    image: nginx:stable-alpine
1103                    resources:
1104                      requests:
1105                        cpu: "200m"
1106            "#;
1107
1108            let p = serde_saphyr::from_str(pod).unwrap();
1109            assert!(is_pod_resized().matches_object(Some(&p)))
1110        }
1111
1112        #[test]
1113        /// fail when a restartable init container still has different resources
1114        fn pod_resize_restartable_init_container_in_progress() {
1115            use super::{Condition, is_pod_resized};
1116
1117            let pod = r#"
1118                apiVersion: v1
1119                kind: Pod
1120                metadata:
1121                  name: resize-demo
1122                  namespace: default
1123                spec:
1124                  initContainers:
1125                  - name: sidecar
1126                    image: nginx:stable-alpine
1127                    restartPolicy: Always
1128                    resources:
1129                      requests:
1130                        cpu: "200m"
1131                  containers:
1132                  - name: app
1133                    image: nginx:stable-alpine
1134                    resources:
1135                      requests:
1136                        cpu: "200m"
1137                status:
1138                  phase: Running
1139                  initContainerStatuses:
1140                  - name: sidecar
1141                    image: nginx:stable-alpine
1142                    resources:
1143                      requests:
1144                        cpu: "100m"
1145                  containerStatuses:
1146                  - name: app
1147                    image: nginx:stable-alpine
1148                    resources:
1149                      requests:
1150                        cpu: "200m"
1151            "#;
1152
1153            let p = serde_saphyr::from_str(pod).unwrap();
1154            assert!(!is_pod_resized().matches_object(Some(&p)))
1155        }
1156
1157        #[test]
1158        /// pass when multiple containers all have matching resources
1159        fn pod_resize_multiple_containers_complete() {
1160            use super::{Condition, is_pod_resized};
1161
1162            let pod = r#"
1163                apiVersion: v1
1164                kind: Pod
1165                metadata:
1166                  name: resize-demo
1167                  namespace: default
1168                spec:
1169                  containers:
1170                  - name: app
1171                    image: alpine:3.23
1172                    resources:
1173                      requests:
1174                        cpu: "200m"
1175                      limits:
1176                        cpu: "400m"
1177                  - name: sidecar
1178                    image: busybox
1179                    resources:
1180                      requests:
1181                        memory: "64Mi"
1182                status:
1183                  phase: Running
1184                  containerStatuses:
1185                  - name: app
1186                    image: alpine:3.23
1187                    resources:
1188                      requests:
1189                        cpu: "200m"
1190                      limits:
1191                        cpu: "400m"
1192                  - name: sidecar
1193                    image: busybox
1194                    resources:
1195                      requests:
1196                        memory: "64Mi"
1197            "#;
1198
1199            let p = serde_saphyr::from_str(pod).unwrap();
1200            assert!(is_pod_resized().matches_object(Some(&p)))
1201        }
1202
1203        #[test]
1204        /// fail when one of multiple containers has mismatched resources
1205        fn pod_resize_multiple_containers_partial() {
1206            use super::{Condition, is_pod_resized};
1207
1208            let pod = r#"
1209                apiVersion: v1
1210                kind: Pod
1211                metadata:
1212                  name: resize-demo
1213                  namespace: default
1214                spec:
1215                  containers:
1216                  - name: app
1217                    image: alpine:3.23
1218                    resources:
1219                      requests:
1220                        cpu: "200m"
1221                  - name: sidecar
1222                    image: busybox
1223                    resources:
1224                      requests:
1225                        memory: "128Mi"
1226                status:
1227                  phase: Running
1228                  containerStatuses:
1229                  - name: app
1230                    image: alpine:3.23
1231                    resources:
1232                      requests:
1233                        cpu: "200m"
1234                  - name: sidecar
1235                    image: busybox
1236                    resources:
1237                      requests:
1238                        memory: "64Mi"
1239            "#;
1240
1241            let p = serde_saphyr::from_str(pod).unwrap();
1242            assert!(!is_pod_resized().matches_object(Some(&p)))
1243        }
1244
1245        #[test]
1246        /// pass if job completed
1247        fn job_completed_ok() {
1248            use super::{Condition, is_job_completed};
1249
1250            let job = r#"
1251                apiVersion: batch/v1
1252                kind: Job
1253                metadata:
1254                  name: pi
1255                  namespace: default
1256                spec:
1257                  template:
1258                    spec:
1259                      containers:
1260                      - name: pi
1261                        command:
1262                        - perl
1263                        - -Mbignum=bpi
1264                        - -wle
1265                        - print bpi(2000)
1266                        image: perl:5.34.0
1267                        imagePullPolicy: IfNotPresent
1268                status:
1269                  completionTime: "2025-03-06T05:27:56Z"
1270                  conditions:
1271                  - lastProbeTime: "2025-03-06T05:27:56Z"
1272                    lastTransitionTime: "2025-03-06T05:27:56Z"
1273                    message: Reached expected number of succeeded pods
1274                    reason: CompletionsReached
1275                    status: "True"
1276                    type: SuccessCriteriaMet
1277                  - lastProbeTime: "2025-03-06T05:27:56Z"
1278                    lastTransitionTime: "2025-03-06T05:27:56Z"
1279                    message: Reached expected number of succeeded pods
1280                    reason: CompletionsReached
1281                    status: "True"
1282                    type: Complete
1283                  ready: 0
1284                  startTime: "2025-03-06T05:27:27Z"
1285                  succeeded: 1
1286                  terminating: 0
1287                  uncountedTerminatedPods: {}
1288            "#;
1289
1290            let j = serde_saphyr::from_str(job).unwrap();
1291            assert!(is_job_completed().matches_object(Some(&j)))
1292        }
1293
1294        #[test]
1295        /// fail if job is still in progress
1296        fn job_completed_running() {
1297            use super::{Condition, is_job_completed};
1298
1299            let job = r#"
1300                apiVersion: batch/v1
1301                kind: Job
1302                metadata:
1303                  name: pi
1304                  namespace: default
1305                spec:
1306                  backoffLimit: 4
1307                  completionMode: NonIndexed
1308                  completions: 1
1309                  manualSelector: false
1310                  parallelism: 1
1311                  template:
1312                    spec:
1313                      containers:
1314                      - name: pi
1315                        command:
1316                        - perl
1317                        - -Mbignum=bpi
1318                        - -wle
1319                        - print bpi(2000)
1320                        image: perl:5.34.0
1321                        imagePullPolicy: IfNotPresent
1322                status:
1323                  active: 1
1324                  ready: 0
1325                  startTime: "2025-03-06T05:27:27Z"
1326                  terminating: 0
1327                  uncountedTerminatedPods: {}
1328            "#;
1329
1330            let j = serde_saphyr::from_str(job).unwrap();
1331            assert!(!is_job_completed().matches_object(Some(&j)))
1332        }
1333
1334        #[test]
1335        /// fail if job does not exist
1336        fn job_completed_missing() {
1337            use super::{Condition, is_job_completed};
1338
1339            assert!(!is_job_completed().matches_object(None))
1340        }
1341
1342        #[test]
1343        /// pass when deployment has been fully rolled out
1344        fn deployment_completed_ok() {
1345            use super::{Condition, is_deployment_completed};
1346
1347            let depl = r#"
1348                apiVersion: apps/v1
1349                kind: Deployment
1350                metadata:
1351                  name: testapp
1352                  namespace: default
1353                spec:
1354                  progressDeadlineSeconds: 600
1355                  replicas: 3
1356                  revisionHistoryLimit: 10
1357                  selector:
1358                    matchLabels:
1359                      app: test
1360                  strategy:
1361                    rollingUpdate:
1362                      maxSurge: 25%
1363                      maxUnavailable: 25%
1364                    type: RollingUpdate
1365                  template:
1366                    metadata:
1367                      creationTimestamp: null
1368                      labels:
1369                        app: test
1370                    spec:
1371                      containers:
1372                      - image: postgres
1373                        imagePullPolicy: Always
1374                        name: postgres
1375                        ports:
1376                        - containerPort: 5432
1377                          protocol: TCP
1378                        env:
1379                        - name: POSTGRES_PASSWORD
1380                          value: foobar
1381                status:
1382                  availableReplicas: 3
1383                  conditions:
1384                  - lastTransitionTime: "2025-03-06T06:06:57Z"
1385                    lastUpdateTime: "2025-03-06T06:06:57Z"
1386                    message: Deployment has minimum availability.
1387                    reason: MinimumReplicasAvailable
1388                    status: "True"
1389                    type: Available
1390                  - lastTransitionTime: "2025-03-06T06:03:20Z"
1391                    lastUpdateTime: "2025-03-06T06:06:57Z"
1392                    message: ReplicaSet "testapp-7fcd4b58c9" has successfully progressed.
1393                    reason: NewReplicaSetAvailable
1394                    status: "True"
1395                    type: Progressing
1396                  observedGeneration: 2
1397                  readyReplicas: 3
1398                  replicas: 3
1399                  updatedReplicas: 3
1400            "#;
1401
1402            let d = serde_saphyr::from_str(depl).unwrap();
1403            assert!(is_deployment_completed().matches_object(Some(&d)))
1404        }
1405
1406        #[test]
1407        /// fail if deployment update is still rolling out
1408        fn deployment_completed_pending() {
1409            use super::{Condition, is_deployment_completed};
1410
1411            let depl = r#"
1412                apiVersion: apps/v1
1413                kind: Deployment
1414                metadata:
1415                  name: testapp
1416                  namespace: default
1417                spec:
1418                  progressDeadlineSeconds: 600
1419                  replicas: 3
1420                  revisionHistoryLimit: 10
1421                  selector:
1422                    matchLabels:
1423                      app: test
1424                  strategy:
1425                    rollingUpdate:
1426                      maxSurge: 25%
1427                      maxUnavailable: 25%
1428                    type: RollingUpdate
1429                  template:
1430                    metadata:
1431                      creationTimestamp: null
1432                      labels:
1433                        app: test
1434                    spec:
1435                      containers:
1436                      - image: postgres
1437                        imagePullPolicy: Always
1438                        name: postgres
1439                        ports:
1440                        - containerPort: 5432
1441                          protocol: TCP
1442                        env:
1443                        - name: POSTGRES_PASSWORD
1444                          value: foobar
1445                status:
1446                  conditions:
1447                  - lastTransitionTime: "2025-03-06T06:03:20Z"
1448                    lastUpdateTime: "2025-03-06T06:03:20Z"
1449                    message: Deployment does not have minimum availability.
1450                    reason: MinimumReplicasUnavailable
1451                    status: "False"
1452                    type: Available
1453                  - lastTransitionTime: "2025-03-06T06:03:20Z"
1454                    lastUpdateTime: "2025-03-06T06:03:20Z"
1455                    message: ReplicaSet "testapp-77789cd7d4" is progressing.
1456                    reason: ReplicaSetUpdated
1457                    status: "True"
1458                    type: Progressing
1459                  observedGeneration: 1
1460                  replicas: 3
1461                  unavailableReplicas: 3
1462                  updatedReplicas: 3
1463            "#;
1464
1465            let d = serde_saphyr::from_str(depl).unwrap();
1466            assert!(!is_deployment_completed().matches_object(Some(&d)))
1467        }
1468
1469        #[test]
1470        /// fail if deployment does not exist
1471        fn deployment_completed_missing() {
1472            use super::{Condition, is_deployment_completed};
1473
1474            assert!(!is_deployment_completed().matches_object(None))
1475        }
1476
1477        #[test]
1478        /// pass if loadbalancer service has received a loadbalancer IP
1479        fn service_lb_provisioned_ok_ip() {
1480            use super::{Condition, is_service_loadbalancer_provisioned};
1481
1482            let service = r"
1483                apiVersion: v1
1484                kind: Service
1485                metadata:
1486                  name: test
1487                spec:
1488                  selector:
1489                    app.kubernetes.io/name: test
1490                  type: LoadBalancer
1491                  ports:
1492                    - protocol: TCP
1493                      port: 80
1494                      targetPort: 9376
1495                  clusterIP: 10.0.171.239
1496                status:
1497                  loadBalancer:
1498                    ingress:
1499                      - ip: 192.0.2.127
1500            ";
1501
1502            let s = serde_saphyr::from_str(service).unwrap();
1503            assert!(is_service_loadbalancer_provisioned().matches_object(Some(&s)))
1504        }
1505
1506        #[test]
1507        /// pass if loadbalancer service has received a loadbalancer hostname
1508        fn service_lb_provisioned_ok_hostname() {
1509            use super::{Condition, is_service_loadbalancer_provisioned};
1510
1511            let service = r"
1512                apiVersion: v1
1513                kind: Service
1514                metadata:
1515                  name: test
1516                spec:
1517                  selector:
1518                    app.kubernetes.io/name: test
1519                  type: LoadBalancer
1520                  ports:
1521                    - protocol: TCP
1522                      port: 80
1523                      targetPort: 9376
1524                  clusterIP: 10.0.171.239
1525                status:
1526                  loadBalancer:
1527                    ingress:
1528                      - hostname: example.exposed.service
1529            ";
1530
1531            let s = serde_saphyr::from_str(service).unwrap();
1532            assert!(is_service_loadbalancer_provisioned().matches_object(Some(&s)))
1533        }
1534
1535        #[test]
1536        /// fail if loadbalancer service is still waiting for a LB
1537        fn service_lb_provisioned_pending() {
1538            use super::{Condition, is_service_loadbalancer_provisioned};
1539
1540            let service = r"
1541                apiVersion: v1
1542                kind: Service
1543                metadata:
1544                  name: test
1545                spec:
1546                  selector:
1547                    app.kubernetes.io/name: test
1548                  type: LoadBalancer
1549                  ports:
1550                    - protocol: TCP
1551                      port: 80
1552                      targetPort: 9376
1553                  clusterIP: 10.0.171.239
1554                status:
1555                  loadBalancer: {}
1556            ";
1557
1558            let s = serde_saphyr::from_str(service).unwrap();
1559            assert!(!is_service_loadbalancer_provisioned().matches_object(Some(&s)))
1560        }
1561
1562        #[test]
1563        /// pass if service is not a loadbalancer
1564        fn service_lb_provisioned_not_loadbalancer() {
1565            use super::{Condition, is_service_loadbalancer_provisioned};
1566
1567            let service = r"
1568                apiVersion: v1
1569                kind: Service
1570                metadata:
1571                  name: test
1572                spec:
1573                  selector:
1574                    app.kubernetes.io/name: test
1575                  type: ClusterIP
1576                  ports:
1577                    - protocol: TCP
1578                      port: 80
1579                      targetPort: 9376
1580                status:
1581                  loadBalancer: {}
1582            ";
1583
1584            let s = serde_saphyr::from_str(service).unwrap();
1585            assert!(is_service_loadbalancer_provisioned().matches_object(Some(&s)))
1586        }
1587
1588        #[test]
1589        /// fail if service does not exist
1590        fn service_lb_provisioned_missing() {
1591            use super::{Condition, is_service_loadbalancer_provisioned};
1592
1593            assert!(!is_service_loadbalancer_provisioned().matches_object(None))
1594        }
1595
1596        #[test]
1597        /// pass when ingress has received a loadbalancer IP
1598        fn ingress_provisioned_ok_ip() {
1599            use super::{Condition, is_ingress_provisioned};
1600
1601            let ingress = r#"
1602                apiVersion: networking.k8s.io/v1
1603                kind: Ingress
1604                metadata:
1605                  name: test
1606                  namespace: default
1607                  resourceVersion: "1401"
1608                  uid: d653ee4d-0adb-40d9-b03c-7f84f35d4a67
1609                spec:
1610                  ingressClassName: nginx
1611                  rules:
1612                  - host: httpbin.local
1613                    http:
1614                      paths:
1615                      - path: /
1616                        backend:
1617                          service:
1618                            name: httpbin
1619                            port:
1620                              number: 80
1621                status:
1622                  loadBalancer:
1623                    ingress:
1624                      - ip: 10.89.7.3
1625            "#;
1626
1627            let i = serde_saphyr::from_str(ingress).unwrap();
1628            assert!(is_ingress_provisioned().matches_object(Some(&i)))
1629        }
1630
1631        #[test]
1632        /// pass when ingress has received a loadbalancer hostname
1633        fn ingress_provisioned_ok_hostname() {
1634            use super::{Condition, is_ingress_provisioned};
1635
1636            let ingress = r#"
1637                apiVersion: networking.k8s.io/v1
1638                kind: Ingress
1639                metadata:
1640                  name: test
1641                  namespace: default
1642                  resourceVersion: "1401"
1643                  uid: d653ee4d-0adb-40d9-b03c-7f84f35d4a67
1644                spec:
1645                  ingressClassName: nginx
1646                  rules:
1647                  - host: httpbin.local
1648                    http:
1649                      paths:
1650                      - path: /
1651                        backend:
1652                          service:
1653                            name: httpbin
1654                            port:
1655                              number: 80
1656                status:
1657                  loadBalancer:
1658                    ingress:
1659                      - hostname: example.exposed.service
1660            "#;
1661
1662            let i = serde_saphyr::from_str(ingress).unwrap();
1663            assert!(is_ingress_provisioned().matches_object(Some(&i)))
1664        }
1665
1666        #[test]
1667        /// fail if ingress is still waiting for a LB
1668        fn ingress_provisioned_pending() {
1669            use super::{Condition, is_ingress_provisioned};
1670
1671            let ingress = r#"
1672                apiVersion: networking.k8s.io/v1
1673                kind: Ingress
1674                metadata:
1675                  name: test
1676                  namespace: default
1677                  resourceVersion: "1401"
1678                  uid: d653ee4d-0adb-40d9-b03c-7f84f35d4a67
1679                spec:
1680                  ingressClassName: nginx
1681                  rules:
1682                  - host: httpbin.local
1683                    http:
1684                      paths:
1685                      - path: /
1686                        backend:
1687                          service:
1688                            name: httpbin
1689                            port:
1690                              number: 80
1691                status:
1692                  loadBalancer: {}
1693            "#;
1694
1695            let i = serde_saphyr::from_str(ingress).unwrap();
1696            assert!(!is_ingress_provisioned().matches_object(Some(&i)))
1697        }
1698
1699        #[test]
1700        /// fail if ingress does not exist
1701        fn ingress_provisioned_missing() {
1702            use super::{Condition, is_ingress_provisioned};
1703
1704            assert!(!is_ingress_provisioned().matches_object(None))
1705        }
1706    }
1707}
1708
1709/// Utilities for deleting objects
1710pub mod delete {
1711    use super::{await_condition, conditions};
1712    use kube_client::{Api, Resource, api::DeleteParams};
1713    use serde::de::DeserializeOwned;
1714    use std::fmt::Debug;
1715    use thiserror::Error;
1716
1717    /// Errors from `delete_and_finalize`
1718    #[derive(Debug, Error)]
1719    pub enum Error {
1720        /// No uid found on metadata.uid on deleted object
1721        #[error("deleted object has no UID to wait for")]
1722        NoUid,
1723
1724        /// Apiserver returned an error to the delete call
1725        #[error("failed to delete object: {0}")]
1726        Delete(#[source] kube_client::Error),
1727
1728        /// A watcher failed to probe the object for the `is_deleted` condition
1729        #[error("failed to wait for object to be deleted: {0}")]
1730        Await(#[source] super::Error),
1731    }
1732
1733    /// Delete an object, and wait for it to be removed from the Kubernetes API (including waiting for all finalizers to unregister themselves).
1734    ///
1735    /// # Errors
1736    ///
1737    /// Returns an [`Error`](enum@super::Error) if the object was unable to be deleted, or if the wait was interrupted.
1738    pub async fn delete_and_finalize<K: Clone + Debug + Send + DeserializeOwned + Resource + 'static>(
1739        api: Api<K>,
1740        name: &str,
1741        delete_params: &DeleteParams,
1742    ) -> Result<(), Error> {
1743        let deleted_obj_uid = api
1744            .delete(name, delete_params)
1745            .await
1746            .map_err(Error::Delete)?
1747            .either(
1748                |mut obj| obj.meta_mut().uid.take(),
1749                |status| status.details.map(|details| details.uid),
1750            )
1751            .ok_or(Error::NoUid)?;
1752        await_condition(api, name, conditions::is_deleted(&deleted_obj_uid))
1753            .await
1754            .map_err(Error::Await)?;
1755        Ok(())
1756    }
1757}