kaniop_person/
controller.rs

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