|
| 1 | +use std::{sync::Arc, time::Duration}; |
| 2 | + |
| 3 | +use futures::StreamExt; |
| 4 | +use snafu::{OptionExt, ResultExt, Snafu}; |
| 5 | +use stackable_operator::{ |
| 6 | + client::Client, |
| 7 | + k8s_openapi::{ |
| 8 | + api::core::v1::Pod, |
| 9 | + chrono::{self, DateTime, FixedOffset, Utc}, |
| 10 | + }, |
| 11 | + kube::{ |
| 12 | + self, |
| 13 | + api::{EvictParams, ListParams}, |
| 14 | + core::DynamicObject, |
| 15 | + runtime::{ |
| 16 | + controller::{Action, Context}, |
| 17 | + reflector::ObjectRef, |
| 18 | + Controller, |
| 19 | + }, |
| 20 | + }, |
| 21 | + logging::controller::{report_controller_reconciled, ReconcilerError}, |
| 22 | +}; |
| 23 | +use strum::{EnumDiscriminants, IntoStaticStr}; |
| 24 | + |
| 25 | +struct Ctx { |
| 26 | + client: Client, |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Snafu, Debug, EnumDiscriminants)] |
| 30 | +#[strum_discriminants(derive(IntoStaticStr))] |
| 31 | +enum Error { |
| 32 | + #[snafu(display("Pod has no name"))] |
| 33 | + PodHasNoName, |
| 34 | + #[snafu(display( |
| 35 | + "failed to parse expiry timestamp annotation ({annotation:?}: {value:?}) as RFC 3999" |
| 36 | + ))] |
| 37 | + UnparseableExpiryTimestamp { |
| 38 | + source: chrono::ParseError, |
| 39 | + annotation: String, |
| 40 | + value: String, |
| 41 | + }, |
| 42 | + #[snafu(display("failed to evict Pod"))] |
| 43 | + EvictPod { source: kube::Error }, |
| 44 | +} |
| 45 | + |
| 46 | +impl ReconcilerError for Error { |
| 47 | + fn category(&self) -> &'static str { |
| 48 | + ErrorDiscriminants::from(self).into() |
| 49 | + } |
| 50 | + |
| 51 | + fn secondary_object(&self) -> Option<ObjectRef<DynamicObject>> { |
| 52 | + match self { |
| 53 | + Error::PodHasNoName => None, |
| 54 | + Error::UnparseableExpiryTimestamp { |
| 55 | + source: _, |
| 56 | + annotation: _, |
| 57 | + value: _, |
| 58 | + } => None, |
| 59 | + Error::EvictPod { source: _ } => None, |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +pub async fn start(client: &Client) { |
| 65 | + let controller = Controller::new(client.get_all_api::<Pod>(), ListParams::default()); |
| 66 | + controller |
| 67 | + .run( |
| 68 | + reconcile, |
| 69 | + error_policy, |
| 70 | + Context::new(Ctx { |
| 71 | + client: client.clone(), |
| 72 | + }), |
| 73 | + ) |
| 74 | + .for_each(|res| async move { |
| 75 | + report_controller_reconciled(client, "pod.restarter.commons.stackable.tech", &res) |
| 76 | + }) |
| 77 | + .await; |
| 78 | +} |
| 79 | + |
| 80 | +async fn reconcile(pod: Arc<Pod>, ctx: Context<Ctx>) -> Result<Action, Error> { |
| 81 | + if pod.metadata.deletion_timestamp.is_some() { |
| 82 | + // Object is already being deleted, no point trying again |
| 83 | + return Ok(Action::await_change()); |
| 84 | + } |
| 85 | + |
| 86 | + let pod_expires_at = pod |
| 87 | + .metadata |
| 88 | + .annotations |
| 89 | + .iter() |
| 90 | + .flatten() |
| 91 | + .filter(|(k, _)| k.starts_with("restarter.stackable.tech/expires-at.")) |
| 92 | + .map(|(k, v)| { |
| 93 | + DateTime::parse_from_rfc3339(v).context(UnparseableExpiryTimestampSnafu { |
| 94 | + annotation: k, |
| 95 | + value: v, |
| 96 | + }) |
| 97 | + }) |
| 98 | + .min_by_key(|res| { |
| 99 | + // Prefer propagating errors over successful cases |
| 100 | + (res.is_ok(), res.as_ref().ok().cloned()) |
| 101 | + }) |
| 102 | + .transpose()?; |
| 103 | + |
| 104 | + let now = DateTime::<FixedOffset>::from(Utc::now()); |
| 105 | + let time_until_pod_expires = pod_expires_at.map(|expires_at| (expires_at - now).to_std()); |
| 106 | + match time_until_pod_expires { |
| 107 | + Some(Err(_has_already_expired)) => { |
| 108 | + let pods = ctx |
| 109 | + .get_ref() |
| 110 | + .client |
| 111 | + .get_api::<Pod>(pod.metadata.namespace.as_deref()); |
| 112 | + pods.evict( |
| 113 | + pod.metadata.name.as_deref().context(PodHasNoNameSnafu)?, |
| 114 | + &EvictParams::default(), |
| 115 | + ) |
| 116 | + .await |
| 117 | + .context(EvictPodSnafu)?; |
| 118 | + Ok(Action::await_change()) |
| 119 | + } |
| 120 | + Some(Ok(time_until_pod_expires)) => Ok(Action::requeue(time_until_pod_expires)), |
| 121 | + None => Ok(Action::await_change()), |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +fn error_policy(_error: &Error, _ctx: Context<Ctx>) -> Action { |
| 126 | + Action::requeue(Duration::from_secs(5)) |
| 127 | +} |
0 commit comments