Skip to main content

k8s_controller/
observe.rs

1//! Observing what reconciliation does, for metrics.
2//!
3//! A [`Controller`](crate::Controller) given a [`ReconcileObserver`] via
4//! [`with_observer`](crate::Controller::with_observer) reports every
5//! reconciliation pass to it as a [`ReconcileRecord`]. Within a pass,
6//! reconcilers can additionally divide their work into named [`Step`]s,
7//! started with [`TraceMetadata::step`], each reported as a [`StepRecord`].
8//! Steps are what attribute a slow or failing pass to the part of the
9//! reconciler responsible, and are the only way to report that a part of it
10//! was [skipped](Outcome::Skipped).
11//!
12//! With the `prometheus` feature enabled,
13//! [`PrometheusMetrics`](crate::PrometheusMetrics) implements
14//! [`ReconcileObserver`] by exporting Prometheus metrics. Implement the trait
15//! directly to export to another metrics system.
16
17use std::collections::BTreeMap;
18use std::fmt::Display;
19use std::sync::Arc;
20use std::time::{Duration, Instant};
21
22use k8s_openapi::api::core::v1::ObjectReference;
23use kube_runtime::controller::Action;
24use tracing::warn;
25
26use crate::events::{Event, EventRecorder};
27
28/// What a reconciliation pass, or a step of one, concluded.
29///
30/// [`as_str`](Outcome::as_str) gives the value used as a metric label, which
31/// is stable.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum Outcome {
35    /// Brought what it manages to the desired state, or found it already
36    /// there.
37    Completed,
38    /// Made progress, but the desired state has not been reached yet, and
39    /// asked to be run again to continue.
40    Waiting,
41    /// Had nothing to do, for instance because what it manages is disabled
42    /// by configuration. Never inferred; reconcilers must report it
43    /// explicitly.
44    Skipped,
45    /// Returned an error.
46    Failed,
47    /// Stopped without reaching a conclusion: either the reconciliation was
48    /// cancelled (for instance because leadership was lost, or the process
49    /// is shutting down), or, for a [`Step`], an error propagated out of it
50    /// before it was finished.
51    Abandoned,
52}
53
54impl Outcome {
55    /// The label value for this outcome.
56    pub fn as_str(self) -> &'static str {
57        match self {
58            Outcome::Completed => "completed",
59            Outcome::Waiting => "waiting",
60            Outcome::Skipped => "skipped",
61            Outcome::Failed => "failed",
62            Outcome::Abandoned => "abandoned",
63        }
64    }
65
66    /// Classifies a result in the form returned by
67    /// [`Context::apply`](crate::Context::apply) and
68    /// [`Context::cleanup`](crate::Context::cleanup):
69    ///
70    /// * `Ok(None)` and `Ok(Some(Action::await_change()))` are
71    ///   [`Completed`](Outcome::Completed), since there is nothing more to
72    ///   do until something changes.
73    /// * Any other `Ok(Some(action))` is [`Waiting`](Outcome::Waiting),
74    ///   since the reconciler asked to be run again.
75    /// * `Err(_)` is [`Failed`](Outcome::Failed).
76    ///
77    /// A reconciler that returns a requeue action as a periodic resync after
78    /// having fully converged will therefore be reported as waiting, and
79    /// should override that with [`TraceMetadata::set_outcome`].
80    ///
81    /// The controller itself reports any `Ok(Some(action))` from
82    /// [`Context::cleanup`](crate::Context::cleanup) as
83    /// [`Waiting`](Outcome::Waiting), since it means cleanup is unfinished.
84    pub fn of_result<E>(result: &Result<Option<Action>, E>) -> Self {
85        match result {
86            Ok(None) => Outcome::Completed,
87            Ok(Some(action)) if *action == Action::await_change() => Outcome::Completed,
88            Ok(Some(_)) => Outcome::Waiting,
89            Err(_) => Outcome::Failed,
90        }
91    }
92}
93
94impl Display for Outcome {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.write_str(self.as_str())
97    }
98}
99
100/// Which part of the resource's lifecycle a reconciliation pass handled.
101///
102/// [`as_str`](Phase::as_str) gives the value used as a metric label, which is
103/// stable, and matches the `event_type` field of the `reconcile` tracing
104/// span.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106#[non_exhaustive]
107pub enum Phase {
108    /// The controller added its finalizer to the resource. Neither
109    /// [`apply`](crate::Context::apply) nor
110    /// [`cleanup`](crate::Context::cleanup) was called; the resource will be
111    /// reconciled again once the finalizer is in place.
112    Init,
113    /// [`Context::apply`](crate::Context::apply) was called.
114    Apply,
115    /// [`Context::cleanup`](crate::Context::cleanup) was called.
116    Cleanup,
117    /// The resource is being deleted, and there was no cleanup to run:
118    /// either the context has no finalizer, or the controller's finalizer
119    /// had already been removed.
120    Delete,
121}
122
123impl Phase {
124    /// The label value for this phase.
125    pub fn as_str(self) -> &'static str {
126        match self {
127            Phase::Init => "init",
128            Phase::Apply => "apply",
129            Phase::Cleanup => "cleanup",
130            Phase::Delete => "delete",
131        }
132    }
133}
134
135impl Display for Phase {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        f.write_str(self.as_str())
138    }
139}
140
141/// A completed (or [abandoned](Outcome::Abandoned)) reconciliation pass, as
142/// reported to [`ReconcileObserver::reconciled`].
143#[derive(Clone, Copy, Debug)]
144#[non_exhaustive]
145pub struct ReconcileRecord<'a> {
146    /// The [name](crate::Controller::with_name) of the controller.
147    pub controller: &'a str,
148    /// The kind of the reconciled resource.
149    pub kind: &'a str,
150    /// The namespace of the reconciled resource, if it is namespaced.
151    pub namespace: Option<&'a str>,
152    /// The name of the reconciled resource.
153    pub name: &'a str,
154    pub phase: Phase,
155    pub outcome: Outcome,
156    /// Time spent in the pass, including the controller's finalizer
157    /// bookkeeping but excluding publishing a failure event.
158    pub duration: Duration,
159}
160
161/// A finished (or [abandoned](Outcome::Abandoned)) [`Step`], as reported to
162/// [`ReconcileObserver::step_finished`].
163#[derive(Clone, Copy, Debug)]
164#[non_exhaustive]
165pub struct StepRecord<'a> {
166    /// The [name](crate::Controller::with_name) of the controller.
167    pub controller: &'a str,
168    /// The kind of the reconciled resource.
169    pub kind: &'a str,
170    /// The namespace of the reconciled resource, if it is namespaced.
171    pub namespace: Option<&'a str>,
172    /// The name of the reconciled resource.
173    pub name: &'a str,
174    /// The name the step was started with.
175    pub step: &'static str,
176    pub outcome: Outcome,
177    pub duration: Duration,
178}
179
180/// Receives reports of what reconciliation did.
181///
182/// Methods are called synchronously from the reconciliation (including from
183/// [`Step`]'s `Drop` implementation), so they should be cheap and must not
184/// block.
185///
186/// Records identify the reconciled resource, but its namespace and name
187/// usually make poor metric labels: they are unbounded, and a label set is
188/// kept for as long as the process lives, even after the resource is
189/// deleted.
190pub trait ReconcileObserver: Send + Sync {
191    /// Called when a reconciliation pass ends, including when it is
192    /// cancelled.
193    fn reconciled(&self, record: &ReconcileRecord<'_>) {
194        let _record = record;
195    }
196
197    /// Called when a [`Step`] is finished or dropped.
198    fn step_finished(&self, record: &StepRecord<'_>) {
199        let _record = record;
200    }
201}
202
203/// The context shared by everything recorded during one reconciliation pass.
204pub(crate) struct Pass {
205    pub(crate) controller: Arc<str>,
206    pub(crate) reference: ObjectReference,
207    pub(crate) observer: Option<Arc<dyn ReconcileObserver>>,
208    pub(crate) events: Option<Arc<EventRecorder>>,
209}
210
211impl Pass {
212    fn kind(&self) -> &str {
213        self.reference.kind.as_deref().unwrap_or_default()
214    }
215
216    fn name(&self) -> &str {
217        self.reference.name.as_deref().unwrap_or_default()
218    }
219
220    pub(crate) fn record(&self, phase: Phase, outcome: Outcome, duration: Duration) {
221        if let Some(observer) = &self.observer {
222            observer.reconciled(&ReconcileRecord {
223                controller: &self.controller,
224                kind: self.kind(),
225                namespace: self.reference.namespace.as_deref(),
226                name: self.name(),
227                phase,
228                outcome,
229                duration,
230            });
231        }
232    }
233}
234
235/// Times one named step of a reconciliation pass, reporting it to the
236/// controller's [`ReconcileObserver`] when finished or dropped.
237///
238/// Created by [`TraceMetadata::step`]. A step dropped without being finished
239/// is reported as [`Outcome::Abandoned`], so that `?` propagating an error
240/// out of a step identifies the step the pass stopped in, without any
241/// bookkeeping at the early return. The flip side is that every path out of
242/// a step that does reach a conclusion must finish it explicitly:
243///
244/// ```no_run
245/// # use k8s_controller::{Outcome, TraceMetadata};
246/// # async fn create_certificate() -> Result<(), kube::Error> { Ok(()) }
247/// # async fn f(metadata: &TraceMetadata, tls_enabled: bool) -> Result<(), kube::Error> {
248/// let step = metadata.step("certificate");
249/// if tls_enabled {
250///     create_certificate().await?;
251///     step.finish(Outcome::Completed);
252/// } else {
253///     step.finish(Outcome::Skipped);
254/// }
255/// # Ok(())
256/// # }
257/// ```
258#[must_use = "a step that is never finished is reported as abandoned"]
259pub struct Step {
260    pass: Option<Arc<Pass>>,
261    name: &'static str,
262    start: Instant,
263    outcome: Option<Outcome>,
264}
265
266impl Step {
267    /// Finishes the step with the given outcome.
268    pub fn finish(mut self, outcome: Outcome) {
269        self.outcome = Some(outcome);
270    }
271
272    /// Finishes the step with the outcome [classified](Outcome::of_result)
273    /// from a reconciler-style result.
274    ///
275    /// Prefer this to propagating an error out of the step with `?` when the
276    /// result is in hand, since that reports the step as
277    /// [abandoned](Outcome::Abandoned) rather than [failed](Outcome::Failed).
278    pub fn finish_with<E>(self, result: &Result<Option<Action>, E>) {
279        self.finish(Outcome::of_result(result));
280    }
281}
282
283impl Drop for Step {
284    fn drop(&mut self) {
285        let Some(pass) = &self.pass else { return };
286        let Some(observer) = &pass.observer else {
287            return;
288        };
289        observer.step_finished(&StepRecord {
290            controller: &pass.controller,
291            kind: pass.kind(),
292            namespace: pass.reference.namespace.as_deref(),
293            name: pass.name(),
294            step: self.name,
295            outcome: self.outcome.unwrap_or(Outcome::Abandoned),
296            duration: self.start.elapsed(),
297        });
298    }
299}
300
301/// Per-pass state handed to [`Context::apply`](crate::Context::apply) and
302/// [`Context::cleanup`](crate::Context::cleanup).
303///
304/// It collects annotations for the pass's tracing span, times
305/// [steps](TraceMetadata::step), overrides the pass's reported
306/// [outcome](TraceMetadata::set_outcome), and
307/// [publishes events](TraceMetadata::publish_event) about the resource being
308/// reconciled.
309///
310/// A `TraceMetadata` created with [`Default`] (for instance, to call a
311/// reconciler from a unit test) accepts all of these, but reports steps and
312/// publishes events nowhere.
313#[derive(Default)]
314pub struct TraceMetadata {
315    pub(crate) annotations: BTreeMap<String, String>,
316    pub(crate) outcome: Option<Outcome>,
317    pass: Option<Arc<Pass>>,
318}
319
320impl std::fmt::Debug for TraceMetadata {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        f.debug_struct("TraceMetadata")
323            .field("annotations", &self.annotations)
324            .field("outcome", &self.outcome)
325            .finish_non_exhaustive()
326    }
327}
328
329impl TraceMetadata {
330    pub(crate) fn for_pass(pass: Arc<Pass>) -> Self {
331        Self {
332            pass: Some(pass),
333            ..Default::default()
334        }
335    }
336
337    /// Adds a key/value pair to the `metadata` field of the pass's
338    /// `reconcile` tracing span, replacing any earlier value for `key`.
339    pub fn annotate<K: Display, V: Display>(&mut self, key: K, val: V) {
340        self.annotations.insert(key.to_string(), val.to_string());
341    }
342
343    /// Starts timing the step named `name`. See [`Step`].
344    ///
345    /// Step names become metric labels, so they should come from a small
346    /// fixed set.
347    pub fn step(&self, name: &'static str) -> Step {
348        Step {
349            pass: self.pass.clone(),
350            name,
351            start: Instant::now(),
352            outcome: None,
353        }
354    }
355
356    /// Overrides the outcome reported for this pass, if the reconciler
357    /// returns `Ok`. By default the outcome is
358    /// [classified](Outcome::of_result) from what the reconciler returns;
359    /// an `Err` is always reported as [`Outcome::Failed`].
360    pub fn set_outcome(&mut self, outcome: Outcome) {
361        self.outcome = Some(outcome);
362    }
363
364    /// Publishes `event` about the resource being reconciled, using the
365    /// controller's [event recorder](crate::Controller::with_event_recorder).
366    /// Does nothing if the controller has none.
367    ///
368    /// Failure to publish is logged rather than returned, since an event
369    /// only reports on reconciliation and should not change its course.
370    /// Use [`EventRecorder::publish`] directly to handle errors.
371    pub async fn publish_event(&self, event: Event) {
372        let Some(pass) = &self.pass else { return };
373        let Some(events) = &pass.events else { return };
374        if let Err(e) = events.publish_to(&pass.reference, &event, false).await {
375            warn!(
376                error = %e,
377                reason = %event.reason,
378                controller = %pass.controller,
379                "failed to publish event",
380            );
381        }
382    }
383}