Skip to main content

kaniop_person/
controller.rs

1use crate::crd::KanidmPersonAccount;
2use crate::reconcile::reconcile_person_account;
3
4use kaniop_k8s_util::error::{Error, Result};
5use kaniop_operator::backoff_reconciler;
6use kaniop_operator::controller::{
7    ControllerId, State, check_api_queryable,
8    context::{BackoffContext, Context as KaniopContext, IdmClientContext},
9    idm_reconcile_interval,
10};
11use kaniop_operator::metrics::ControllerMetrics;
12
13use kanidm_client::KanidmClient;
14
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use futures::StreamExt;
19use kube::client::Client;
20use kube::runtime::controller::{self, Controller};
21use kube::runtime::reflector::ObjectRef;
22use kube::runtime::watcher;
23use time::OffsetDateTime;
24use tokio::sync::RwLock;
25use tokio::time::Duration;
26use tracing::{info, trace};
27
28pub const CONTROLLER_ID: ControllerId = "person-account";
29
30#[derive(Clone)]
31pub struct Context {
32    pub kaniop_ctx: KaniopContext<KanidmPersonAccount>,
33    /// Internal controller cache
34    pub internal_cache: Arc<RwLock<HashMap<ObjectRef<KanidmPersonAccount>, time::OffsetDateTime>>>,
35}
36
37impl Context {
38    pub fn new(kaniop_ctx: KaniopContext<KanidmPersonAccount>) -> Self {
39        Context {
40            kaniop_ctx,
41            internal_cache: Arc::default(),
42        }
43    }
44}
45
46impl BackoffContext<KanidmPersonAccount> for Context {
47    fn metrics(&self) -> &Arc<ControllerMetrics> {
48        self.kaniop_ctx.metrics()
49    }
50    async fn get_backoff(&self, obj_ref: ObjectRef<KanidmPersonAccount>) -> Duration {
51        self.kaniop_ctx.get_backoff(obj_ref).await
52    }
53
54    async fn reset_backoff(&self, obj_ref: ObjectRef<KanidmPersonAccount>) {
55        self.kaniop_ctx.reset_backoff(obj_ref).await
56    }
57}
58
59impl IdmClientContext<KanidmPersonAccount> for Context {
60    async fn get_idm_client(&self, obj: &KanidmPersonAccount) -> Result<Arc<KanidmClient>> {
61        self.kaniop_ctx.get_idm_client(obj).await
62    }
63}
64
65pub async fn cleanup_expired_tokens(ctx: Arc<Context>) {
66    loop {
67        tokio::time::sleep(idm_reconcile_interval()).await;
68        trace!("cleaning up expired tokens cache");
69        let now = OffsetDateTime::now_utc();
70        {
71            let mut cache = ctx.internal_cache.write().await;
72            cache.retain(|_, v| *v > now);
73            cache.shrink_to_fit();
74        }
75    }
76}
77
78/// Initialize Kanidm controller and shared state
79pub async fn run(state: State, client: Client) {
80    let person = check_api_queryable::<KanidmPersonAccount>(client.clone()).await;
81
82    let ctx = Arc::new(Context::new(state.to_context(client, CONTROLLER_ID)));
83
84    info!(msg = format!("starting {CONTROLLER_ID} controller"));
85    // TODO: watcher::Config::default().streaming_lists() when stabilized in K8s
86    // https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
87    let person_controller = Controller::new(person, watcher::Config::default().any_semantic())
88        // debounce to filter out reconcile calls that happen quick succession (only taking the latest)
89        .with_config(controller::Config::default().debounce(Duration::from_millis(500)))
90        .shutdown_on_signal()
91        .run(
92            backoff_reconciler!(reconcile_person_account),
93            |_obj, _error: &Error, _ctx| unreachable!(),
94            ctx.clone(),
95        )
96        .filter_map(|x| async move { std::result::Result::ok(x) })
97        .for_each(|_| futures::future::ready(()));
98
99    ctx.kaniop_ctx.metrics.ready_set(1);
100    tokio::select! {
101        _ = person_controller => {},
102        _ = cleanup_expired_tokens(ctx.clone()) => {},
103    }
104}