Skip to main content

k8s_controller/
controller.rs

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/// An error from a reconciliation pass, as passed to
24/// [`Context::error_action`] and [`Context::failure_event`].
25#[derive(Debug, thiserror::Error)]
26pub enum Error<E: std::error::Error + 'static> {
27    /// [`Context::apply`] returned an error, and the context has no
28    /// finalizer.
29    #[error("{0}")]
30    ControllerError(#[source] E),
31    /// The context has a finalizer, and either [`Context::apply`] or
32    /// [`Context::cleanup`] returned an error (wrapped as
33    /// [`ApplyFailed`](kube_runtime::finalizer::Error::ApplyFailed) or
34    /// [`CleanupFailed`](kube_runtime::finalizer::Error::CleanupFailed)), or
35    /// adding or removing the finalizer failed.
36    #[error("{0}")]
37    FinalizerError(#[source] kube_runtime::finalizer::Error<E>),
38}
39
40impl<E: std::error::Error + 'static> Error<E> {
41    /// Renders this error followed by each of its causes, separated by
42    /// `": "`, as used in the note of the default
43    /// [failure event](Context::failure_event).
44    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            // Error types commonly end their own message with their source's
50            // (as this one does), which a naive join would repeat.
51            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    /// Whether the API server rejected a write because the object changed
61    /// since the controller read it. Retrying against the newer version
62    /// resolves this on its own.
63    ///
64    /// This covers a `409 Conflict` anywhere in the source chain, for
65    /// instance from a replace with a stale `resourceVersion`, and a failed
66    /// `test` operation in the JSON patch that adds or removes the finalizer.
67    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
90/// Whether `e` is the API server rejecting a JSON patch whose `test`
91/// operation failed.
92fn is_failed_patch_test(e: &kube::Error) -> bool {
93    // Observed: a failed `test` is a 422 whose details name no object kind
94    // and list no causes. A validation failure, which retrying does not fix,
95    // is also a 422 but names the kind and the invalid fields.
96    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
107/// The observability configured on a [`Controller`], shared by its passes.
108struct Instrumentation {
109    name: Arc<str>,
110    observer: Option<Arc<dyn ReconcileObserver>>,
111    events: Option<Arc<EventRecorder>>,
112}
113
114/// The [`Controller`] watches a set of resources, calling methods on the
115/// provided [`Context`] when events occur.
116pub 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    /// Creates a new controller for a namespaced resource using the given
145    /// `client`. The `context` given determines the type of resource
146    /// to watch (via the [`Context::Resource`] type provided as part of
147    /// the trait implementation). The resources to be watched will be
148    /// limited to resources in the given `namespace`. A [`watcher::Config`]
149    /// can be given to limit the resources watched (for instance,
150    /// `watcher::Config::default().labels("app=myapp")`).
151    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    /// Creates a new controller for a namespaced resource using the given
169    /// `client`. The `context` given determines the type of resource to
170    /// watch (via the [`Context::Resource`] type provided as part of the
171    /// trait implementation). The resources to be watched will not be
172    /// limited by namespace. A [`watcher::Config`] can be given to limit the
173    /// resources watched (for instance,
174    /// `watcher::Config::default().labels("app=myapp")`).
175    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    /// Creates a new controller for a cluster-scoped resource using the
193    /// given `client`. The `context` given determines the type of resource
194    /// to watch (via the [`Context::Resource`] type provided as part of the
195    /// trait implementation). A [`watcher::Config`] can be given to limit the
196    /// resources watched (for instance,
197    /// `watcher::Config::default().labels("app=myapp")`).
198    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    /// Sets the name identifying this controller in its metrics (the
231    /// `controller` field of [`ReconcileRecord`](crate::ReconcileRecord) and
232    /// [`StepRecord`](crate::StepRecord)), and in the `controller` field of
233    /// its `reconcile` tracing span. Defaults to [`Context::FINALIZER_NAME`]
234    /// if set, and otherwise to the kind of the resource being watched.
235    ///
236    /// Controllers sharing an [observer](Controller::with_observer) must
237    /// have distinct names, or their metrics will be merged.
238    pub fn with_name(mut self, name: impl Into<String>) -> Self {
239        self.name = Some(name.into().into());
240        self
241    }
242
243    /// Reports every reconciliation pass, and every [step](crate::Step)
244    /// within one, to `observer`. See the [`observe`](crate::observe)
245    /// module.
246    pub fn with_observer(mut self, observer: Arc<dyn ReconcileObserver>) -> Self {
247        self.observer = Some(observer);
248        self
249    }
250
251    /// Publishes a Kubernetes event on the resource whenever reconciling it
252    /// fails, as determined by [`Context::failure_event`], and enables
253    /// [`TraceMetadata::publish_event`] for the context's own events. See
254    /// the [`events`](crate::events) module, including for the RBAC
255    /// permissions this requires.
256    ///
257    /// `events` must not be given to any other controller. Besides every
258    /// event appearing to come from the same controller, a successful pass
259    /// of one controller would reset the aggregation of another's failure
260    /// events for the same resource.
261    pub fn with_event_recorder(mut self, events: Arc<EventRecorder>) -> Self {
262        self.events = Some(events);
263        self
264    }
265
266    /// Run the controller. This method will not return. The [`Context`]
267    /// given to the constructor will have its [`apply`](Context::apply)
268    /// method called when a resource is created or updated, and its
269    /// [`cleanup`](Context::cleanup) method called when a resource is about
270    /// to be deleted.
271    ///
272    /// To run multiple replicas of a controller with only one reconciling
273    /// at a time, pass this method's future to
274    /// [`LeaderElection::with_lease`](crate::LeaderElection::with_lease).
275    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                // ReconcilerFailed errors will already have been reported by
329                // the _reconcile function
330                if let Err(e) = res
331                    && !matches!(e, kube_runtime::controller::Error::ReconcilerFailed(..))
332                {
333                    // warn instead of error because these kinds of errors
334                    // are almost always recoverable
335                    warn!(
336                        error = %e,
337                        source = e.source(),
338                        "internal kube controller error",
339                    );
340                }
341            })
342            .await
343    }
344
345    /// Allow configuring the underlying [`kube_runtime::Controller`]. For
346    /// example, you can use
347    /// `controller.with_controller(|controller| controller.with_config(Config::default().concurrency(10)))`
348    /// to limit the created controller to reconciling 10 resources at once.
349    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/// The [`Context`] trait should be implemented in order to provide callbacks
361/// for events that happen to resources watched by a [`Controller`].
362#[cfg_attr(not(docsrs), async_trait::async_trait)]
363pub trait Context {
364    /// The type of Kubernetes [resource](Resource) that will be watched by
365    /// the [`Controller`] this context is passed to
366    type Resource: Resource + Send + Sync + 'static;
367    /// The error type which will be returned by the [`apply`](Self::apply)
368    /// and [`cleanup`](Self::cleanup) methods
369    type Error: std::error::Error;
370
371    /// The name to use for the finalizer. This must be unique across
372    /// controllers - if multiple controllers with the same finalizer name
373    /// run against the same resource, unexpected behavior can occur.
374    ///
375    /// If this is None (the default), a finalizer will not be used, and
376    /// cleanup events will not be reported.
377    const FINALIZER_NAME: Option<&'static str> = None;
378
379    /// This method is called when a watched resource is created or updated.
380    /// The [`Client`] used by the controller is passed in to allow making
381    /// additional API requests, as is the resource which triggered this
382    /// event. If this method returns `Some(action)`, the given action will
383    /// be performed, otherwise if `None` is returned,
384    /// [`success_action`](Self::success_action) will be called to find the
385    /// action to perform.
386    ///
387    /// `metadata` is state for this reconciliation pass, which can be used
388    /// to annotate its tracing span, time [steps](TraceMetadata::step) of
389    /// the work for metrics, and [publish events](TraceMetadata::publish_event)
390    /// about the resource.
391    ///
392    /// What this returns determines the [`Outcome`] reported to the
393    /// controller's [observer](Controller::with_observer), as described in
394    /// [`Outcome::of_result`].
395    async fn apply(
396        &self,
397        client: Client,
398        resource: &Self::Resource,
399        metadata: &mut TraceMetadata,
400    ) -> Result<Option<Action>, Self::Error>;
401
402    /// This method is called when a watched resource is marked for deletion.
403    /// The [`Client`] used by the controller is passed in to allow making
404    /// additional API requests, as is the resource which triggered this
405    /// event. If this method returns `None`, cleanup is complete and the
406    /// finalizer is removed. If it returns `Some(action)`, cleanup is not yet
407    /// complete: the finalizer is kept and the given action is performed.
408    /// Return a requeue action to have cleanup run again; with
409    /// [`Action::await_change`] it only runs again once the resource
410    /// changes, and until then the resource stays in deletion.
411    ///
412    /// `metadata` is treated as for [`apply`](Self::apply). The reported
413    /// [`Outcome`] is too, except that any `Some(action)` is
414    /// [`Waiting`](Outcome::Waiting).
415    ///
416    /// Note that this method will only be called if a finalizer is used.
417    async fn cleanup(
418        &self,
419        client: Client,
420        resource: &Self::Resource,
421        metadata: &mut TraceMetadata,
422    ) -> Result<Option<Action>, Self::Error> {
423        // use a better name for the parameter name in the docs
424        let _client = client;
425        let _resource = resource;
426        let _metadata = metadata;
427
428        Ok(None)
429    }
430
431    /// This method is called when a call to [`apply`](Self::apply) returns
432    /// `Ok(None)`. It should return the
433    /// default [`Action`] to perform. The default implementation will
434    /// requeue the event at a random time between 40 and 60 minutes in the
435    /// future.
436    fn success_action(&self, resource: &Self::Resource) -> Action {
437        // use a better name for the parameter name in the docs
438        let _resource = resource;
439
440        Action::requeue(Duration::from_secs(rng().random_range(2400..3600)))
441    }
442
443    /// This method is called when a call to [`apply`](Self::apply) or
444    /// [`cleanup`](Self::cleanup) returns `Err`. It should return the
445    /// default [`Action`] to perform. The error returned will be passed in
446    /// here, as well as a count of how many consecutive errors have happened
447    /// for this resource, to allow for an exponential backoff strategy. The
448    /// default implementation uses exponential backoff with a max of 256
449    /// seconds and some added randomization to avoid thundering herds.
450    fn error_action(
451        self: Arc<Self>,
452        resource: Arc<Self::Resource>,
453        err: &Error<Self::Error>,
454        consecutive_errors: u32,
455    ) -> Action {
456        // use a better name for the parameter name in the docs
457        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    /// This method is called when a reconciliation pass fails, if the
467    /// controller has an [event recorder](Controller::with_event_recorder),
468    /// to determine the Kubernetes event to publish on the resource. Return
469    /// `None` to publish nothing, for instance for errors that are an
470    /// expected part of waiting on something else.
471    ///
472    /// The default implementation publishes a `Warning` event with reason
473    /// `ReconcileFailed` (or `CleanupFailed`, if the resource is being
474    /// deleted), and the error and its causes as the note. Repeats of an
475    /// identical event are aggregated, as described in the
476    /// [`events`](crate::events) module; this means that errors which
477    /// include something that varies from one attempt to the next (such as a
478    /// timestamp or request ID) create a new event per attempt, so should be
479    /// rephrased here.
480    fn failure_event(
481        &self,
482        resource: &Self::Resource,
483        phase: Phase,
484        err: &Error<Self::Error>,
485    ) -> Option<Event> {
486        // use a better name for the parameter name in the docs
487        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
503/// Records a reconciliation pass as [abandoned](Outcome::Abandoned) if it is
504/// dropped before being finished.
505struct 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            // `kube_runtime::finalizer` removes the finalizer whenever cleanup
586            // returns `Ok`, so we manage it ourselves to keep it across
587            // `Ok(Some(action))`. The patches mirror that helper's: a `Test`
588            // op makes them fail if the list changed underneath us.
589            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                    // Adding the finalizer triggers a fresh reconcile, which
607                    // runs apply.
608                    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                        // Kubernetes doesn't deduplicate finalizers, so fail
623                        // if anyone else appended in the meantime.
624                        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                    // Any action means cleanup is unfinished, even
648                    // `await_change`, which `of_result` counts as completed.
649                    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                    // Our finalizer is already gone: nothing to do.
686                    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                // Conflicts are expected whenever the cache lags the API
725                // server, for instance after a leadership change, and the
726                // retry resolves them. Logging them as errors floods error
727                // trackers that report every error event.
728                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            // a success ends the series, so the next failure is a new event
1030            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}