5 unstable releases

0.3.0 Mar 4, 2024
0.2.1 Nov 27, 2023
0.2.0 Aug 10, 2023
0.1.1 Jul 14, 2023
0.1.0 Jul 10, 2023

#998 in Rust patterns

Download history 872/week @ 2024-01-24 685/week @ 2024-01-31 850/week @ 2024-02-07 720/week @ 2024-02-14 836/week @ 2024-02-21 1102/week @ 2024-02-28 715/week @ 2024-03-06 413/week @ 2024-03-13 814/week @ 2024-03-20 1172/week @ 2024-03-27 962/week @ 2024-04-03 1033/week @ 2024-04-10 974/week @ 2024-04-17 517/week @ 2024-04-24 382/week @ 2024-05-01 976/week @ 2024-05-08

3,081 downloads per month

Apache-2.0

24KB
338 lines

k8s-controller

This crate implements a lightweight framework around kube_runtime::Controller which provides a simpler interface for common controller patterns. To use it, you define the data that your controller is going to operate over, and implement the Context trait on that struct:

#[derive(Default, Clone)]
struct PodCounter {
    pods: Arc<Mutex<BTreeSet<String>>>,
}

impl PodCounter {
    fn pod_count(&self) -> usize {
        let mut pods = self.pods.lock().unwrap();
        pods.len()
    }
}

#[async_trait::async_trait]
impl k8s_controller::Context for PodCounter {
    type Resource = Pod;
    type Error = kube::Error;

    const FINALIZER_NAME: &'static str = "example.com/pod-counter";

    async fn apply(
        &self,
        client: Client,
        pod: &Self::Resource,
    ) -> Result<Option<Action>, Self::Error> {
        let mut pods = self.pods.lock().unwrap();
        pods.insert(pod.meta().uid.as_ref().unwrap().clone());
        Ok(None)
    }

    async fn cleanup(
        &self,
        client: Client,
        pod: &Self::Resource,
    ) -> Result<Option<Action>, Self::Error> {
        let mut pods = self.pods.lock().unwrap();
        pods.remove(pod.meta().uid.as_ref().unwrap());
        Ok(None)
    }
}

Then you can run it against your Kubernetes cluster by creating a Controller:

let kube_config = Config::infer().await.unwrap();
let kube_client = Client::try_from(kube_config).unwrap();
let context = PodCounter::default();
let controller = k8s_controller::Controller::namespaced_all(
    kube_client,
    context.clone(),
    ListParams::default(),
);
task::spawn(controller.run());

loop {
    println!("{} pods running", context.pod_count());
    sleep(Duration::from_secs(1));
}

Dependencies

~70MB
~1M SLoC