#kubernetes #kubernetes-cluster #controller

k8s-controller

lightweight framework for writing kubernetes controllers

9 unstable releases (3 breaking)

0.4.0 Aug 22, 2024
0.3.3 Aug 20, 2024
0.3.2 Jul 24, 2024
0.3.1 Jun 6, 2024
0.1.1 Jul 14, 2023

#9 in #kubernetes-cluster

Download history 567/week @ 2024-06-16 637/week @ 2024-06-23 742/week @ 2024-06-30 422/week @ 2024-07-07 387/week @ 2024-07-14 610/week @ 2024-07-21 585/week @ 2024-07-28 481/week @ 2024-08-04 461/week @ 2024-08-11 786/week @ 2024-08-18 721/week @ 2024-08-25 570/week @ 2024-09-01 795/week @ 2024-09-08 679/week @ 2024-09-15 817/week @ 2024-09-22 542/week @ 2024-09-29

2,835 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

~64MB
~1M SLoC