1use 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#[derive(Debug, Error)]
14pub enum Error {
15 #[error("failed to probe for whether the condition is fulfilled yet: {0}")]
17 ProbeFailed(#[source] watcher::Error),
18}
19
20#[allow(clippy::missing_panics_doc)] pub 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 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 let obj = stream
66 .try_next()
67 .await
68 .map_err(Error::ProbeFailed)?
69 .expect("stream must not terminate");
70 Ok(obj)
71}
72
73pub trait Condition<K> {
96 fn matches_object(&self, obj: Option<&K>) -> bool;
98
99 fn not(self) -> conditions::Not<Self>
110 where
111 Self: Sized,
112 {
113 conditions::Not(self)
114 }
115
116 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 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
163pub 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 #[must_use]
186 pub fn is_deleted<K: Resource>(uid: &str) -> impl Condition<K> + '_ {
187 move |obj: Option<&K>| {
188 obj.is_none_or(
190 |obj| obj.meta().uid.as_deref() != Some(uid),
192 )
193 }
194 }
195
196 #[must_use]
200 pub fn is_created<K: Resource>() -> impl Condition<K> {
201 |obj: Option<&K>| obj.is_some()
202 }
203
204 #[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 #[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 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 #[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 #[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 #[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 #[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 if spec.type_ != Some("LoadBalancer".to_string()) {
445 return true;
446 }
447 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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn ingress_provisioned_missing() {
1702 use super::{Condition, is_ingress_provisioned};
1703
1704 assert!(!is_ingress_provisioned().matches_object(None))
1705 }
1706 }
1707}
1708
1709pub 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 #[derive(Debug, Error)]
1719 pub enum Error {
1720 #[error("deleted object has no UID to wait for")]
1722 NoUid,
1723
1724 #[error("failed to delete object: {0}")]
1726 Delete(#[source] kube_client::Error),
1727
1728 #[error("failed to wait for object to be deleted: {0}")]
1730 Await(#[source] super::Error),
1731 }
1732
1733 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}