1use std::collections::BTreeMap;
2use std::error::Error as _;
3use std::str::FromStr;
4use std::sync::{Arc, Mutex};
5use std::time::{Duration, Instant};
6
7use futures::future::FutureExt;
8use futures::stream::StreamExt;
9use json_patch::jsonptr::PointerBuf;
10use json_patch::{AddOperation, PatchOperation, RemoveOperation, TestOperation};
11use kube::api::{Api, Patch, PatchParams};
12use kube::core::{ClusterResourceScope, NamespaceResourceScope};
13use kube::{Client, Resource, ResourceExt};
14use kube_runtime::controller::Action;
15use kube_runtime::watcher;
16use rand::{RngExt, rng};
17use tracing::field::Empty;
18use tracing::{Instrument, Span, error, info, info_span, trace, warn};
19
20use crate::events::{Event, EventRecorder, EventType};
21use crate::observe::{Outcome, Pass, Phase, ReconcileObserver, TraceMetadata};
22
23#[derive(Debug, thiserror::Error)]
26pub enum Error<E: std::error::Error + 'static> {
27 #[error("{0}")]
30 ControllerError(#[source] E),
31 #[error("{0}")]
37 FinalizerError(#[source] kube_runtime::finalizer::Error<E>),
38}
39
40impl<E: std::error::Error + 'static> Error<E> {
41 pub fn display_chain(&self) -> String {
45 let mut out = self.to_string();
46 let mut source = self.source();
47 while let Some(err) = source {
48 let message = err.to_string();
49 if !out.ends_with(&message) {
52 out.push_str(": ");
53 out.push_str(&message);
54 }
55 source = err.source();
56 }
57 out
58 }
59
60 pub fn is_conflict(&self) -> bool {
68 if let Error::FinalizerError(
69 kube_runtime::finalizer::Error::AddFinalizer(e)
70 | kube_runtime::finalizer::Error::RemoveFinalizer(e),
71 ) = self
72 && is_failed_patch_test(e)
73 {
74 return true;
75 }
76 let mut source: Option<&(dyn std::error::Error + 'static)> = Some(self);
77 while let Some(err) = source {
78 if let Some(kube::Error::Api(status)) = err.downcast_ref::<kube::Error>()
79 && status.code == 409
80 && status.reason == "Conflict"
81 {
82 return true;
83 }
84 source = err.source();
85 }
86 false
87 }
88}
89
90fn is_failed_patch_test(e: &kube::Error) -> bool {
93 matches!(
97 e,
98 kube::Error::Api(status)
99 if status.code == 422
100 && status
101 .details
102 .as_ref()
103 .is_none_or(|d| d.kind.is_empty() && d.causes.is_empty())
104 )
105}
106
107struct Instrumentation {
109 name: Arc<str>,
110 observer: Option<Arc<dyn ReconcileObserver>>,
111 events: Option<Arc<EventRecorder>>,
112}
113
114pub struct Controller<Ctx: Context>
117where
118 Ctx: Send + Sync + 'static,
119 Ctx::Error: Send + Sync + 'static,
120 Ctx::Resource: Send + Sync + 'static,
121 Ctx::Resource: Clone + std::fmt::Debug + serde::Serialize,
122 for<'de> Ctx::Resource: serde::Deserialize<'de>,
123 <Ctx::Resource as Resource>::DynamicType:
124 Eq + Clone + std::hash::Hash + std::default::Default + std::fmt::Debug + std::marker::Unpin,
125{
126 client: kube::Client,
127 make_api: Box<dyn Fn(&Ctx::Resource) -> Api<Ctx::Resource> + Sync + Send + 'static>,
128 controller: kube_runtime::controller::Controller<Ctx::Resource>,
129 context: Ctx,
130 name: Option<Arc<str>>,
131 observer: Option<Arc<dyn ReconcileObserver>>,
132 events: Option<Arc<EventRecorder>>,
133}
134
135impl<Ctx: Context> Controller<Ctx>
136where
137 Ctx: Send + Sync + 'static,
138 Ctx::Error: Send + Sync + 'static,
139 Ctx::Resource: Clone + std::fmt::Debug + serde::Serialize,
140 for<'de> Ctx::Resource: serde::Deserialize<'de>,
141 <Ctx::Resource as Resource>::DynamicType:
142 Eq + Clone + std::hash::Hash + std::default::Default + std::fmt::Debug + std::marker::Unpin,
143{
144 pub fn namespaced(client: Client, context: Ctx, namespace: &str, wc: watcher::Config) -> Self
152 where
153 Ctx::Resource: Resource<Scope = NamespaceResourceScope>,
154 {
155 let make_api = {
156 let client = client.clone();
157 Box::new(move |resource: &Ctx::Resource| {
158 Api::<Ctx::Resource>::namespaced(client.clone(), &resource.namespace().unwrap())
159 })
160 };
161 let controller = kube_runtime::controller::Controller::new(
162 Api::<Ctx::Resource>::namespaced(client.clone(), namespace),
163 wc,
164 );
165 Self::new(client, make_api, controller, context)
166 }
167
168 pub fn namespaced_all(client: Client, context: Ctx, wc: watcher::Config) -> Self
176 where
177 Ctx::Resource: Resource<Scope = NamespaceResourceScope>,
178 {
179 let make_api = {
180 let client = client.clone();
181 Box::new(move |resource: &Ctx::Resource| {
182 Api::<Ctx::Resource>::namespaced(client.clone(), &resource.namespace().unwrap())
183 })
184 };
185 let controller = kube_runtime::controller::Controller::new(
186 Api::<Ctx::Resource>::all(client.clone()),
187 wc,
188 );
189 Self::new(client, make_api, controller, context)
190 }
191
192 pub fn cluster(client: Client, context: Ctx, wc: watcher::Config) -> Self
199 where
200 Ctx::Resource: Resource<Scope = ClusterResourceScope>,
201 {
202 let make_api = {
203 let client = client.clone();
204 Box::new(move |_: &Ctx::Resource| Api::<Ctx::Resource>::all(client.clone()))
205 };
206 let controller = kube_runtime::controller::Controller::new(
207 Api::<Ctx::Resource>::all(client.clone()),
208 wc,
209 );
210 Self::new(client, make_api, controller, context)
211 }
212
213 fn new(
214 client: Client,
215 make_api: Box<dyn Fn(&Ctx::Resource) -> Api<Ctx::Resource> + Sync + Send + 'static>,
216 controller: kube_runtime::controller::Controller<Ctx::Resource>,
217 context: Ctx,
218 ) -> Self {
219 Self {
220 client,
221 make_api,
222 controller,
223 context,
224 name: None,
225 observer: None,
226 events: None,
227 }
228 }
229
230 pub fn with_name(mut self, name: impl Into<String>) -> Self {
239 self.name = Some(name.into().into());
240 self
241 }
242
243 pub fn with_observer(mut self, observer: Arc<dyn ReconcileObserver>) -> Self {
247 self.observer = Some(observer);
248 self
249 }
250
251 pub fn with_event_recorder(mut self, events: Arc<EventRecorder>) -> Self {
262 self.events = Some(events);
263 self
264 }
265
266 pub async fn run(self) {
276 let Self {
277 client,
278 make_api,
279 controller,
280 context,
281 name,
282 observer,
283 events,
284 } = self;
285 let instrumentation = Arc::new(Instrumentation {
286 name: name.unwrap_or_else(|| match Ctx::FINALIZER_NAME {
287 Some(finalizer_name) => finalizer_name.into(),
288 None => Ctx::Resource::kind(&Default::default()).into(),
289 }),
290 observer,
291 events,
292 });
293 let instrumentation = &instrumentation;
294 let backoffs = Arc::new(Mutex::new(BTreeMap::new()));
295 let backoffs = &backoffs;
296 controller
297 .run(
298 |resource, context| {
299 let uid = resource.uid().unwrap();
300 let backoffs = Arc::clone(backoffs);
301 reconcile(
302 context,
303 client.clone(),
304 make_api(&resource),
305 resource,
306 Arc::clone(instrumentation),
307 )
308 .inspect(move |result| {
309 if result.is_ok() {
310 backoffs.lock().unwrap().remove(&uid);
311 }
312 })
313 },
314 |resource, err, context| {
315 let consecutive_errors = {
316 let uid = resource.uid().unwrap();
317 let mut backoffs = backoffs.lock().unwrap();
318 let consecutive_errors: u32 =
319 backoffs.get(&uid).copied().unwrap_or_default();
320 backoffs.insert(uid, consecutive_errors.saturating_add(1));
321 consecutive_errors
322 };
323 context.error_action(resource, err, consecutive_errors)
324 },
325 Arc::new(context),
326 )
327 .for_each(|res| async {
328 if let Err(e) = res
331 && !matches!(e, kube_runtime::controller::Error::ReconcilerFailed(..))
332 {
333 warn!(
336 error = %e,
337 source = e.source(),
338 "internal kube controller error",
339 );
340 }
341 })
342 .await
343 }
344
345 pub fn with_controller<F>(mut self, f: F) -> Self
350 where
351 F: FnOnce(
352 kube_runtime::Controller<Ctx::Resource>,
353 ) -> kube_runtime::Controller<Ctx::Resource>,
354 {
355 self.controller = f(self.controller);
356 self
357 }
358}
359
360#[cfg_attr(not(docsrs), async_trait::async_trait)]
363pub trait Context {
364 type Resource: Resource + Send + Sync + 'static;
367 type Error: std::error::Error;
370
371 const FINALIZER_NAME: Option<&'static str> = None;
378
379 async fn apply(
396 &self,
397 client: Client,
398 resource: &Self::Resource,
399 metadata: &mut TraceMetadata,
400 ) -> Result<Option<Action>, Self::Error>;
401
402 async fn cleanup(
418 &self,
419 client: Client,
420 resource: &Self::Resource,
421 metadata: &mut TraceMetadata,
422 ) -> Result<Option<Action>, Self::Error> {
423 let _client = client;
425 let _resource = resource;
426 let _metadata = metadata;
427
428 Ok(None)
429 }
430
431 fn success_action(&self, resource: &Self::Resource) -> Action {
437 let _resource = resource;
439
440 Action::requeue(Duration::from_secs(rng().random_range(2400..3600)))
441 }
442
443 fn error_action(
451 self: Arc<Self>,
452 resource: Arc<Self::Resource>,
453 err: &Error<Self::Error>,
454 consecutive_errors: u32,
455 ) -> Action {
456 let _resource = resource;
458 let _err = err;
459
460 let seconds = 2u64.pow(consecutive_errors.min(7) + 1);
461 Action::requeue(Duration::from_millis(
462 rng().random_range((seconds * 500)..(seconds * 1000)),
463 ))
464 }
465
466 fn failure_event(
481 &self,
482 resource: &Self::Resource,
483 phase: Phase,
484 err: &Error<Self::Error>,
485 ) -> Option<Event> {
486 let _resource = resource;
488
489 let (reason, action) = match phase {
490 Phase::Cleanup | Phase::Delete => ("CleanupFailed", "Cleanup"),
491 _ => ("ReconcileFailed", "Reconcile"),
492 };
493 Some(Event {
494 type_: EventType::Warning,
495 reason: reason.to_owned(),
496 action: action.to_owned(),
497 note: Some(err.display_chain()),
498 related: None,
499 })
500 }
501}
502
503struct PassGuard {
506 pass: Arc<Pass>,
507 start: Instant,
508 phase: Option<Phase>,
509 fallback_phase: Phase,
510 finished: bool,
511}
512
513impl PassGuard {
514 fn phase(&self) -> Phase {
515 self.phase.unwrap_or(self.fallback_phase)
516 }
517
518 fn finish(&mut self, outcome: Outcome) {
519 self.finished = true;
520 self.pass
521 .record(self.phase(), outcome, self.start.elapsed());
522 }
523}
524
525impl Drop for PassGuard {
526 fn drop(&mut self) {
527 if !self.finished {
528 self.pass
529 .record(self.phase(), Outcome::Abandoned, self.start.elapsed());
530 }
531 }
532}
533
534async fn reconcile<Ctx>(
535 ctx: Arc<Ctx>,
536 client: Client,
537 api: Api<Ctx::Resource>,
538 resource: Arc<Ctx::Resource>,
539 instrumentation: Arc<Instrumentation>,
540) -> Result<Action, Error<Ctx::Error>>
541where
542 Ctx: Context + Send + Sync + 'static,
543 Ctx::Error: Send + Sync + 'static,
544 Ctx::Resource: Send + Sync + 'static,
545 Ctx::Resource: Clone + std::fmt::Debug + serde::Serialize,
546 for<'de> Ctx::Resource: serde::Deserialize<'de>,
547 <Ctx::Resource as Resource>::DynamicType:
548 Eq + Clone + std::hash::Hash + std::default::Default + std::fmt::Debug + std::marker::Unpin,
549{
550 let span = info_span!(
551 "reconcile",
552 resource_type = Ctx::Resource::kind(&Default::default()).as_ref(),
553 resource_name = resource.name_unchecked().as_str(),
554 controller = &*instrumentation.name,
555 event_type = Empty,
556 outcome = Empty,
557 success = Empty,
558 duration_seconds = Empty,
559 metadata = Empty,
560 );
561 async {
562 trace!("beginning reconciliation");
563
564 let pass = Arc::new(Pass {
565 controller: Arc::clone(&instrumentation.name),
566 reference: resource.object_ref(&Default::default()),
567 observer: instrumentation.observer.clone(),
568 events: instrumentation.events.clone(),
569 });
570 let mut metadata = TraceMetadata::for_pass(Arc::clone(&pass));
571 let mut guard = PassGuard {
572 pass: Arc::clone(&pass),
573 start: Instant::now(),
574 phase: None,
575 fallback_phase: if resource.meta().deletion_timestamp.is_some() {
576 Phase::Delete
577 } else {
578 Phase::Init
579 },
580 finished: false,
581 };
582 let mut reconciler_outcome = None;
583
584 let res = if let Some(finalizer_name) = Ctx::FINALIZER_NAME {
585 let name = resource.name_unchecked();
590 let finalizer_i = resource
591 .finalizers()
592 .iter()
593 .position(|f| f == finalizer_name);
594 let is_deleting = resource.meta().deletion_timestamp.is_some();
595 match (finalizer_i, is_deleting) {
596 (Some(_), false) => {
597 guard.phase = Some(Phase::Apply);
598 let res = ctx.apply(client, &resource, &mut metadata).await;
599 reconciler_outcome = Some(Outcome::of_result(&res));
600 res.map(|action| action.unwrap_or_else(|| ctx.success_action(&resource)))
601 .map_err(|e| {
602 Error::FinalizerError(kube_runtime::finalizer::Error::ApplyFailed(e))
603 })
604 }
605 (None, false) => {
606 let patch = if resource.finalizers().is_empty() {
609 json_patch::Patch(vec![
610 PatchOperation::Test(TestOperation {
611 path: PointerBuf::from_str("/metadata/finalizers")
612 .expect("constructed pointer is valid"),
613 value: serde_json::Value::Null,
614 }),
615 PatchOperation::Add(AddOperation {
616 path: PointerBuf::from_str("/metadata/finalizers")
617 .expect("constructed pointer is valid"),
618 value: vec![finalizer_name].into(),
619 }),
620 ])
621 } else {
622 json_patch::Patch(vec![
625 PatchOperation::Test(TestOperation {
626 path: PointerBuf::from_str("/metadata/finalizers")
627 .expect("constructed pointer is valid"),
628 value: resource.finalizers().into(),
629 }),
630 PatchOperation::Add(AddOperation {
631 path: PointerBuf::from_str("/metadata/finalizers/-")
632 .expect("constructed pointer is valid"),
633 value: finalizer_name.into(),
634 }),
635 ])
636 };
637 api.patch::<Ctx::Resource>(&name, &PatchParams::default(), &Patch::Json(patch))
638 .await
639 .map(|_| Action::await_change())
640 .map_err(|e| {
641 Error::FinalizerError(kube_runtime::finalizer::Error::AddFinalizer(e))
642 })
643 }
644 (Some(finalizer_i), true) => {
645 guard.phase = Some(Phase::Cleanup);
646 let res = ctx.cleanup(client, &resource, &mut metadata).await;
647 reconciler_outcome = Some(match &res {
650 Ok(Some(_)) => Outcome::Waiting,
651 res => Outcome::of_result(res),
652 });
653 match res {
654 Err(e) => Err(Error::FinalizerError(
655 kube_runtime::finalizer::Error::CleanupFailed(e),
656 )),
657 Ok(Some(action)) => Ok(action),
658 Ok(None) => {
659 let finalizer_path = format!("/metadata/finalizers/{finalizer_i}");
660 let pointer = PointerBuf::from_str(&finalizer_path)
661 .expect("constructed pointer is valid");
662 let patch = json_patch::Patch(vec![
663 PatchOperation::Test(TestOperation {
664 path: pointer.clone(),
665 value: finalizer_name.into(),
666 }),
667 PatchOperation::Remove(RemoveOperation { path: pointer }),
668 ]);
669 api.patch::<Ctx::Resource>(
670 &name,
671 &PatchParams::default(),
672 &Patch::Json(patch),
673 )
674 .await
675 .map(|_| Action::await_change())
676 .map_err(|e| {
677 Error::FinalizerError(
678 kube_runtime::finalizer::Error::RemoveFinalizer(e),
679 )
680 })
681 }
682 }
683 }
684 (None, true) => {
685 Ok(Action::await_change())
687 }
688 }
689 } else if resource.meta().deletion_timestamp.is_none() {
690 guard.phase = Some(Phase::Apply);
691 let res = ctx.apply(client, &resource, &mut metadata).await;
692 reconciler_outcome = Some(Outcome::of_result(&res));
693 res.map(|action| action.unwrap_or_else(|| ctx.success_action(&resource)))
694 .map_err(Error::ControllerError)
695 } else {
696 Ok(Action::await_change())
697 };
698
699 let outcome = match &res {
700 Err(_) => Outcome::Failed,
701 Ok(_) => metadata
702 .outcome
703 .or(reconciler_outcome)
704 .unwrap_or(Outcome::Completed),
705 };
706 let phase = guard.phase();
707 let duration = guard.start.elapsed();
708 guard.finish(outcome);
709
710 let span = Span::current();
711 span.record("event_type", phase.as_str());
712 span.record("outcome", outcome.as_str());
713 span.record("duration_seconds", duration.as_secs_f64());
714
715 if !metadata.annotations.is_empty()
716 && let Ok(s) = serde_json::to_string(&metadata.annotations)
717 {
718 span.record("metadata", s);
719 }
720
721 if let Err(e) = &res {
722 span.record("success", false);
723 if e.is_conflict() {
724 info!(error = %e, source = e.source(), "reconcile");
729 } else {
730 error!(error = %e, source = e.source(), "reconcile");
731 }
732 } else {
733 span.record("success", true);
734 info!("reconcile");
735 }
736
737 if let Some(events) = &instrumentation.events {
738 match &res {
739 Err(e) => {
740 if let Some(event) = ctx.failure_event(&resource, phase, e)
741 && let Err(publish_err) =
742 events.publish_to(&pass.reference, &event, true).await
743 {
744 warn!(
745 error = %publish_err,
746 reason = %event.reason,
747 "failed to publish reconciliation failure event",
748 );
749 }
750 }
751 Ok(_) => {
752 if let Some(uid) = &pass.reference.uid {
753 events.forget_failures(uid);
754 }
755 }
756 }
757 }
758
759 res
760 }
761 .instrument(span)
762 .await
763}
764
765#[cfg(test)]
766mod tests {
767 use std::future::pending;
768 use std::sync::Mutex;
769
770 use futures::FutureExt;
771 use k8s_openapi::api::core::v1::ConfigMap;
772 use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, Time};
773 use k8s_openapi::jiff::Timestamp;
774 use kube::core::Status;
775 use kube::core::response::{StatusCause, StatusDetails, StatusSummary};
776
777 use super::*;
778 use crate::events::Reporter;
779 use crate::observe::{ReconcileRecord, StepRecord};
780 use crate::test_util::{MockApiServer, block_on};
781
782 #[derive(Debug, thiserror::Error)]
783 enum TestError {
784 #[error("reconciling failed: {0}")]
785 Wrapped(#[source] std::io::Error),
786 #[error("talking to the API server failed")]
787 Kube(#[source] kube::Error),
788 }
789
790 #[derive(Clone, Copy)]
791 enum Behavior {
792 Done,
793 Requeue,
794 Skip,
795 Fail,
796 FailQuietly,
797 Hang,
798 }
799
800 struct TestContext {
801 behavior: Mutex<Behavior>,
802 }
803
804 impl TestContext {
805 fn new(behavior: Behavior) -> Arc<Self> {
806 Arc::new(Self {
807 behavior: Mutex::new(behavior),
808 })
809 }
810
811 fn set(&self, behavior: Behavior) {
812 *self.behavior.lock().unwrap() = behavior;
813 }
814 }
815
816 #[async_trait::async_trait]
817 impl Context for TestContext {
818 type Resource = ConfigMap;
819 type Error = TestError;
820
821 async fn apply(
822 &self,
823 _client: Client,
824 _resource: &ConfigMap,
825 metadata: &mut TraceMetadata,
826 ) -> Result<Option<Action>, TestError> {
827 let behavior = *self.behavior.lock().unwrap();
828 let step = metadata.step("work");
829 match behavior {
830 Behavior::Done => {
831 step.finish(Outcome::Completed);
832 Ok(None)
833 }
834 Behavior::Requeue => {
835 step.finish(Outcome::Waiting);
836 Ok(Some(Action::requeue(Duration::from_secs(1))))
837 }
838 Behavior::Skip => {
839 step.finish(Outcome::Skipped);
840 metadata.set_outcome(Outcome::Skipped);
841 Ok(None)
842 }
843 Behavior::Fail | Behavior::FailQuietly => {
844 Err(TestError::Wrapped(std::io::Error::other("disk on fire")))
845 }
846 Behavior::Hang => pending().await,
847 }
848 }
849
850 fn failure_event(
851 &self,
852 _resource: &ConfigMap,
853 _phase: Phase,
854 err: &Error<TestError>,
855 ) -> Option<Event> {
856 match *self.behavior.lock().unwrap() {
857 Behavior::FailQuietly => None,
858 _ => Some(Event {
859 type_: EventType::Warning,
860 reason: "ReconcileFailed".to_owned(),
861 action: "Reconcile".to_owned(),
862 note: Some(err.display_chain()),
863 related: None,
864 }),
865 }
866 }
867 }
868
869 #[derive(Debug, Clone, PartialEq)]
870 enum Recorded {
871 Pass(String, Phase, Outcome),
872 Step(String, &'static str, Outcome),
873 }
874
875 #[derive(Default)]
876 struct TestObserver(Mutex<Vec<Recorded>>);
877
878 impl TestObserver {
879 fn take(&self) -> Vec<Recorded> {
880 std::mem::take(&mut self.0.lock().unwrap())
881 }
882 }
883
884 impl ReconcileObserver for TestObserver {
885 fn reconciled(&self, record: &ReconcileRecord<'_>) {
886 assert_eq!(record.kind, "ConfigMap");
887 assert_eq!(record.namespace, Some("ns"));
888 assert_eq!(record.name, "cm");
889 self.0.lock().unwrap().push(Recorded::Pass(
890 record.controller.to_owned(),
891 record.phase,
892 record.outcome,
893 ));
894 }
895
896 fn step_finished(&self, record: &StepRecord<'_>) {
897 self.0.lock().unwrap().push(Recorded::Step(
898 record.controller.to_owned(),
899 record.step,
900 record.outcome,
901 ));
902 }
903 }
904
905 struct Harness {
906 server: MockApiServer,
907 observer: Arc<TestObserver>,
908 instrumentation: Arc<Instrumentation>,
909 }
910
911 impl Harness {
912 fn new() -> Self {
913 let server = MockApiServer::new();
914 let observer = Arc::new(TestObserver::default());
915 let instrumentation = Arc::new(Instrumentation {
916 name: "test".into(),
917 observer: Some(Arc::<TestObserver>::clone(&observer)),
918 events: Some(Arc::new(EventRecorder::new(
919 server.client(),
920 Reporter {
921 controller: "test.example.com".to_owned(),
922 instance: None,
923 },
924 ))),
925 });
926 Self {
927 server,
928 observer,
929 instrumentation,
930 }
931 }
932
933 fn reconcile(
934 &self,
935 ctx: &Arc<TestContext>,
936 resource: ConfigMap,
937 ) -> impl Future<Output = Result<Action, Error<TestError>>> + use<> {
938 let client = self.server.client();
939 reconcile(
940 Arc::clone(ctx),
941 client.clone(),
942 Api::namespaced(client, "ns"),
943 Arc::new(resource),
944 Arc::clone(&self.instrumentation),
945 )
946 }
947
948 fn methods(&self) -> Vec<String> {
949 self.server
950 .requests()
951 .into_iter()
952 .map(|r| r.method)
953 .collect()
954 }
955 }
956
957 fn config_map() -> ConfigMap {
958 ConfigMap {
959 metadata: ObjectMeta {
960 name: Some("cm".to_owned()),
961 namespace: Some("ns".to_owned()),
962 uid: Some("uid-1".to_owned()),
963 ..Default::default()
964 },
965 ..Default::default()
966 }
967 }
968
969 fn pass(phase: Phase, outcome: Outcome) -> Recorded {
970 Recorded::Pass("test".to_owned(), phase, outcome)
971 }
972
973 fn step(outcome: Outcome) -> Recorded {
974 Recorded::Step("test".to_owned(), "work", outcome)
975 }
976
977 #[test]
978 fn classifies_successful_passes() {
979 block_on(async {
980 let harness = Harness::new();
981 let ctx = TestContext::new(Behavior::Done);
982 harness.reconcile(&ctx, config_map()).await.unwrap();
983 assert_eq!(
984 harness.observer.take(),
985 [
986 step(Outcome::Completed),
987 pass(Phase::Apply, Outcome::Completed)
988 ]
989 );
990
991 ctx.set(Behavior::Requeue);
992 harness.reconcile(&ctx, config_map()).await.unwrap();
993 assert_eq!(
994 harness.observer.take(),
995 [step(Outcome::Waiting), pass(Phase::Apply, Outcome::Waiting)]
996 );
997
998 ctx.set(Behavior::Skip);
999 harness.reconcile(&ctx, config_map()).await.unwrap();
1000 assert_eq!(
1001 harness.observer.take(),
1002 [step(Outcome::Skipped), pass(Phase::Apply, Outcome::Skipped)]
1003 );
1004
1005 assert!(harness.server.requests().is_empty());
1006 });
1007 }
1008
1009 #[test]
1010 fn publishes_and_aggregates_failure_events() {
1011 block_on(async {
1012 let harness = Harness::new();
1013 let ctx = TestContext::new(Behavior::Fail);
1014 harness.reconcile(&ctx, config_map()).await.unwrap_err();
1015 assert_eq!(
1016 harness.observer.take(),
1017 [
1018 step(Outcome::Abandoned),
1019 pass(Phase::Apply, Outcome::Failed)
1020 ]
1021 );
1022 let requests = harness.server.requests();
1023 assert_eq!(requests[0].body["reason"], "ReconcileFailed");
1024 assert_eq!(requests[0].body["note"], "reconciling failed: disk on fire");
1025
1026 harness.reconcile(&ctx, config_map()).await.unwrap_err();
1027 assert_eq!(harness.methods(), ["POST", "PATCH"]);
1028
1029 ctx.set(Behavior::Done);
1031 harness.reconcile(&ctx, config_map()).await.unwrap();
1032 ctx.set(Behavior::Fail);
1033 harness.reconcile(&ctx, config_map()).await.unwrap_err();
1034 assert_eq!(harness.methods(), ["POST", "PATCH", "POST"]);
1035 });
1036 }
1037
1038 #[test]
1039 fn failure_event_can_be_suppressed() {
1040 block_on(async {
1041 let harness = Harness::new();
1042 let ctx = TestContext::new(Behavior::FailQuietly);
1043 harness.reconcile(&ctx, config_map()).await.unwrap_err();
1044 assert_eq!(
1045 harness.observer.take(),
1046 [
1047 step(Outcome::Abandoned),
1048 pass(Phase::Apply, Outcome::Failed)
1049 ]
1050 );
1051 assert!(harness.server.requests().is_empty());
1052 });
1053 }
1054
1055 #[test]
1056 fn deleted_resource_without_finalizer() {
1057 block_on(async {
1058 let harness = Harness::new();
1059 let ctx = TestContext::new(Behavior::Fail);
1060 let mut resource = config_map();
1061 resource.metadata.deletion_timestamp = Some(Time(Timestamp::now()));
1062 harness.reconcile(&ctx, resource).await.unwrap();
1063 assert_eq!(
1064 harness.observer.take(),
1065 [pass(Phase::Delete, Outcome::Completed)]
1066 );
1067 });
1068 }
1069
1070 #[test]
1071 fn cancelled_pass_is_abandoned() {
1072 block_on(async {
1073 let harness = Harness::new();
1074 let ctx = TestContext::new(Behavior::Hang);
1075 let mut fut = Box::pin(harness.reconcile(&ctx, config_map()));
1076 assert!((&mut fut).now_or_never().is_none());
1077 assert!(harness.observer.take().is_empty());
1078 drop(fut);
1079 assert_eq!(
1080 harness.observer.take(),
1081 [
1082 step(Outcome::Abandoned),
1083 pass(Phase::Apply, Outcome::Abandoned)
1084 ]
1085 );
1086 });
1087 }
1088
1089 #[test]
1090 fn display_chain_does_not_repeat_messages() {
1091 let err: Error<TestError> =
1092 Error::FinalizerError(kube_runtime::finalizer::Error::ApplyFailed(
1093 TestError::Wrapped(std::io::Error::other("disk on fire")),
1094 ));
1095 assert_eq!(
1096 err.display_chain(),
1097 "failed to apply object: reconciling failed: disk on fire"
1098 );
1099
1100 #[derive(Debug, thiserror::Error)]
1101 #[error("outer")]
1102 struct Outer(#[source] std::io::Error);
1103 let err: Error<Outer> = Error::ControllerError(Outer(std::io::Error::other("inner")));
1104 assert_eq!(err.display_chain(), "outer: inner");
1105
1106 #[derive(Debug, thiserror::Error)]
1107 #[error("reading lock: timed out waiting for lock")]
1108 struct Mentions(#[source] std::io::Error);
1109 let err: Error<Mentions> =
1110 Error::ControllerError(Mentions(std::io::Error::other("timed out")));
1111 assert_eq!(
1112 err.display_chain(),
1113 "reading lock: timed out waiting for lock: timed out"
1114 );
1115 }
1116
1117 fn api_error(code: u16, reason: &str, details: Option<StatusDetails>) -> kube::Error {
1118 kube::Error::Api(Box::new(Status {
1119 status: Some(StatusSummary::Failure),
1120 code,
1121 message: String::new(),
1122 metadata: None,
1123 reason: reason.into(),
1124 details,
1125 }))
1126 }
1127
1128 #[test]
1129 fn conflicts_are_classified() {
1130 use kube_runtime::finalizer::Error as F;
1131
1132 let stale_apply: Error<TestError> = Error::FinalizerError(F::ApplyFailed(TestError::Kube(
1133 api_error(409, "Conflict", None),
1134 )));
1135 assert!(
1136 stale_apply.is_conflict(),
1137 "409 nested in the context's error"
1138 );
1139
1140 let stale_controller: Error<TestError> =
1141 Error::ControllerError(TestError::Kube(api_error(409, "Conflict", None)));
1142 assert!(stale_controller.is_conflict(), "409 without a finalizer");
1143
1144 let failed_test = || {
1145 api_error(
1146 422,
1147 "Invalid",
1148 Some(StatusDetails {
1149 name: String::new(),
1150 group: String::new(),
1151 kind: String::new(),
1152 uid: String::new(),
1153 causes: vec![],
1154 retry_after_seconds: 0,
1155 }),
1156 )
1157 };
1158 let add: Error<TestError> = Error::FinalizerError(F::AddFinalizer(failed_test()));
1159 assert!(
1160 add.is_conflict(),
1161 "failed patch test when adding the finalizer"
1162 );
1163 let remove: Error<TestError> = Error::FinalizerError(F::RemoveFinalizer(failed_test()));
1164 assert!(
1165 remove.is_conflict(),
1166 "failed patch test when removing the finalizer"
1167 );
1168 }
1169
1170 #[test]
1171 fn other_errors_are_not_conflicts() {
1172 use kube_runtime::finalizer::Error as F;
1173
1174 let exists: Error<TestError> =
1175 Error::ControllerError(TestError::Kube(api_error(409, "AlreadyExists", None)));
1176 assert!(
1177 !exists.is_conflict(),
1178 "AlreadyExists does not resolve on retry"
1179 );
1180
1181 let invalid = api_error(
1182 422,
1183 "Invalid",
1184 Some(StatusDetails {
1185 name: "cm".into(),
1186 group: String::new(),
1187 kind: "ConfigMap".into(),
1188 uid: String::new(),
1189 causes: vec![StatusCause {
1190 reason: "FieldValueInvalid".into(),
1191 message: "bad value".into(),
1192 field: "metadata.finalizers[0]".into(),
1193 }],
1194 retry_after_seconds: 0,
1195 }),
1196 );
1197 let add: Error<TestError> = Error::FinalizerError(F::AddFinalizer(invalid));
1198 assert!(
1199 !add.is_conflict(),
1200 "validation failure of the finalizer patch"
1201 );
1202
1203 let invalid_apply: Error<TestError> = Error::FinalizerError(F::ApplyFailed(
1204 TestError::Kube(api_error(422, "Invalid", None)),
1205 ));
1206 assert!(
1207 !invalid_apply.is_conflict(),
1208 "422 from the context's own writes"
1209 );
1210
1211 let io: Error<TestError> =
1212 Error::ControllerError(TestError::Wrapped(std::io::Error::other("disk on fire")));
1213 assert!(!io.is_conflict());
1214 }
1215}