kaniop_oauth2/
controller.rs

1use crate::crd::KanidmOAuth2Client;
2use crate::reconcile::reconcile_oauth2;
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};
10use kaniop_operator::controller::{
11    RELOAD_BUFFER_SIZE, SUBSCRIBE_BUFFER_SIZE, create_subscriber, create_watcher,
12};
13use kaniop_operator::metrics::ControllerMetrics;
14
15use std::sync::Arc;
16
17use futures::StreamExt;
18use futures::channel::mpsc;
19use k8s_openapi::api::core::v1::Secret;
20use kanidm_client::KanidmClient;
21use kube::client::Client;
22use kube::runtime::controller::{self, Controller};
23use kube::runtime::reflector::{ObjectRef, Store};
24use kube::runtime::watcher;
25use tokio::time::Duration;
26use tracing::info;
27
28pub const CONTROLLER_ID: ControllerId = "oauth2";
29
30#[derive(Clone)]
31pub struct Context {
32    pub kaniop_ctx: KaniopContext<KanidmOAuth2Client>,
33    /// Secret store for OAuth2 clients
34    pub secret_store: Store<Secret>,
35}
36
37impl Context {
38    pub fn new(kaniop_ctx: KaniopContext<KanidmOAuth2Client>, secret_store: Store<Secret>) -> Self {
39        Context {
40            kaniop_ctx,
41            secret_store,
42        }
43    }
44}
45
46impl BackoffContext<KanidmOAuth2Client> for Context {
47    fn metrics(&self) -> &Arc<ControllerMetrics> {
48        self.kaniop_ctx.metrics()
49    }
50    async fn get_backoff(&self, obj_ref: ObjectRef<KanidmOAuth2Client>) -> Duration {
51        self.kaniop_ctx.get_backoff(obj_ref).await
52    }
53
54    async fn reset_backoff(&self, obj_ref: ObjectRef<KanidmOAuth2Client>) {
55        self.kaniop_ctx.reset_backoff(obj_ref).await
56    }
57}
58
59impl IdmClientContext<KanidmOAuth2Client> for Context {
60    async fn get_idm_client(&self, obj: &KanidmOAuth2Client) -> Result<Arc<KanidmClient>> {
61        self.kaniop_ctx.get_idm_client(obj).await
62    }
63}
64
65/// Initialize Kanidm controller and shared state
66pub async fn run(state: State, client: Client) {
67    let oauth2 = check_api_queryable::<KanidmOAuth2Client>(client.clone()).await;
68    let secret = check_api_queryable::<Secret>(client.clone()).await;
69    let secret_r = create_subscriber::<Secret>(SUBSCRIBE_BUFFER_SIZE);
70
71    let (reload_tx, reload_rx) = mpsc::channel(RELOAD_BUFFER_SIZE);
72    let ctx = Arc::new(Context::new(
73        state.to_context(client, CONTROLLER_ID),
74        secret_r.store,
75    ));
76    let kaniop_ctx = Arc::new(ctx.kaniop_ctx.clone());
77
78    // TODO: just metadata is needed
79    let secret_watcher = create_watcher(
80        secret,
81        secret_r.writer,
82        reload_tx.clone(),
83        CONTROLLER_ID,
84        kaniop_ctx,
85    );
86    info!(msg = format!("starting {CONTROLLER_ID} controller"));
87    // TODO: watcher::Config::default().streaming_lists() when stabilized in K8s
88    // https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
89    let oauth2_controller = Controller::new(oauth2, watcher::Config::default().any_semantic())
90        // debounce to filter out reconcile calls that happen quick succession (only taking the latest)
91        .with_config(controller::Config::default().debounce(Duration::from_millis(500)))
92        .owns_shared_stream(secret_r.subscriber)
93        .reconcile_all_on(reload_rx.map(|_| ()))
94        .shutdown_on_signal()
95        .run(
96            backoff_reconciler!(reconcile_oauth2),
97            |_obj, _error: &Error, _ctx| unreachable!(),
98            ctx.clone(),
99        )
100        .filter_map(|x| async move { std::result::Result::ok(x) })
101        .for_each(|_| futures::future::ready(()));
102
103    ctx.kaniop_ctx.metrics.ready_set(1);
104    tokio::select! {
105        _ = oauth2_controller => {},
106        _ = secret_watcher => {},
107    }
108}