k8s_controller/lib.rs
1#![allow(clippy::style)]
2#![allow(clippy::complexity)]
3#![allow(clippy::large_enum_variant)]
4#![allow(clippy::mutable_key_type)]
5#![allow(clippy::stable_sort_primitive)]
6#![allow(clippy::map_entry)]
7#![allow(clippy::box_default)]
8#![warn(clippy::bool_comparison)]
9#![warn(clippy::clone_on_ref_ptr)]
10#![warn(clippy::no_effect)]
11#![warn(clippy::unnecessary_unwrap)]
12#![warn(clippy::dbg_macro)]
13#![warn(clippy::todo)]
14#![warn(clippy::wildcard_dependencies)]
15#![warn(clippy::zero_prefixed_literal)]
16#![warn(clippy::borrowed_box)]
17#![warn(clippy::deref_addrof)]
18#![warn(clippy::double_must_use)]
19#![warn(clippy::double_parens)]
20#![warn(clippy::extra_unused_lifetimes)]
21#![warn(clippy::needless_borrow)]
22#![warn(clippy::needless_question_mark)]
23#![warn(clippy::needless_return)]
24#![warn(clippy::redundant_pattern)]
25#![warn(clippy::redundant_slicing)]
26#![warn(clippy::redundant_static_lifetimes)]
27#![warn(clippy::single_component_path_imports)]
28#![warn(clippy::unnecessary_cast)]
29#![warn(clippy::useless_asref)]
30#![warn(clippy::useless_conversion)]
31#![warn(clippy::builtin_type_shadow)]
32#![warn(clippy::duplicate_underscore_argument)]
33#![warn(double_negations)]
34#![warn(clippy::unnecessary_mut_passed)]
35#![warn(clippy::wildcard_in_or_patterns)]
36#![warn(clippy::crosspointer_transmute)]
37#![warn(clippy::excessive_precision)]
38#![warn(clippy::panicking_overflow_checks)]
39#![warn(clippy::as_conversions)]
40#![warn(clippy::match_overlapping_arm)]
41#![warn(clippy::zero_divided_by_zero)]
42#![warn(clippy::must_use_unit)]
43#![warn(clippy::suspicious_assignment_formatting)]
44#![warn(clippy::suspicious_else_formatting)]
45#![warn(clippy::suspicious_unary_op_formatting)]
46#![warn(clippy::mut_mutex_lock)]
47#![warn(clippy::print_literal)]
48#![warn(clippy::same_item_push)]
49#![warn(clippy::useless_format)]
50#![warn(clippy::write_literal)]
51#![warn(clippy::redundant_closure)]
52#![warn(clippy::redundant_closure_call)]
53#![warn(clippy::unnecessary_lazy_evaluations)]
54#![warn(clippy::partialeq_ne_impl)]
55#![warn(clippy::redundant_field_names)]
56#![warn(clippy::transmutes_expressible_as_ptr_casts)]
57#![warn(clippy::unused_async)]
58#![warn(clippy::disallowed_methods)]
59#![warn(clippy::disallowed_macros)]
60#![warn(clippy::disallowed_types)]
61#![warn(clippy::from_over_into)]
62#![cfg_attr(docsrs, feature(async_fn_in_trait))]
63
64//! This crate implements a lightweight framework around
65//! [`kube_runtime::Controller`] which provides a simpler interface for common
66//! controller patterns. To use it, you define the data that your controller is
67//! going to operate over, and implement the [`Context`] trait on that struct:
68//!
69//! ```no_run
70//! # use std::collections::BTreeSet;
71//! # use std::sync::{Arc, Mutex};
72//! # use k8s_openapi::api::core::v1::Pod;
73//! # use kube::{Client, Resource};
74//! # use kube_runtime::controller::Action;
75//! #[derive(Default, Clone)]
76//! struct PodCounter {
77//! pods: Arc<Mutex<BTreeSet<String>>>,
78//! }
79//!
80//! impl PodCounter {
81//! fn pod_count(&self) -> usize {
82//! let mut pods = self.pods.lock().unwrap();
83//! pods.len()
84//! }
85//! }
86//!
87//! #[async_trait::async_trait]
88//! impl k8s_controller::Context for PodCounter {
89//! type Resource = Pod;
90//! type Error = kube::Error;
91//!
92//! const FINALIZER_NAME: Option<&'static str> = Some("example.com/pod-counter");
93//!
94//! async fn apply(
95//! &self,
96//! client: Client,
97//! pod: &Self::Resource,
98//! _metadata: &mut k8s_controller::TraceMetadata,
99//! ) -> Result<Option<Action>, Self::Error> {
100//! let mut pods = self.pods.lock().unwrap();
101//! pods.insert(pod.meta().uid.as_ref().unwrap().clone());
102//! Ok(None)
103//! }
104//!
105//! async fn cleanup(
106//! &self,
107//! client: Client,
108//! pod: &Self::Resource,
109//! _metadata: &mut k8s_controller::TraceMetadata,
110//! ) -> Result<Option<Action>, Self::Error> {
111//! let mut pods = self.pods.lock().unwrap();
112//! pods.remove(pod.meta().uid.as_ref().unwrap());
113//! Ok(None)
114//! }
115//! }
116//! ```
117//!
118//! Then you can run it against your Kubernetes cluster by creating a
119//! [`Controller`]:
120//!
121//! ```no_run
122//! # use std::collections::BTreeSet;
123//! # use std::sync::{Arc, Mutex};
124//! # use std::thread::sleep;
125//! # use std::time::Duration;
126//! # use k8s_openapi::api::core::v1::Pod;
127//! # use kube::{Config, Client};
128//! # use kube_runtime::controller::Action;
129//! # use kube_runtime::watcher;
130//! # use tokio::task;
131//! # #[derive(Default, Clone)]
132//! # struct PodCounter {
133//! # pods: Arc<Mutex<BTreeSet<String>>>,
134//! # }
135//! # impl PodCounter {
136//! # fn pod_count(&self) -> usize { todo!() }
137//! # }
138//! # #[async_trait::async_trait]
139//! # impl k8s_controller::Context for PodCounter {
140//! # type Resource = Pod;
141//! # type Error = kube::Error;
142//! # const FINALIZER_NAME: Option<&'static str> = Some("example.com/pod-counter");
143//! # async fn apply(
144//! # &self,
145//! # client: Client,
146//! # pod: &Self::Resource,
147//! # _metadata: &mut k8s_controller::TraceMetadata,
148//! # ) -> Result<Option<Action>, Self::Error> { todo!() }
149//! # async fn cleanup(
150//! # &self,
151//! # client: Client,
152//! # pod: &Self::Resource,
153//! # _metadata: &mut k8s_controller::TraceMetadata,
154//! # ) -> Result<Option<Action>, Self::Error> { todo!() }
155//! # }
156//! # async fn foo() {
157//! let kube_config = Config::infer().await.unwrap();
158//! let kube_client = Client::try_from(kube_config).unwrap();
159//! let context = PodCounter::default();
160//! let controller = k8s_controller::Controller::namespaced_all(
161//! kube_client,
162//! context.clone(),
163//! watcher::Config::default(),
164//! );
165//! task::spawn(controller.run());
166//!
167//! loop {
168//! println!("{} pods running", context.pod_count());
169//! sleep(Duration::from_secs(1));
170//! }
171//! # }
172//! ```
173//!
174//! If you run multiple replicas of your controller (for instance, to avoid
175//! downtime of webhooks served by the same process during rollouts), you
176//! can use [leader election](LeaderElection) to ensure that only one
177//! replica reconciles at a time:
178//!
179//! ```no_run
180//! # use std::collections::BTreeSet;
181//! # use std::sync::{Arc, Mutex};
182//! # use k8s_openapi::api::core::v1::Pod;
183//! # use kube::{Config, Client};
184//! # use kube_runtime::controller::Action;
185//! # use kube_runtime::watcher;
186//! # #[derive(Default, Clone)]
187//! # struct PodCounter {
188//! # pods: Arc<Mutex<BTreeSet<String>>>,
189//! # }
190//! # #[async_trait::async_trait]
191//! # impl k8s_controller::Context for PodCounter {
192//! # type Resource = Pod;
193//! # type Error = kube::Error;
194//! # const FINALIZER_NAME: Option<&'static str> = Some("example.com/pod-counter");
195//! # async fn apply(
196//! # &self,
197//! # client: Client,
198//! # pod: &Self::Resource,
199//! # _metadata: &mut k8s_controller::TraceMetadata,
200//! # ) -> Result<Option<Action>, Self::Error> { todo!() }
201//! # }
202//! # async fn foo() {
203//! # let kube_config = Config::infer().await.unwrap();
204//! # let kube_client = Client::try_from(kube_config).unwrap();
205//! # let context = PodCounter::default();
206//! let leader_election = k8s_controller::LeaderElection::new(
207//! kube_client.clone(),
208//! "my-namespace",
209//! "pod-counter",
210//! // must be unique per replica; the pod name is a good choice
211//! &std::env::var("HOSTNAME").unwrap(),
212//! );
213//! loop {
214//! let controller = k8s_controller::Controller::namespaced_all(
215//! kube_client.clone(),
216//! context.clone(),
217//! watcher::Config::default(),
218//! );
219//! leader_election
220//! // see below for stopping on a shutdown signal instead
221//! .with_lease(std::future::pending::<()>(), controller.run())
222//! .await;
223//! // leadership was lost; the controller has been stopped, and we loop
224//! // to rejoin the election. Exiting the process (and letting
225//! // Kubernetes restart it) works too, and is preferable if your
226//! // reconcilers spawn tasks or do blocking work that stopping the
227//! // controller can't cancel.
228//! }
229//! # }
230//! ```
231//!
232//! A process that runs several controllers should usually guard them all
233//! with a single lease, rather than electing a separate leader per
234//! controller (which could scatter the controllers across replicas). Use
235//! [`LeaderElection::with_lease`] with a future that runs all of them.
236//! This example also shuts down gracefully: on `shutdown`, a replica
237//! waiting for the lease stops waiting, and the leader finishes its
238//! in-flight reconciles and then releases the lease, rather than leaving
239//! the other replicas to wait for it to expire.
240//!
241//! ```no_run
242//! # use std::collections::BTreeSet;
243//! # use std::sync::{Arc, Mutex};
244//! # use futures::FutureExt;
245//! # use k8s_openapi::api::core::v1::Pod;
246//! # use kube::{Config, Client};
247//! # use kube_runtime::controller::Action;
248//! # use kube_runtime::watcher;
249//! # #[derive(Default, Clone)]
250//! # struct PodCounter {
251//! # pods: Arc<Mutex<BTreeSet<String>>>,
252//! # }
253//! # #[async_trait::async_trait]
254//! # impl k8s_controller::Context for PodCounter {
255//! # type Resource = Pod;
256//! # type Error = kube::Error;
257//! # const FINALIZER_NAME: Option<&'static str> = Some("example.com/pod-counter");
258//! # async fn apply(
259//! # &self,
260//! # client: Client,
261//! # pod: &Self::Resource,
262//! # _metadata: &mut k8s_controller::TraceMetadata,
263//! # ) -> Result<Option<Action>, Self::Error> { todo!() }
264//! # }
265//! # async fn foo() {
266//! # let kube_config = Config::infer().await.unwrap();
267//! # let kube_client = Client::try_from(kube_config).unwrap();
268//! # let leader_election = k8s_controller::LeaderElection::new(
269//! # kube_client.clone(),
270//! # "my-namespace",
271//! # "pod-counter",
272//! # &std::env::var("HOSTNAME").unwrap(),
273//! # );
274//! # let termination_signal = std::future::pending::<()>();
275//! // any future which completes when the process should shut down
276//! let shutdown = termination_signal.shared();
277//! let controller_a = k8s_controller::Controller::namespaced(
278//! kube_client.clone(),
279//! PodCounter::default(),
280//! "namespace-a",
281//! watcher::Config::default(),
282//! )
283//! .with_controller(|controller| controller.graceful_shutdown_on(shutdown.clone()));
284//! let controller_b = k8s_controller::Controller::namespaced(
285//! kube_client.clone(),
286//! PodCounter::default(),
287//! "namespace-b",
288//! watcher::Config::default(),
289//! )
290//! .with_controller(|controller| controller.graceful_shutdown_on(shutdown.clone()));
291//! let outcome = leader_election
292//! .with_lease(
293//! shutdown,
294//! futures::future::join(controller_a.run(), controller_b.run()),
295//! )
296//! .await;
297//! if matches!(outcome, k8s_controller::LeaseOutcome::Lost) {
298//! // both controllers have been stopped
299//! std::process::exit(1);
300//! }
301//! # }
302//! ```
303//!
304//! # Observability
305//!
306//! Every reconciliation pass is logged, as a `reconcile` [tracing]
307//! span. Beyond that, a [`Controller`] can be configured to:
308//!
309//! * report each pass, and each [step](Step) a reconciler divides its work
310//! into, to a [`ReconcileObserver`], for metrics. With the `prometheus`
311//! feature, [`PrometheusMetrics`] exports these
312//! as Prometheus metrics. See the [`observe`] module.
313//! * publish a Kubernetes event on the resource whenever reconciling it
314//! fails, through an [`EventRecorder`](events::EventRecorder), so that
315//! `kubectl describe` explains why it is not converging. Reconcilers can
316//! publish events of their own through the same recorder. See the
317//! [`events`] module.
318//!
319//! * report the state of a resource through the standard
320//! `status.conditions`, maintained with the [`conditions`] module, which
321//! keeps `lastTransitionTime` and `observedGeneration` consistent with
322//! Kubernetes conventions. Writing the status remains up to the
323//! reconciler.
324//!
325//! A single observer is typically shared by every controller in a process,
326//! while each controller gets its own event recorder, whose reporter names
327//! that controller:
328//!
329//! ```no_run
330//! # use std::collections::BTreeSet;
331//! # use std::sync::{Arc, Mutex};
332//! # use k8s_openapi::api::core::v1::Pod;
333//! # use kube::{Config, Client};
334//! # use kube_runtime::controller::Action;
335//! # use kube_runtime::watcher;
336//! # #[derive(Default, Clone)]
337//! # struct PodCounter {
338//! # pods: Arc<Mutex<BTreeSet<String>>>,
339//! # }
340//! # #[async_trait::async_trait]
341//! # impl k8s_controller::Context for PodCounter {
342//! # type Resource = Pod;
343//! # type Error = kube::Error;
344//! # async fn apply(
345//! # &self,
346//! # client: Client,
347//! # pod: &Self::Resource,
348//! # _metadata: &mut k8s_controller::TraceMetadata,
349//! # ) -> Result<Option<Action>, Self::Error> { todo!() }
350//! # }
351//! # struct MyObserver;
352//! # impl k8s_controller::ReconcileObserver for MyObserver {}
353//! # async fn foo() {
354//! # let kube_client = Client::try_from(Config::infer().await.unwrap()).unwrap();
355//! use k8s_controller::events::{EventRecorder, Reporter};
356//!
357//! let observer: Arc<dyn k8s_controller::ReconcileObserver> = Arc::new(MyObserver);
358//! let events = Arc::new(EventRecorder::new(
359//! kube_client.clone(),
360//! Reporter {
361//! controller: "example.com/pod-counter".to_owned(),
362//! instance: std::env::var("HOSTNAME").ok(),
363//! },
364//! ));
365//! let controller = k8s_controller::Controller::namespaced_all(
366//! kube_client,
367//! PodCounter::default(),
368//! watcher::Config::default(),
369//! )
370//! .with_name("pod-counter")
371//! .with_observer(Arc::clone(&observer))
372//! .with_event_recorder(Arc::clone(&events));
373//! controller.run().await;
374//! # }
375//! ```
376//!
377//! Within a reconciler, steps are started from the [`TraceMetadata`] passed
378//! to [`Context::apply`] and [`Context::cleanup`]:
379//!
380//! ```no_run
381//! # use kube::Client;
382//! # use kube_runtime::controller::Action;
383//! # use k8s_openapi::api::core::v1::ConfigMap;
384//! # async fn sync_deployment() -> Result<(), kube::Error> { Ok(()) }
385//! # async fn deployment_ready() -> Result<bool, kube::Error> { Ok(true) }
386//! # struct Widgets;
387//! # #[async_trait::async_trait]
388//! # impl k8s_controller::Context for Widgets {
389//! # type Resource = ConfigMap;
390//! # type Error = kube::Error;
391//! async fn apply(
392//! &self,
393//! client: Client,
394//! widget: &Self::Resource,
395//! metadata: &mut k8s_controller::TraceMetadata,
396//! ) -> Result<Option<Action>, Self::Error> {
397//! let step = metadata.step("deployment");
398//! sync_deployment().await?;
399//! if !deployment_ready().await? {
400//! step.finish(k8s_controller::Outcome::Waiting);
401//! return Ok(Some(Action::requeue(std::time::Duration::from_secs(5))));
402//! }
403//! step.finish(k8s_controller::Outcome::Completed);
404//! Ok(None)
405//! }
406//! # }
407//! ```
408
409pub mod conditions;
410mod controller;
411pub mod events;
412mod leader_election;
413pub mod observe;
414#[cfg(feature = "prometheus")]
415mod prometheus;
416#[cfg(test)]
417mod test_util;
418
419pub use controller::{Context, Controller, Error};
420pub use leader_election::{LeaderElection, LeaseOutcome};
421pub use observe::{
422 Outcome, Phase, ReconcileObserver, ReconcileRecord, Step, StepRecord, TraceMetadata,
423};
424#[cfg(feature = "prometheus")]
425pub use prometheus::PrometheusMetrics;