Skip to main content

Module controller

Module controller 

Source
Available on crate feature k8s only.
Expand description

Controllers: watch a kind, reconcile each object toward what it asks for, requeue, clean up through a finalizer — kube-runtime’s controller with the parts every operator writes anyway: an Operator running several controllers under leader election, a Context with status and event helpers, metrics on /metrics, a readiness check, and the RBAC rules the controllers need.

use std::sync::Arc;
use std::time::Duration;
use rws_k8s::k8s::controller::{Action, Context, Controller, Operator};
use rws_k8s::k8s::kube::{api::Api, CustomResource};
use rws_k8s::k8s::schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)]
#[kube(group = "example.com", version = "v1", kind = "Backup", namespaced, status = "BackupStatus")]
pub struct BackupSpec { pub schedule: String }

#[derive(Deserialize, Serialize, Clone, Debug, Default, JsonSchema)]
pub struct BackupStatus { pub last_run: Option<String> }

async fn reconcile(backup: Arc<Backup>, ctx: Arc<Context>) -> Result<Action, rws_k8s::k8s::Error> {
    // … make the world match backup.spec …
    ctx.patch_status(&*backup, serde_json::json!({ "last_run": "now" })).await?;
    Ok(Action::requeue(Duration::from_secs(300)))
}

let client = rws_k8s::k8s::client::client().await?;
Operator::new(client.clone(), "backup-operator")
    .leader_election("default", "backup-operator")
    .controller(Controller::new(Api::<Backup>::all(client)).reconcile(reconcile).finalizer("example.com/cleanup", |_backup, _ctx| async { Ok(()) }))
    .run()
    .await;

A reconcile that fails is retried after on_error’s delay (5 s by default, doubling up to 5 min for the same object). With a finalizer, the cleanup runs when the object is deleted and the finalizer is removed after it succeeds.

Structs§

Action
Results of the reconciliation attempt
Context
What a reconcile gets besides the object: the client, an event recorder, and the operator’s name.
Controller
One controller: a kind, what it owns, how it reconciles. See the module docs.
Operator
Several controllers, optionally under leader election, with a readiness check. See the module docs.

Traits§

Runnable
A controller, its kind erased, for the Operator.

Functions§

backoff
The delay before retry number failures (1-based): first doubled per failure, at most 5 minutes.
group_and_plural
The API group and plural of K (("apps", "deployments")).
metrics_text
rws_controller_reconciles_total / rws_controller_reconcile_errors_total by controller kind.