From 33396b003efadfdf0806e448321ae2fb08260c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20M=C3=BCller?= Date: Wed, 25 Nov 2026 11:35:50 +0100 Subject: [PATCH 1/3] feat: simplified content digest for restart controller --- CHANGELOG.md | 11 + Cargo.lock | 3 + Cargo.nix | 12 + Cargo.toml | 3 + .../commons-operator/templates/roles.yaml | 41 ++- .../commons-operator/pages/restarter.adoc | 20 +- rust/operator-binary/Cargo.toml | 3 + rust/operator-binary/src/main.rs | 5 +- .../src/restart_controller/content_digest.rs | 328 ++++++++++++++++++ .../src/restart_controller/digest_key.rs | 181 ++++++++++ .../src/restart_controller/mod.rs | 2 + .../src/restart_controller/statefulset.rs | 213 +++++++++--- .../src/webhooks/restarter_mutate_sts.rs | 15 +- .../03-assert.yaml | 13 + .../03-content.yaml | 39 +++ .../04-assert.yaml | 6 + .../04-metadata-only-write.yaml | 6 + .../05-assert.yaml | 6 + .../05-content-change.yaml | 7 + .../06-upgrade-config.yaml | 10 + .../07-assert.yaml | 21 ++ .../07-upgrade-statefulset.yaml | 42 +++ .../08-assert.yaml | 6 + .../08-first-metadata-only-write.yaml | 8 + .../09-assert.yaml | 6 + .../09-second-metadata-only-write.yaml | 6 + 26 files changed, 959 insertions(+), 54 deletions(-) create mode 100644 rust/operator-binary/src/restart_controller/content_digest.rs create mode 100644 rust/operator-binary/src/restart_controller/digest_key.rs create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/03-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/03-content.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/04-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/04-metadata-only-write.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/05-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/05-content-change.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/06-upgrade-config.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/07-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/07-upgrade-statefulset.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/08-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/08-first-metadata-only-write.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/09-assert.yaml create mode 100644 tests/templates/kuttl/restarter-no-unneeded-restart/09-second-metadata-only-write.yaml diff --git a/CHANGELOG.md b/CHANGELOG.md index 449e610c..7b43e7b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Changed + +- The restarter only restarts the Pods of a StatefulSet when the content of a referenced ConfigMap + or Secret changes. Previously every write to such an object restarted them, including writes by + third parties that only touch its metadata. Upgrading does not restart any Pods by itself ([#449]). +- Extend Helm deployed RBAC permissions to get configmaps and secrets, required to digest their + content, and to create secrets in the operator namespace, required to store the key of these + digests ([#449]). + +[#449]: https://github.com/stackabletech/commons-operator/pull/449 + ## [26.11.0] - 2026-11-20 ## [26.11.0-rc1] - 2026-11-19 diff --git a/Cargo.lock b/Cargo.lock index dbc3ef5c..b195dd3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3108,10 +3108,13 @@ dependencies = [ "chrono", "clap", "futures 0.3.34", + "hmac", "http", "json-patch", + "rand 0.10.3", "serde", "serde_json", + "sha2", "snafu 0.9.2", "stackable-operator", "strum", diff --git a/Cargo.nix b/Cargo.nix index 9a258385..79c87ff6 100644 --- a/Cargo.nix +++ b/Cargo.nix @@ -10616,6 +10616,10 @@ rec { packageId = "futures 0.3.34"; features = [ "compat" ]; } + { + name = "hmac"; + packageId = "hmac"; + } { name = "http"; packageId = "http"; @@ -10624,6 +10628,10 @@ rec { name = "json-patch"; packageId = "json-patch"; } + { + name = "rand"; + packageId = "rand 0.10.3"; + } { name = "serde"; packageId = "serde"; @@ -10633,6 +10641,10 @@ rec { name = "serde_json"; packageId = "serde_json"; } + { + name = "sha2"; + packageId = "sha2"; + } { name = "snafu"; packageId = "snafu 0.9.2"; diff --git a/Cargo.toml b/Cargo.toml index 4d2cbc1a..99482ffa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,9 +21,12 @@ chrono = "0.4" clap = "4.6" futures = { version = "0.3", features = ["compat"] } http = "1.5" +hmac = "0.13" json-patch = "4.2" +rand = "0.10" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +sha2 = "0.11" snafu = "0.9" strum = { version = "0.28", features = ["derive"] } tokio = { version = "1.54", features = ["full"] } diff --git a/deploy/helm/commons-operator/templates/roles.yaml b/deploy/helm/commons-operator/templates/roles.yaml index 8ed0df31..90096c4f 100644 --- a/deploy/helm/commons-operator/templates/roles.yaml +++ b/deploy/helm/commons-operator/templates/roles.yaml @@ -7,14 +7,22 @@ metadata: {{- include "commons-operator.labels" . | nindent 4 }} rules: # Watch pods to detect expired restart annotations. - # Watch configmaps and secrets to trigger rolling restarts of referencing StatefulSets. - apiGroups: - "" resources: - pods + verbs: + - list + - watch + # Watch configmaps and secrets to trigger rolling restarts of referencing StatefulSets. + # Get them to digest their content, so that only content changes trigger rolling restarts. + - apiGroups: + - "" + resources: - configmaps - secrets verbs: + - get - list - watch # For automatic cluster domain detection. @@ -73,3 +81,34 @@ rules: # Required for startup condition - list - watch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "commons-operator.fullname" . }}-role + labels: + {{- include "commons-operator.labels" . | nindent 4 }} +rules: + # Create the Secret holding the key of the content digests on first use. + # Reading it is covered by the ClusterRole above. + - apiGroups: + - "" + resources: + - secrets + verbs: + - create +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "commons-operator.fullname" . }}-rolebinding + labels: + {{- include "commons-operator.labels" . | nindent 4 }} +subjects: + - kind: ServiceAccount + name: {{ include "commons-operator.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +roleRef: + kind: Role + name: {{ include "commons-operator.fullname" . }}-role + apiGroup: rbac.authorization.k8s.io diff --git a/docs/modules/commons-operator/pages/restarter.adoc b/docs/modules/commons-operator/pages/restarter.adoc index 36993b55..39253e77 100644 --- a/docs/modules/commons-operator/pages/restarter.adoc +++ b/docs/modules/commons-operator/pages/restarter.adoc @@ -61,13 +61,29 @@ spec: ... ---- +==== What counts as a change + +Only a change of the content (`data` and `binaryData` of a ConfigMap, `data` of a Secret) counts as a change. +Writes that leave the content as it is, for example writes by third parties that only touch the labels, annotations or managed fields of the object, do not restart the Pods. +If you want to restart the Pods without changing any content, use `kubectl rollout restart statefulset \{name\}`. + +To hash the content, the operator reads a referenced object whenever its resource version changes. +It only keeps the hash, not the content. +The hash is keyed with a random key stored in a Secret in the operator namespace and bound to the UID of the object, so the hash in the Pod template annotations reveals nothing about the content beyond whether it equals an earlier content of the same object. +The operator creates this key in the Secret `commons-operator-restarter-digest-key` in its own namespace when it first needs it. +Deleting that Secret, or the namespace, makes the operator create a new key on its next start, which changes every hash and therefore rolling-restarts every StatefulSet managed by the restarter once. + +Earlier releases counted every write to a referenced object as a change, and stored its resource version instead of a hash of its content. +Upgrading from such a release does not restart any Pods by itself: the operator keeps the value of every referenced object that has not been written since the Pods were last rolled. +The next write to such an object restarts the Pods once, as it would have before the upgrade, and from then on only content changes do. + ==== Pod template annotations To detect changes, the operator adds an annotation for every referenced ConfigMap and Secret to the Pod template of the StatefulSet. -Its key is `configmap.restarter.stackable.tech/\{name\}` or `secret.restarter.stackable.tech/\{name\}`, its value is the UID and resource version of the referenced object. +Its key is `configmap.restarter.stackable.tech/\{name\}` or `secret.restarter.stackable.tech/\{name\}`, its value is the UID of the referenced object, followed by a hash of its content (or by its resource version, as described above for upgrades). The value is `changes-ignored` instead if the object is excluded, either by the StatefulSet annotations described above or by the `restarter.stackable.tech/ignore` label described below. The value is also `changes-ignored` if the referenced object does not exist (yet), for example because the StatefulSet was created before a mounted Secret. -This is intended: once the object is created, the value changes to its UID and resource version (unless it is excluded), and the Pods are restarted to pick it up. +This is intended: once the object is created, the value changes as described above (unless it is excluded), and the Pods are restarted to pick it up. Kubernetes rolling-restarts the Pods whenever one of these values changes. These annotations are managed by the operator, there is no need to set them yourself. diff --git a/rust/operator-binary/Cargo.toml b/rust/operator-binary/Cargo.toml index 12c1a69b..931db83a 100644 --- a/rust/operator-binary/Cargo.toml +++ b/rust/operator-binary/Cargo.toml @@ -16,9 +16,12 @@ chrono.workspace = true clap.workspace = true http.workspace = true futures.workspace = true +hmac.workspace = true json-patch.workspace = true +rand.workspace = true serde.workspace = true serde_json.workspace = true +sha2.workspace = true snafu.workspace = true strum.workspace = true tokio.workspace = true diff --git a/rust/operator-binary/src/main.rs b/rust/operator-binary/src/main.rs index 0951e191..b512f5dd 100644 --- a/rust/operator-binary/src/main.rs +++ b/rust/operator-binary/src/main.rs @@ -110,7 +110,10 @@ async fn main() -> anyhow::Result<()> { ) .await?; - let (ctx, cm_store_tx, secret_store_tx) = create_context(client.clone()); + let (ctx, cm_store_tx, secret_store_tx) = create_context( + client.clone(), + operator_environment.operator_namespace.clone(), + ); let mut readiness_checks = HealthCheckRegistry::new(); let authentication_class_crd_check = readiness_checks.register(format!( diff --git a/rust/operator-binary/src/restart_controller/content_digest.rs b/rust/operator-binary/src/restart_controller/content_digest.rs new file mode 100644 index 00000000..b18c1e42 --- /dev/null +++ b/rust/operator-binary/src/restart_controller/content_digest.rs @@ -0,0 +1,328 @@ +//! Digests over the content of ConfigMaps and Secrets, which the StatefulSet restarter tracks to +//! detect changes. +//! +//! The restarter only watches the metadata of ConfigMaps and Secrets. The content of an object is +//! fetched on demand, only when a StatefulSet references it, and only once per resourceVersion: +//! the [`DigestCache`] keeps the digest, never the content. +//! +//! The digests are keyed with a [`DigestKey`] and bound to the uid of their object, so that anyone +//! who can read them in the Pod template annotations learns nothing about the content beyond +//! whether it changed. + +use std::{ + collections::HashMap, + future::Future, + sync::{Mutex, MutexGuard}, +}; + +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use stackable_operator::{ + k8s_openapi::{ + api::core::v1::{ConfigMap, Secret}, + apimachinery::pkg::apis::meta::v1::ObjectMeta, + }, + kube::{Resource, runtime::reflector::ObjectRef}, +}; + +use crate::restart_controller::digest_key::DigestKey; + +/// An object whose content can be digested. +pub trait ContentDigest: Resource { + /// Keyed digest over the parts of the object that a Pod can read, bound to the object's `uid`. + fn content_digest(&self, uid: &str, digest_key: &DigestKey) -> String; +} + +impl ContentDigest for ConfigMap { + fn content_digest(&self, uid: &str, digest_key: &DigestKey) -> String { + let mut mac = object_mac(uid, digest_key); + mac.update(b"configmap/data"); + for (key, value) in self.data.iter().flatten() { + update_entry(&mut mac, key, value.as_bytes()); + } + mac.update(b"configmap/binaryData"); + for (key, value) in self.binary_data.iter().flatten() { + update_entry(&mut mac, key, &value.0); + } + finish_digest(mac) + } +} + +impl ContentDigest for Secret { + fn content_digest(&self, uid: &str, digest_key: &DigestKey) -> String { + let mut mac = object_mac(uid, digest_key); + mac.update(b"secret/data"); + for (key, value) in self.data.iter().flatten() { + update_entry(&mut mac, key, &value.0); + } + finish_digest(mac) + } +} + +/// Returns a new MAC keyed with `digest_key` and bound to the object with the given `uid`. +/// +/// Binding to the uid keeps the digests of different objects apart, even with identical content. +/// Otherwise anyone able to create an object could have the operator digest guesses of another +/// object's content and compare the results. +fn object_mac(uid: &str, digest_key: &DigestKey) -> Hmac { + let mut mac = digest_key.mac(); + update_entry(&mut mac, "uid", uid.as_bytes()); + mac +} + +/// Adds one key/value pair to `mac`, length-prefixed. +fn update_entry(mac: &mut Hmac, key: &str, value: &[u8]) { + mac.update(&(key.len() as u64).to_be_bytes()); + mac.update(key.as_bytes()); + mac.update(&(value.len() as u64).to_be_bytes()); + mac.update(value); +} + +/// Truncates the digest to 128 bits and hex-encodes it. +fn finish_digest(mac: Hmac) -> String { + mac.finalize().into_bytes()[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// The content digest of one object at one resourceVersion. +/// +/// Deliberately holds no content, so no Secret data stays in memory after hashing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CachedDigest { + pub uid: String, + pub resource_version: String, + pub digest: String, +} + +/// Content digests of the objects of kind `K` referenced by StatefulSets. +/// +/// An entry is replaced when the uid or resourceVersion changes, and removed when a fetch finds +/// the object gone. Entries of objects deleted without a later fetch stay until the operator +/// restarts. They cannot be served for a recreated object, which has a new uid, and are only a +/// few hundred bytes each, so they are not tracked any further. +#[derive(Debug, Default)] +pub struct DigestCache { + entries: Mutex, CachedDigest>>, +} + +impl DigestCache { + /// Returns the digest of the object described by `metadata`, as seen by the metadata watch. + /// + /// The cached digest is used if it was computed for the same uid and resourceVersion, + /// otherwise the object is fetched by calling `fetch` with its name and namespace, and its + /// digest cached. Returns `None` if `metadata` lacks a name or namespace, or `fetch` does not + /// find the object. + /// + /// All calls on one cache must pass the same `digest_key`, as the cached digests are not keyed + /// by it. + pub async fn get_or_fetch<'a, E, Fut>( + &self, + metadata: &'a ObjectMeta, + digest_key: &DigestKey, + fetch: impl FnOnce(&'a str, &'a str) -> Fut, + ) -> Result, E> + where + Fut: Future, E>>, + { + let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { + return Ok(None); + }; + let cache_key = ObjectRef::::new(name).within(namespace); + + if let Some(cached) = self.lock().get(&cache_key) + && Some(&cached.uid) == metadata.uid.as_ref() + && Some(&cached.resource_version) == metadata.resource_version.as_ref() + { + return Ok(Some(cached.clone())); + } + + tracing::debug!( + k8s.object.namespace = namespace, + k8s.object.name = name, + "Fetching object to digest its content" + ); + let Some(object) = fetch(name, namespace).await? else { + self.lock().remove(&cache_key); + return Ok(None); + }; + let (Some(uid), Some(resource_version)) = ( + object.meta().uid.clone(), + object.meta().resource_version.clone(), + ) else { + return Ok(None); + }; + let cached = CachedDigest { + digest: object.content_digest(&uid, digest_key), + uid, + resource_version, + }; + self.lock().insert(cache_key, cached.clone()); + + Ok(Some(cached)) + } + + fn lock(&self) -> MutexGuard<'_, HashMap, CachedDigest>> { + self.entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use std::{cell::Cell, convert::Infallible}; + + use stackable_operator::k8s_openapi::{ + ByteString, apimachinery::pkg::apis::meta::v1::ManagedFieldsEntry, + }; + + use super::*; + + const TEST_KEY: DigestKey = DigestKey::new([42; 32]); + + const TEST_UID: &str = "f9dc0a8f-5f4b-4f52-9d0f-1a0ba1e0bd2c"; + + fn config_map(data: &[(&str, &str)]) -> ConfigMap { + ConfigMap { + data: Some( + data.iter() + .map(|(key, value)| ((*key).to_owned(), (*value).to_owned())) + .collect(), + ), + ..ConfigMap::default() + } + } + + fn metadata(uid: &str, resource_version: &str) -> ObjectMeta { + ObjectMeta { + name: Some("my-config".to_owned()), + namespace: Some("my-namespace".to_owned()), + uid: Some(uid.to_owned()), + resource_version: Some(resource_version.to_owned()), + ..ObjectMeta::default() + } + } + + fn stored(uid: &str, resource_version: &str, data: &[(&str, &str)]) -> ConfigMap { + ConfigMap { + metadata: metadata(uid, resource_version), + ..config_map(data) + } + } + + /// Changing the digest function rolling-restarts every StatefulSet managed by the restarter. + #[test] + fn digest_is_stable_across_releases() { + let binary_config_map = ConfigMap { + binary_data: Some([("foo".to_owned(), ByteString(b"bar".to_vec()))].into()), + ..ConfigMap::default() + }; + let secret = Secret { + data: Some([("foo".to_owned(), ByteString(b"bar".to_vec()))].into()), + ..Secret::default() + }; + + assert_eq!( + config_map(&[("foo", "bar")]).content_digest(TEST_UID, &TEST_KEY), + "aec6a1a9a372bda7f4b7a600d631186f" + ); + assert_eq!( + binary_config_map.content_digest(TEST_UID, &TEST_KEY), + "c2efb2422a076038e7e3affa23d7ffb1" + ); + assert_eq!( + secret.content_digest(TEST_UID, &TEST_KEY), + "646f7311f8401d03267d18cf5419ba32" + ); + } + + #[test] + fn digest_ignores_metadata() { + let mut changed = config_map(&[("foo", "bar")]); + changed.metadata = ObjectMeta { + resource_version: Some("12345".to_owned()), + labels: Some([("cost-center".to_owned(), "irrelevant".to_owned())].into()), + annotations: Some([("probe".to_owned(), "1".to_owned())].into()), + managed_fields: Some(vec![ManagedFieldsEntry { + manager: Some("third-party-controller".to_owned()), + ..ManagedFieldsEntry::default() + }]), + ..ObjectMeta::default() + }; + + assert_eq!( + config_map(&[("foo", "bar")]).content_digest(TEST_UID, &TEST_KEY), + changed.content_digest(TEST_UID, &TEST_KEY) + ); + } + + /// Each pair would collide without the key, the uid binding, the length prefixes or the field + /// prefixes. + #[test] + fn digest_distinguishes_content() { + let binary = ConfigMap { + binary_data: Some([("foo".to_owned(), ByteString(b"bar".to_vec()))].into()), + ..ConfigMap::default() + }; + let text = config_map(&[("foo", "bar")]); + + for (left, right) in [ + ( + text.content_digest(TEST_UID, &TEST_KEY), + text.content_digest(TEST_UID, &DigestKey::new([43; 32])), + ), + ( + text.content_digest(TEST_UID, &TEST_KEY), + text.content_digest("0b6f1a52-2d1e-4c43-8c55-5ad3d3a4e7f1", &TEST_KEY), + ), + ( + config_map(&[("ab", "c")]).content_digest(TEST_UID, &TEST_KEY), + config_map(&[("a", "bc")]).content_digest(TEST_UID, &TEST_KEY), + ), + ( + text.content_digest(TEST_UID, &TEST_KEY), + binary.content_digest(TEST_UID, &TEST_KEY), + ), + ] { + assert_ne!(left, right); + } + } + + /// Each step looks the object up by uid and resourceVersion, with the content a fetch returns + /// (`None` if the object is gone) and whether the cache has to fetch it. + #[tokio::test] + async fn cache_fetches_once_per_uid_and_resource_version() { + let cache = DigestCache::::default(); + + for (uid, resource_version, content, fetches) in [ + ("uid-1", "100", Some("bar"), true), + ("uid-1", "100", Some("bar"), false), + ("uid-1", "101", Some("baz"), true), + ("uid-2", "101", Some("qux"), true), + ("uid-2", "102", None, true), + ("uid-2", "101", Some("qux"), true), + ] { + let fetched = Cell::new(false); + let object = content.map(|content| stored(uid, resource_version, &[("foo", content)])); + let cached = cache + .get_or_fetch(&metadata(uid, resource_version), &TEST_KEY, |_, _| { + fetched.set(true); + std::future::ready(Ok::<_, Infallible>(object.clone())) + }) + .await + .expect("fetching should be infallible"); + + assert_eq!(fetched.get(), fetches); + assert_eq!( + cached, + object.map(|object| CachedDigest { + uid: uid.to_owned(), + resource_version: resource_version.to_owned(), + digest: object.content_digest(uid, &TEST_KEY), + }) + ); + } + } +} diff --git a/rust/operator-binary/src/restart_controller/digest_key.rs b/rust/operator-binary/src/restart_controller/digest_key.rs new file mode 100644 index 00000000..c0d92e8d --- /dev/null +++ b/rust/operator-binary/src/restart_controller/digest_key.rs @@ -0,0 +1,181 @@ +//! The secret key of the content digests tracked by the StatefulSet restarter. +//! +//! The digests end up in Pod template annotations, which anyone who can read a StatefulSet or its +//! Pods can see. Without a secret key, a digest would let them verify guesses of a Secret's +//! content offline. Each digest is also bound to the uid of its object (see +//! [`crate::restart_controller::content_digest`]), so that the operator cannot be used to verify +//! such guesses either. The key lives in a Secret in the operator namespace, so that it survives +//! operator restarts: a new key changes every digest and rolling-restarts every StatefulSet managed +//! by the restarter. + +use std::fmt; + +use hmac::{Hmac, KeyInit}; +use sha2::Sha256; +use snafu::{OptionExt, ResultExt, Snafu}; +use stackable_operator::{ + builder::meta::ObjectMetaBuilder, + client::Client, + k8s_openapi::{ByteString, api::core::v1::Secret}, + kvp::Label, +}; +use tokio::sync::OnceCell; + +/// Name of the Secret holding the [`DigestKey`]. +const SECRET_NAME: &str = "commons-operator-restarter-digest-key"; + +/// Entry of the Secret data holding the [`DigestKey`]. +const SECRET_DATA_KEY: &str = "key"; + +/// Length of the [`DigestKey`] in bytes. +const KEY_LENGTH: usize = 32; + +#[derive(Debug, Snafu)] +pub enum Error { + #[snafu(display("failed to load or create the digest key Secret {SECRET_NAME:?}"))] + LoadOrCreateSecret { + source: stackable_operator::client::Error, + }, + + #[snafu(display( + "the digest key Secret {SECRET_NAME:?} does not hold a {KEY_LENGTH} byte key in {SECRET_DATA_KEY:?}, delete it to generate a new key (this rolling-restarts every StatefulSet managed by the restarter)" + ))] + InvalidKey, +} + +/// The secret key of the content digests. +#[derive(Clone)] +pub struct DigestKey([u8; KEY_LENGTH]); + +impl DigestKey { + pub const fn new(bytes: [u8; KEY_LENGTH]) -> Self { + Self(bytes) + } + + /// Returns a new HMAC-SHA256 keyed with this key. + pub fn mac(&self) -> Hmac { + Hmac::new_from_slice(&self.0).expect("HMAC must accept keys of any length") + } + + fn generate() -> Self { + Self::new(rand::random()) + } + + fn from_secret(secret: &Secret) -> Result { + let bytes = secret + .data + .as_ref() + .and_then(|data| data.get(SECRET_DATA_KEY)) + .and_then(|value| <[u8; KEY_LENGTH]>::try_from(value.0.as_slice()).ok()) + .context(InvalidKeySnafu)?; + + Ok(Self::new(bytes)) + } + + fn to_secret(&self, namespace: &str) -> Secret { + Secret { + metadata: ObjectMetaBuilder::new() + .name(SECRET_NAME) + .namespace(namespace) + .with_label(Label::stackable_vendor()) + .build(), + data: Some([(SECRET_DATA_KEY.to_owned(), ByteString(self.0.to_vec()))].into()), + immutable: Some(true), + ..Secret::default() + } + } +} + +/// Redacted, so that the key never ends up in logs. +impl fmt::Debug for DigestKey { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("DigestKey()") + } +} + +/// Loads the [`DigestKey`] on first use, creating its Secret if it does not exist yet. +/// +/// Loading lazily keeps the operator startup independent of the Secret: if it cannot be loaded or +/// created, only the reconciles that need a digest fail, and they are retried. +pub struct DigestKeyStore { + client: Client, + namespace: String, + key: OnceCell, +} + +impl DigestKeyStore { + pub fn new(client: Client, namespace: String) -> Self { + Self { + client, + namespace, + key: OnceCell::new(), + } + } + + /// Returns the key, loading or creating its Secret in the operator namespace on first use. + /// + /// A failed attempt is not cached, the next call tries again. + pub async fn get(&self) -> Result<&DigestKey, Error> { + self.key + .get_or_try_init(|| async { + let secret = self + .client + .create_if_missing(&DigestKey::generate().to_secret(&self.namespace)) + .await + .context(LoadOrCreateSecretSnafu)?; + DigestKey::from_secret(&secret) + }) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn key_round_trips_through_its_secret() { + let key = DigestKey::new([7; KEY_LENGTH]); + let secret = key.to_secret("operator-namespace"); + + assert_eq!(secret.metadata.name.as_deref(), Some(SECRET_NAME)); + assert_eq!( + secret.metadata.namespace.as_deref(), + Some("operator-namespace") + ); + assert_eq!(secret.immutable, Some(true)); + assert_eq!( + DigestKey::from_secret(&secret) + .expect("a Secret built from a key should hold a valid key") + .0, + key.0 + ); + } + + #[test] + fn secret_without_valid_key_is_rejected() { + let short_key = Secret { + data: Some([(SECRET_DATA_KEY.to_owned(), ByteString(vec![7; 16]))].into()), + ..Secret::default() + }; + let wrong_entry = Secret { + data: Some([("other".to_owned(), ByteString(vec![7; KEY_LENGTH]))].into()), + ..Secret::default() + }; + + for secret in [Secret::default(), short_key, wrong_entry] { + assert!(matches!( + DigestKey::from_secret(&secret), + Err(Error::InvalidKey) + )); + } + } + + #[test] + fn debug_output_redacts_the_key() { + assert_eq!( + format!("{:?}", DigestKey::new([7; KEY_LENGTH])), + "DigestKey()" + ); + } +} diff --git a/rust/operator-binary/src/restart_controller/mod.rs b/rust/operator-binary/src/restart_controller/mod.rs index 37b64887..5f171a64 100644 --- a/rust/operator-binary/src/restart_controller/mod.rs +++ b/rust/operator-binary/src/restart_controller/mod.rs @@ -1,2 +1,4 @@ +pub mod content_digest; +pub mod digest_key; pub mod pod; pub mod statefulset; diff --git a/rust/operator-binary/src/restart_controller/statefulset.rs b/rust/operator-binary/src/restart_controller/statefulset.rs index ec4ce942..a67f49c4 100644 --- a/rust/operator-binary/src/restart_controller/statefulset.rs +++ b/rust/operator-binary/src/restart_controller/statefulset.rs @@ -1,19 +1,25 @@ use std::{ collections::{BTreeMap, BTreeSet}, + fmt::Debug, future::Future, sync::Arc, time::Duration, }; use futures::{Stream, StreamExt, TryStream, stream}; +use serde::de::DeserializeOwned; use serde_json::json; use snafu::{ResultExt, Snafu}; use stackable_operator::{ client::Client, constants::RESTART_CONTROLLER_ENABLED_LABEL, - k8s_openapi::api::{ - apps::v1::StatefulSet, - core::v1::{ConfigMap, EnvFromSource, EnvVar, PodSpec, Secret, Volume}, + k8s_openapi::{ + NamespaceResourceScope, + api::{ + apps::v1::StatefulSet, + core::v1::{ConfigMap, EnvFromSource, EnvVar, PodSpec, Secret, Volume}, + }, + apimachinery::pkg::apis::meta::v1::ObjectMeta, }, kube::{ self, Resource, ResourceExt, @@ -33,7 +39,13 @@ use stackable_operator::{ }; use strum::{EnumDiscriminants, IntoStaticStr}; -use crate::utils::delayed_init::{DelayedInit, InitDropped, Initializer}; +use crate::{ + restart_controller::{ + content_digest::{ContentDigest, DigestCache}, + digest_key::{self, DigestKeyStore}, + }, + utils::delayed_init::{DelayedInit, InitDropped, Initializer}, +}; const FULL_CONTROLLER_NAME: &str = "statefulset.restarter.commons.stackable.tech"; @@ -47,6 +59,9 @@ pub struct Ctx { client: Client, cms: DelayedInit>>, secrets: DelayedInit>>, + cm_digests: DigestCache, + secret_digests: DigestCache, + digest_key: DigestKeyStore, } #[derive(Snafu, Debug, EnumDiscriminants)] @@ -75,6 +90,15 @@ pub enum Error { source: KeyError, object_name: String, }, + + #[snafu(display("failed to fetch {obj_ref} to digest its content"))] + FetchContentFailed { + source: stackable_operator::client::Error, + obj_ref: Box>, + }, + + #[snafu(display("failed to load the key for content digests"))] + LoadDigestKey { source: digest_key::Error }, } impl ReconcilerError for Error { @@ -89,6 +113,8 @@ impl ReconcilerError for Error { Error::ConfigMapsUninitialized { .. } => None, Error::SecretsUninitialized { .. } => None, Error::InvalidAnnotationKey { .. } => None, + Error::FetchContentFailed { obj_ref, .. } => Some(*obj_ref.clone()), + Error::LoadDigestKey { .. } => None, } } } @@ -96,6 +122,7 @@ impl ReconcilerError for Error { #[allow(clippy::type_complexity)] pub fn create_context( client: Client, + operator_namespace: String, ) -> ( Arc, Initializer>>, @@ -104,9 +131,12 @@ pub fn create_context( let (cm_store_tx, cm_store_delayed) = DelayedInit::new(); let (secret_store_tx, secret_store_delayed) = DelayedInit::new(); let ctx = Arc::new(Ctx { - client, + client: client.clone(), cms: cm_store_delayed, secrets: secret_store_delayed, + cm_digests: DigestCache::default(), + secret_digests: DigestCache::default(), + digest_key: DigestKeyStore::new(client, operator_namespace), }); (ctx, cm_store_tx, secret_store_tx) @@ -276,6 +306,77 @@ fn annotation_key(prefix: &str, object_name: &str) -> Result { Ok(key.to_string()) } +/// Returns `previous_value` if it is the `uid/resourceVersion` value that releases before content +/// digests wrote for the object with the given `metadata`, i.e. the object has not been written +/// since the Pods were last rolled with that value. +/// +/// Keeping this value lets the operator upgrade from those releases without restarting any Pods. +/// The Pods are restarted on the next write to the object instead, as they would have been by +/// those releases, and from then on the annotation holds the content digest. Objects that are +/// never written keep the value indefinitely, so this has no planned removal: removing it would +/// cost exactly the restart it avoids. +/// +/// A digest never matches, as it is 32 hexadecimal characters, while resourceVersions written by +/// etcd are decimal numbers of at most 19 digits. +fn unchanged_resource_version_value( + metadata: &ObjectMeta, + previous_value: Option<&str>, +) -> Option { + let value = format!( + "{}/{}", + metadata.uid.as_deref()?, + metadata.resource_version.as_deref()? + ); + (Some(value.as_str()) == previous_value).then_some(value) +} + +/// Value of the Pod template annotation tracking `object`. +/// +/// `previous_value` is the value the Pod template annotation currently has, if any. This fetches +/// the object to digest its content, unless `digests` already holds the digest for its current +/// resourceVersion, or `previous_value` is still up to date, see +/// [`unchanged_resource_version_value`]. +/// +/// The value is `changes-ignored` if the object is `ignored` via the StatefulSet annotations, or +/// missing from the store (`None`) or the API, i.e. it doesn't exist (yet), e.g. because the +/// StatefulSet was created before it, or it has the label `restarter.stackable.tech/ignore=true` +/// (filtered out by the watcher). This is intended: once the object shows up, the value changes +/// to its digest (unless ignored via the StatefulSet annotations), which restarts the Pods so that +/// they pick it up. Leaving out the annotation instead would not avoid any restart, but cause +/// additional ones, e.g. when an object ignored via a StatefulSet annotation is created after the +/// StatefulSet. +async fn tracking_value( + ctx: &Ctx, + digests: &DigestCache, + object: Option<&PartialObjectMeta>, + ignored: bool, + previous_value: Option<&str>, +) -> Result +where + K: ContentDigest + Resource + Clone + Debug + DeserializeOwned, +{ + let changes_ignored = || "changes-ignored".to_owned(); + let Some(object) = object.filter(|_| !ignored) else { + return Ok(changes_ignored()); + }; + let metadata = &object.metadata; + if let Some(value) = unchanged_resource_version_value(metadata, previous_value) { + return Ok(value); + } + let digest_key = ctx.digest_key.get().await.context(LoadDigestKeySnafu)?; + let cached = digests + .get_or_fetch(metadata, digest_key, |name, namespace| { + ctx.client.get_opt::(name, namespace) + }) + .await + .with_context(|_| FetchContentFailedSnafu { + obj_ref: ObjectRef::from_obj(object).erase(), + })?; + Ok(cached.map_or_else(changes_ignored, |cached| { + format!("{}/{}", cached.uid, cached.digest) + })) +} + pub async fn get_updated_restarter_annotations( sts: &StatefulSet, ctx: Arc, @@ -283,6 +384,11 @@ pub async fn get_updated_restarter_annotations( let ns = sts.metadata.namespace.as_deref().expect( "A StatefulSet observed by a reflector (so send by Kubernetes) always has a namespace set", ); + let previous_annotations = sts + .spec + .as_ref() + .and_then(|sts_spec| sts_spec.template.metadata.as_ref()) + .and_then(|metadata| metadata.annotations.as_ref()); let mut annotations = BTreeMap::::new(); let pod_specs = sts @@ -330,29 +436,16 @@ pub async fn get_updated_restarter_annotations( }) .collect::>(); for cm_ref in cm_refs { - let cm_name = &cm_ref.name; - let cm = cms.get(&cm_ref); - - // It is intended that "changes-ignored" is also used if the ConfigMap is not in the store, - // i.e. it doesn't exist (yet), e.g. because the StatefulSet was created before the - // ConfigMap, or it has the label `restarter.stackable.tech/ignore=true` (filtered out by the - // watcher). Once the ConfigMap shows up, the value changes to its uid/resourceVersion - // (unless ignored via the StatefulSet annotations), which restarts the Pods so that they - // pick it up. - // Leaving out the annotation instead would not avoid any restart, but cause additional - // ones, e.g. when an object ignored via a StatefulSet annotation is created after the - // StatefulSet. - let value = if let Some(cm) = cm - && let Some(uid) = &cm.metadata.uid - && let Some(resource_version) = &cm.metadata.resource_version - && !ignored_cms.contains(cm_name) - { - format!("{uid}/{resource_version}",) - } else { - "changes-ignored".to_owned() - }; - - annotations.insert(annotation_key(CONFIGMAP_ANNOTATION_PREFIX, cm_name)?, value); + let key = annotation_key(CONFIGMAP_ANNOTATION_PREFIX, &cm_ref.name)?; + let value = tracking_value( + &ctx, + &ctx.cm_digests, + cms.get(&cm_ref).as_deref(), + ignored_cms.contains(&cm_ref.name), + previous_annotations.and_then(|previous| previous.get(&key).map(String::as_str)), + ) + .await?; + annotations.insert(key, value); } let secret_refs = pod_specs @@ -391,24 +484,16 @@ pub async fn get_updated_restarter_annotations( .map(|x| x.1) .collect::>(); for secret_ref in secret_refs { - let secret_name = &secret_ref.name; - let secret = secrets.get(&secret_ref); - - // Same as for ConfigMaps above, "changes-ignored" is intended for Secrets not in the store. - let value = if let Some(secret) = secret - && let Some(uid) = &secret.metadata.uid - && let Some(resource_version) = &secret.metadata.resource_version - && !ignored_secrets.contains(secret_name) - { - format!("{uid}/{resource_version}",) - } else { - "changes-ignored".to_owned() - }; - - annotations.insert( - annotation_key(SECRET_ANNOTATION_PREFIX, secret_name)?, - value, - ); + let key = annotation_key(SECRET_ANNOTATION_PREFIX, &secret_ref.name)?; + let value = tracking_value( + &ctx, + &ctx.secret_digests, + secrets.get(&secret_ref).as_deref(), + ignored_secrets.contains(&secret_ref.name), + previous_annotations.and_then(|previous| previous.get(&key).map(String::as_str)), + ) + .await?; + annotations.insert(key, value); } Ok(annotations) @@ -499,4 +584,40 @@ mod tests { "secret.restarter.stackable.tech/hiverest-owner-user.stackable-postgres-cluster.credent-8221aa71" ); } + + #[test] + fn resource_version_value_is_kept_until_the_object_is_written() { + let uid = "f9dc0a8f-5f4b-4f52-9d0f-1a0ba1e0bd2c"; + let metadata = ObjectMeta { + uid: Some(uid.to_owned()), + resource_version: Some("12345".to_owned()), + ..ObjectMeta::default() + }; + + for (previous_value, expected) in [ + (Some(format!("{uid}/12345")), Some(format!("{uid}/12345"))), + (Some(format!("{uid}/12344")), None), + ( + Some("0a1b2c3d-0000-0000-0000-000000000000/12345".to_owned()), + None, + ), + ( + Some(format!("{uid}/0123456789abcdef0123456789abcdef")), + None, + ), + (Some("changes-ignored".to_owned()), None), + (None, None), + ] { + assert_eq!( + unchanged_resource_version_value(&metadata, previous_value.as_deref()), + expected, + "previous value {previous_value:?}" + ); + } + + assert_eq!( + unchanged_resource_version_value(&ObjectMeta::default(), Some(&format!("{uid}/12345"))), + None + ); + } } diff --git a/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs b/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs index afa08303..2db9daa5 100644 --- a/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs +++ b/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs @@ -24,7 +24,7 @@ use stackable_operator::{ use crate::{ FIELD_MANAGER, OPERATOR_NAME, - restart_controller::statefulset::{Ctx, get_updated_restarter_annotations}, + restart_controller::statefulset::{Ctx, Error, get_updated_restarter_annotations}, }; pub fn create_webhook( @@ -95,9 +95,9 @@ fn get_sts_restarter_mutating_webhook_configuration() -> MutatingWebhookConfigur // > Webhooks typically operate only on the content of the AdmissionReview sent to them. // > Some webhooks, however, make out-of-band changes as part of processing admission requests. // - // We read in the state of the world using the ConfigMap and Secret store. - // So, technically our outcome depends on external factors, *but* this webhook is not - // creating any external objects, so from our understanding it's side-effect free. + // We read in the state of the world using the ConfigMap and Secret store and by + // fetching the referenced objects. The only object we may create is the idempotent + // digest key Secret (see `DigestKeyStore`), so we consider this side-effect free. side_effects: "None".to_owned(), ..Default::default() }]), @@ -136,6 +136,13 @@ async fn add_sts_restarter_annotations_handler( let annotations = match get_updated_restarter_annotations(sts, ctx).await { Ok(annotations) => annotations, + Err(err @ (Error::FetchContentFailed { .. } | Error::LoadDigestKey { .. })) => { + tracing::warn!( + error = &err as &dyn std::error::Error, + "Admitting StatefulSet without restarter annotations, the controller adds them later" + ); + return AdmissionResponse::from(&request); + } Err(err) => { return AdmissionResponse::invalid(format!( "failed to get updated restarted annotations: {err:#}" diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/03-assert.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/03-assert.yaml new file mode 100644 index 00000000..77d65dd5 --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/03-assert.yaml @@ -0,0 +1,13 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +timeout: 300 +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: content + generation: 1 +status: + readyReplicas: 2 + replicas: 2 diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/03-content.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/03-content.yaml new file mode 100644 index 00000000..c607a6da --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/03-content.yaml @@ -0,0 +1,39 @@ +--- +# Only content changes of the ConfigMap restart the Pods, writes that only touch its metadata do +# not. + +apiVersion: v1 +kind: ConfigMap +metadata: + name: content-config +data: + foo: bar +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: content + labels: + restarter.stackable.tech/enabled: "true" +spec: + selector: + matchLabels: + app: content + serviceName: content + replicas: 2 + template: + metadata: + labels: + app: content + spec: + terminationGracePeriodSeconds: 1 + containers: + - name: nginx + image: nginxinc/nginx-unprivileged:1.27 + volumeMounts: + - name: config + mountPath: /config + volumes: + - name: config + configMap: + name: content-config diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/04-assert.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/04-assert.yaml new file mode 100644 index 00000000..03d3560c --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/04-assert.yaml @@ -0,0 +1,6 @@ +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: content + generation: 1 diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/04-metadata-only-write.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/04-metadata-only-write.yaml new file mode 100644 index 00000000..b88ff638 --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/04-metadata-only-write.yaml @@ -0,0 +1,6 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - script: kubectl label configmap content-config --namespace $NAMESPACE third-party=true + - script: sleep 15 diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/05-assert.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/05-assert.yaml new file mode 100644 index 00000000..70843e5d --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/05-assert.yaml @@ -0,0 +1,6 @@ +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: content + generation: 2 diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/05-content-change.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/05-content-change.yaml new file mode 100644 index 00000000..9e598a02 --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/05-content-change.yaml @@ -0,0 +1,7 @@ +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: content-config +data: + foo: baz diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/06-upgrade-config.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/06-upgrade-config.yaml new file mode 100644 index 00000000..a498f989 --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/06-upgrade-config.yaml @@ -0,0 +1,10 @@ +--- +# Simulates an upgrade from a release that tracked the resourceVersion instead of the content: +# the StatefulSet in the next step is created with the annotation value such a release wrote. + +apiVersion: v1 +kind: ConfigMap +metadata: + name: upgrade-config +data: + foo: bar diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/07-assert.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/07-assert.yaml new file mode 100644 index 00000000..d61f32d7 --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/07-assert.yaml @@ -0,0 +1,21 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +timeout: 300 +commands: + - script: | + sleep 15 + LEGACY_VALUE="$(kubectl get configmap upgrade-config --namespace "$NAMESPACE" \ + --output 'jsonpath={.metadata.uid}/{.metadata.resourceVersion}')" + ACTUAL_VALUE="$(kubectl get statefulset upgrade --namespace "$NAMESPACE" \ + --output 'jsonpath={.spec.template.metadata.annotations.configmap\.restarter\.stackable\.tech/upgrade-config}')" + test "$LEGACY_VALUE" = "$ACTUAL_VALUE" +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: upgrade + generation: 1 +status: + readyReplicas: 2 + replicas: 2 diff --git a/tests/templates/kuttl/restarter-no-unneeded-restart/07-upgrade-statefulset.yaml b/tests/templates/kuttl/restarter-no-unneeded-restart/07-upgrade-statefulset.yaml new file mode 100644 index 00000000..268f909c --- /dev/null +++ b/tests/templates/kuttl/restarter-no-unneeded-restart/07-upgrade-statefulset.yaml @@ -0,0 +1,42 @@ +--- +# The operator keeps the annotation value as long as the ConfigMap is not written, so the upgrade +# itself does not restart the Pods. +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - script: | + LEGACY_VALUE="$(kubectl get configmap upgrade-config --namespace "$NAMESPACE" \ + --output 'jsonpath={.metadata.uid}/{.metadata.resourceVersion}')" + kubectl apply --namespace "$NAMESPACE" --filename - < Date: Wed, 25 Nov 2026 12:51:53 +0100 Subject: [PATCH 2/3] refactor: several simplifications --- CHANGELOG.md | 15 +- .../commons-operator/templates/roles.yaml | 15 +- .../commons-operator/pages/restarter.adoc | 5 +- rust/operator-binary/src/main.rs | 16 +- .../src/restart_controller/content_digest.rs | 254 ++++++-------- .../src/restart_controller/digest_key.rs | 45 +-- .../src/restart_controller/statefulset.rs | 314 ++++++++++-------- .../operator-binary/src/utils/delayed_init.rs | 212 ------------ rust/operator-binary/src/utils/mod.rs | 1 - .../src/webhooks/restarter_mutate_sts.rs | 15 +- 10 files changed, 318 insertions(+), 574 deletions(-) delete mode 100644 rust/operator-binary/src/utils/delayed_init.rs delete mode 100644 rust/operator-binary/src/utils/mod.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b43e7b9..8d723760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,17 @@ All notable changes to this project will be documented in this file. - The restarter only restarts the Pods of a StatefulSet when the content of a referenced ConfigMap or Secret changes. Previously every write to such an object restarted them, including writes by - third parties that only touch its metadata. Upgrading does not restart any Pods by itself ([#449]). -- Extend Helm deployed RBAC permissions to get configmaps and secrets, required to digest their - content, and to create secrets in the operator namespace, required to store the key of these - digests ([#449]). + third parties that only touch its metadata. Upgrading does not restart any Pods by itself ([#481]). +- Extend Helm deployed RBAC permissions to get and create secrets in the operator namespace, + required to store the key of the content digests ([#481]). -[#449]: https://github.com/stackabletech/commons-operator/pull/449 +### Fixed + +- The restarter no longer rolling-restarts StatefulSets twice when the operator starts. Previously + a StatefulSet reconciled before the initial list of ConfigMaps and Secrets was complete saw every + referenced object as missing ([#481]). + +[#481]: https://github.com/stackabletech/commons-operator/pull/481 ## [26.11.0] - 2026-11-20 diff --git a/deploy/helm/commons-operator/templates/roles.yaml b/deploy/helm/commons-operator/templates/roles.yaml index 90096c4f..0dc228e3 100644 --- a/deploy/helm/commons-operator/templates/roles.yaml +++ b/deploy/helm/commons-operator/templates/roles.yaml @@ -7,22 +7,14 @@ metadata: {{- include "commons-operator.labels" . | nindent 4 }} rules: # Watch pods to detect expired restart annotations. - - apiGroups: - - "" - resources: - - pods - verbs: - - list - - watch # Watch configmaps and secrets to trigger rolling restarts of referencing StatefulSets. - # Get them to digest their content, so that only content changes trigger rolling restarts. - apiGroups: - "" resources: + - pods - configmaps - secrets verbs: - - get - list - watch # For automatic cluster domain detection. @@ -89,13 +81,14 @@ metadata: labels: {{- include "commons-operator.labels" . | nindent 4 }} rules: - # Create the Secret holding the key of the content digests on first use. - # Reading it is covered by the ClusterRole above. + # Load, or create on first start, the Secret holding the key of the content digests tracked by + # the StatefulSet restarter. - apiGroups: - "" resources: - secrets verbs: + - get - create --- apiVersion: rbac.authorization.k8s.io/v1 diff --git a/docs/modules/commons-operator/pages/restarter.adoc b/docs/modules/commons-operator/pages/restarter.adoc index 39253e77..27a6c3a6 100644 --- a/docs/modules/commons-operator/pages/restarter.adoc +++ b/docs/modules/commons-operator/pages/restarter.adoc @@ -67,10 +67,11 @@ Only a change of the content (`data` and `binaryData` of a ConfigMap, `data` of Writes that leave the content as it is, for example writes by third parties that only touch the labels, annotations or managed fields of the object, do not restart the Pods. If you want to restart the Pods without changing any content, use `kubectl rollout restart statefulset \{name\}`. -To hash the content, the operator reads a referenced object whenever its resource version changes. +To hash the content, the operator watches ConfigMaps and Secrets including their content. It only keeps the hash, not the content. +Of the metadata, it only keeps the name, namespace, UID and resource version, as other metadata can hold the content too, for example the `kubectl.kubernetes.io/last-applied-configuration` annotation of objects created with `kubectl apply`. The hash is keyed with a random key stored in a Secret in the operator namespace and bound to the UID of the object, so the hash in the Pod template annotations reveals nothing about the content beyond whether it equals an earlier content of the same object. -The operator creates this key in the Secret `commons-operator-restarter-digest-key` in its own namespace when it first needs it. +The operator creates this key in the Secret `commons-operator-restarter-digest-key` in its own namespace on its first start, and does not start if it cannot load or create it. Deleting that Secret, or the namespace, makes the operator create a new key on its next start, which changes every hash and therefore rolling-restarts every StatefulSet managed by the restarter once. Earlier releases counted every write to a referenced object as a change, and stored its resource version instead of a hash of its content. diff --git a/rust/operator-binary/src/main.rs b/rust/operator-binary/src/main.rs index b512f5dd..4250cd61 100644 --- a/rust/operator-binary/src/main.rs +++ b/rust/operator-binary/src/main.rs @@ -24,7 +24,6 @@ use stackable_operator::{ use webhooks::create_webhook_server; mod restart_controller; -mod utils; mod webhooks; mod built_info { @@ -110,10 +109,12 @@ async fn main() -> anyhow::Result<()> { ) .await?; - let (ctx, cm_store_tx, secret_store_tx) = create_context( - client.clone(), - operator_environment.operator_namespace.clone(), - ); + let digest_key = restart_controller::digest_key::load_or_create( + &client, + &operator_environment.operator_namespace, + ) + .await?; + let (ctx, cm_store, secret_store) = create_context(client.clone()); let mut readiness_checks = HealthCheckRegistry::new(); let authentication_class_crd_check = readiness_checks.register(format!( @@ -144,8 +145,9 @@ async fn main() -> anyhow::Result<()> { let sts_restart_controller = restart_controller::statefulset::start( ctx, - cm_store_tx, - secret_store_tx, + cm_store, + secret_store, + digest_key, &watch_namespace, sigterm_watcher.handle(), ) diff --git a/rust/operator-binary/src/restart_controller/content_digest.rs b/rust/operator-binary/src/restart_controller/content_digest.rs index b18c1e42..63f36666 100644 --- a/rust/operator-binary/src/restart_controller/content_digest.rs +++ b/rust/operator-binary/src/restart_controller/content_digest.rs @@ -1,20 +1,15 @@ //! Digests over the content of ConfigMaps and Secrets, which the StatefulSet restarter tracks to //! detect changes. //! -//! The restarter only watches the metadata of ConfigMaps and Secrets. The content of an object is -//! fetched on demand, only when a StatefulSet references it, and only once per resourceVersion: -//! the [`DigestCache`] keeps the digest, never the content. +//! The restarter watches ConfigMaps and Secrets and replaces their content by its digest before +//! storing them (see [`replace_content_by_digest`]). It also drops all metadata it does not need, +//! as metadata can hold the content too, e.g. the `kubectl.kubernetes.io/last-applied-configuration` +//! annotation of objects created with `kubectl apply`. So its stores hold no content. //! //! The digests are keyed with a [`DigestKey`] and bound to the uid of their object, so that anyone //! who can read them in the Pod template annotations learns nothing about the content beyond //! whether it changed. -use std::{ - collections::HashMap, - future::Future, - sync::{Mutex, MutexGuard}, -}; - use hmac::{Hmac, Mac}; use sha2::Sha256; use stackable_operator::{ @@ -22,15 +17,24 @@ use stackable_operator::{ api::core::v1::{ConfigMap, Secret}, apimachinery::pkg::apis::meta::v1::ObjectMeta, }, - kube::{Resource, runtime::reflector::ObjectRef}, + kube::Resource, }; use crate::restart_controller::digest_key::DigestKey; +/// Annotation holding the content digest of a ConfigMap or Secret in the restarter's stores. +/// +/// Only set in memory by [`replace_content_by_digest`], which overwrites any value the object +/// already has. It is never written to the API server. +const CONTENT_DIGEST_ANNOTATION: &str = "restarter.stackable.tech/content-digest"; + /// An object whose content can be digested. pub trait ContentDigest: Resource { /// Keyed digest over the parts of the object that a Pod can read, bound to the object's `uid`. fn content_digest(&self, uid: &str, digest_key: &DigestKey) -> String; + + /// Removes the parts of the object that [`ContentDigest::content_digest`] covers. + fn clear_content(&mut self); } impl ContentDigest for ConfigMap { @@ -46,6 +50,11 @@ impl ContentDigest for ConfigMap { } finish_digest(mac) } + + fn clear_content(&mut self) { + self.data = None; + self.binary_data = None; + } } impl ContentDigest for Secret { @@ -57,6 +66,46 @@ impl ContentDigest for Secret { } finish_digest(mac) } + + fn clear_content(&mut self) { + self.data = None; + self.string_data = None; + } +} + +/// Replaces the content of `object` by its digest, stored in the [`CONTENT_DIGEST_ANNOTATION`], so +/// that no content stays in memory. +/// +/// Of the metadata, only the name, namespace, uid and resourceVersion are kept, which is all the +/// restarter needs. All labels, managed fields and other annotations are dropped, as they can +/// hold the content as well. +/// +/// Without a uid, which every object from the API server has, no digest is stored. +pub fn replace_content_by_digest(object: &mut K, digest_key: &DigestKey) { + let digest = object + .meta() + .uid + .as_deref() + .map(|uid| object.content_digest(uid, digest_key)); + object.clear_content(); + let metadata = std::mem::take(object.meta_mut()); + *object.meta_mut() = ObjectMeta { + name: metadata.name, + namespace: metadata.namespace, + uid: metadata.uid, + resource_version: metadata.resource_version, + annotations: digest.map(|digest| [(CONTENT_DIGEST_ANNOTATION.to_owned(), digest)].into()), + ..ObjectMeta::default() + }; +} + +/// Returns the digest that [`replace_content_by_digest`] stored in `metadata`, if any. +pub fn stored_digest(metadata: &ObjectMeta) -> Option<&str> { + metadata + .annotations + .as_ref()? + .get(CONTENT_DIGEST_ANNOTATION) + .map(String::as_str) } /// Returns a new MAC keyed with `digest_key` and bound to the object with the given `uid`. @@ -86,94 +135,8 @@ fn finish_digest(mac: Hmac) -> String { .collect() } -/// The content digest of one object at one resourceVersion. -/// -/// Deliberately holds no content, so no Secret data stays in memory after hashing. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CachedDigest { - pub uid: String, - pub resource_version: String, - pub digest: String, -} - -/// Content digests of the objects of kind `K` referenced by StatefulSets. -/// -/// An entry is replaced when the uid or resourceVersion changes, and removed when a fetch finds -/// the object gone. Entries of objects deleted without a later fetch stay until the operator -/// restarts. They cannot be served for a recreated object, which has a new uid, and are only a -/// few hundred bytes each, so they are not tracked any further. -#[derive(Debug, Default)] -pub struct DigestCache { - entries: Mutex, CachedDigest>>, -} - -impl DigestCache { - /// Returns the digest of the object described by `metadata`, as seen by the metadata watch. - /// - /// The cached digest is used if it was computed for the same uid and resourceVersion, - /// otherwise the object is fetched by calling `fetch` with its name and namespace, and its - /// digest cached. Returns `None` if `metadata` lacks a name or namespace, or `fetch` does not - /// find the object. - /// - /// All calls on one cache must pass the same `digest_key`, as the cached digests are not keyed - /// by it. - pub async fn get_or_fetch<'a, E, Fut>( - &self, - metadata: &'a ObjectMeta, - digest_key: &DigestKey, - fetch: impl FnOnce(&'a str, &'a str) -> Fut, - ) -> Result, E> - where - Fut: Future, E>>, - { - let (Some(namespace), Some(name)) = (&metadata.namespace, &metadata.name) else { - return Ok(None); - }; - let cache_key = ObjectRef::::new(name).within(namespace); - - if let Some(cached) = self.lock().get(&cache_key) - && Some(&cached.uid) == metadata.uid.as_ref() - && Some(&cached.resource_version) == metadata.resource_version.as_ref() - { - return Ok(Some(cached.clone())); - } - - tracing::debug!( - k8s.object.namespace = namespace, - k8s.object.name = name, - "Fetching object to digest its content" - ); - let Some(object) = fetch(name, namespace).await? else { - self.lock().remove(&cache_key); - return Ok(None); - }; - let (Some(uid), Some(resource_version)) = ( - object.meta().uid.clone(), - object.meta().resource_version.clone(), - ) else { - return Ok(None); - }; - let cached = CachedDigest { - digest: object.content_digest(&uid, digest_key), - uid, - resource_version, - }; - self.lock().insert(cache_key, cached.clone()); - - Ok(Some(cached)) - } - - fn lock(&self) -> MutexGuard<'_, HashMap, CachedDigest>> { - self.entries - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - } -} - #[cfg(test)] mod tests { - use std::{cell::Cell, convert::Infallible}; - use stackable_operator::k8s_openapi::{ ByteString, apimachinery::pkg::apis::meta::v1::ManagedFieldsEntry, }; @@ -195,23 +158,6 @@ mod tests { } } - fn metadata(uid: &str, resource_version: &str) -> ObjectMeta { - ObjectMeta { - name: Some("my-config".to_owned()), - namespace: Some("my-namespace".to_owned()), - uid: Some(uid.to_owned()), - resource_version: Some(resource_version.to_owned()), - ..ObjectMeta::default() - } - } - - fn stored(uid: &str, resource_version: &str, data: &[(&str, &str)]) -> ConfigMap { - ConfigMap { - metadata: metadata(uid, resource_version), - ..config_map(data) - } - } - /// Changing the digest function rolling-restarts every StatefulSet managed by the restarter. #[test] fn digest_is_stable_across_releases() { @@ -290,39 +236,57 @@ mod tests { } } - /// Each step looks the object up by uid and resourceVersion, with the content a fetch returns - /// (`None` if the object is gone) and whether the cache has to fetch it. - #[tokio::test] - async fn cache_fetches_once_per_uid_and_resource_version() { - let cache = DigestCache::::default(); + #[test] + fn content_is_replaced_by_its_digest() { + let annotations = [ + (CONTENT_DIGEST_ANNOTATION.to_owned(), "spoofed".to_owned()), + ( + "kubectl.kubernetes.io/last-applied-configuration".to_owned(), + r#"{"data":{"foo":"bar"}}"#.to_owned(), + ), + ]; + let mut with_uid = ConfigMap { + metadata: ObjectMeta { + name: Some("config".to_owned()), + namespace: Some("default".to_owned()), + uid: Some(TEST_UID.to_owned()), + resource_version: Some("12345".to_owned()), + labels: Some([("foo".to_owned(), "bar".to_owned())].into()), + annotations: Some(annotations.clone().into()), + managed_fields: Some(vec![ManagedFieldsEntry::default()]), + ..ObjectMeta::default() + }, + binary_data: Some([("foo".to_owned(), ByteString(b"bar".to_vec()))].into()), + ..config_map(&[("foo", "bar")]) + }; + let mut without_uid = ConfigMap { + metadata: ObjectMeta { + annotations: Some(annotations.into()), + ..ObjectMeta::default() + }, + ..config_map(&[("foo", "bar")]) + }; + let expected_digest = with_uid.content_digest(TEST_UID, &TEST_KEY); - for (uid, resource_version, content, fetches) in [ - ("uid-1", "100", Some("bar"), true), - ("uid-1", "100", Some("bar"), false), - ("uid-1", "101", Some("baz"), true), - ("uid-2", "101", Some("qux"), true), - ("uid-2", "102", None, true), - ("uid-2", "101", Some("qux"), true), - ] { - let fetched = Cell::new(false); - let object = content.map(|content| stored(uid, resource_version, &[("foo", content)])); - let cached = cache - .get_or_fetch(&metadata(uid, resource_version), &TEST_KEY, |_, _| { - fetched.set(true); - std::future::ready(Ok::<_, Infallible>(object.clone())) - }) - .await - .expect("fetching should be infallible"); + replace_content_by_digest(&mut with_uid, &TEST_KEY); + replace_content_by_digest(&mut without_uid, &TEST_KEY); - assert_eq!(fetched.get(), fetches); - assert_eq!( - cached, - object.map(|object| CachedDigest { - uid: uid.to_owned(), - resource_version: resource_version.to_owned(), - digest: object.content_digest(uid, &TEST_KEY), - }) - ); - } + assert_eq!( + with_uid, + ConfigMap { + metadata: ObjectMeta { + name: Some("config".to_owned()), + namespace: Some("default".to_owned()), + uid: Some(TEST_UID.to_owned()), + resource_version: Some("12345".to_owned()), + annotations: Some( + [(CONTENT_DIGEST_ANNOTATION.to_owned(), expected_digest)].into() + ), + ..ObjectMeta::default() + }, + ..ConfigMap::default() + } + ); + assert_eq!(without_uid, ConfigMap::default()); } } diff --git a/rust/operator-binary/src/restart_controller/digest_key.rs b/rust/operator-binary/src/restart_controller/digest_key.rs index c0d92e8d..c89831de 100644 --- a/rust/operator-binary/src/restart_controller/digest_key.rs +++ b/rust/operator-binary/src/restart_controller/digest_key.rs @@ -6,7 +6,7 @@ //! [`crate::restart_controller::content_digest`]), so that the operator cannot be used to verify //! such guesses either. The key lives in a Secret in the operator namespace, so that it survives //! operator restarts: a new key changes every digest and rolling-restarts every StatefulSet managed -//! by the restarter. +//! by the restarter. The operator loads it on startup, see [`load_or_create`]. use std::fmt; @@ -19,7 +19,6 @@ use stackable_operator::{ k8s_openapi::{ByteString, api::core::v1::Secret}, kvp::Label, }; -use tokio::sync::OnceCell; /// Name of the Secret holding the [`DigestKey`]. const SECRET_NAME: &str = "commons-operator-restarter-digest-key"; @@ -93,40 +92,14 @@ impl fmt::Debug for DigestKey { } } -/// Loads the [`DigestKey`] on first use, creating its Secret if it does not exist yet. -/// -/// Loading lazily keeps the operator startup independent of the Secret: if it cannot be loaded or -/// created, only the reconciles that need a digest fail, and they are retried. -pub struct DigestKeyStore { - client: Client, - namespace: String, - key: OnceCell, -} - -impl DigestKeyStore { - pub fn new(client: Client, namespace: String) -> Self { - Self { - client, - namespace, - key: OnceCell::new(), - } - } - - /// Returns the key, loading or creating its Secret in the operator namespace on first use. - /// - /// A failed attempt is not cached, the next call tries again. - pub async fn get(&self) -> Result<&DigestKey, Error> { - self.key - .get_or_try_init(|| async { - let secret = self - .client - .create_if_missing(&DigestKey::generate().to_secret(&self.namespace)) - .await - .context(LoadOrCreateSecretSnafu)?; - DigestKey::from_secret(&secret) - }) - .await - } +/// Loads the [`DigestKey`] from its Secret in `namespace`, creating the Secret with a new random +/// key if it does not exist yet. +pub async fn load_or_create(client: &Client, namespace: &str) -> Result { + let secret = client + .create_if_missing(&DigestKey::generate().to_secret(namespace)) + .await + .context(LoadOrCreateSecretSnafu)?; + DigestKey::from_secret(&secret) } #[cfg(test)] diff --git a/rust/operator-binary/src/restart_controller/statefulset.rs b/rust/operator-binary/src/restart_controller/statefulset.rs index a67f49c4..f9b66769 100644 --- a/rust/operator-binary/src/restart_controller/statefulset.rs +++ b/rust/operator-binary/src/restart_controller/statefulset.rs @@ -1,20 +1,17 @@ use std::{ collections::{BTreeMap, BTreeSet}, - fmt::Debug, future::Future, sync::Arc, time::Duration, }; use futures::{Stream, StreamExt, TryStream, stream}; -use serde::de::DeserializeOwned; use serde_json::json; use snafu::{ResultExt, Snafu}; use stackable_operator::{ client::Client, constants::RESTART_CONTROLLER_ENABLED_LABEL, k8s_openapi::{ - NamespaceResourceScope, api::{ apps::v1::StatefulSet, core::v1::{ConfigMap, EnvFromSource, EnvVar, PodSpec, Secret, Volume}, @@ -23,13 +20,16 @@ use stackable_operator::{ }, kube::{ self, Resource, ResourceExt, - api::{PartialObjectMeta, Patch, PatchParams}, + api::{Patch, PatchParams}, core::{DeserializeGuard, DynamicObject, error_boundary}, runtime::{ Config, WatchStreamExt, applier, controller::{Action, ReconcileRequest, trigger_self, trigger_with}, events::{Recorder, Reporter}, - reflector::{self, ObjectRef, Store}, + reflector::{ + self, ObjectRef, Store, + store::{Writer, WriterDropped}, + }, watcher::{self, watcher}, }, }, @@ -39,12 +39,9 @@ use stackable_operator::{ }; use strum::{EnumDiscriminants, IntoStaticStr}; -use crate::{ - restart_controller::{ - content_digest::{ContentDigest, DigestCache}, - digest_key::{self, DigestKeyStore}, - }, - utils::delayed_init::{DelayedInit, InitDropped, Initializer}, +use crate::restart_controller::{ + content_digest::{replace_content_by_digest, stored_digest}, + digest_key::DigestKey, }; const FULL_CONTROLLER_NAME: &str = "statefulset.restarter.commons.stackable.tech"; @@ -55,13 +52,28 @@ const CONFIGMAP_ANNOTATION_PREFIX: &str = "configmap.restarter.stackable.tech"; /// Prefix of the Pod annotations tracking the referenced Secrets. const SECRET_ANNOTATION_PREFIX: &str = "secret.restarter.stackable.tech"; +/// Page size of the initial list of the watched ConfigMaps and Secrets. +/// +/// They are watched including their content, so a page is held in memory in full until its +/// content is replaced by digests. With kube's default of 500, a page of Secrets (up to 1 MiB +/// each) could need hundreds of MiB, and the memory of the operator grew with the total size of +/// all watched objects in tests. With 20 it stays bounded. +const CONTENT_WATCH_PAGE_SIZE: u32 = 20; + pub struct Ctx { client: Client, - cms: DelayedInit>>, - secrets: DelayedInit>>, - cm_digests: DigestCache, - secret_digests: DigestCache, - digest_key: DigestKeyStore, + + /// Watched ConfigMaps, filled by [`start`]. + /// + /// Readers must [`Store::wait_until_ready`] first, as the store stays empty until its initial + /// list is complete. Otherwise a reconcile in between would see every referenced object as + /// missing and set `changes-ignored`, rolling-restarting the StatefulSet twice on every + /// operator start. + cms: Store, + + /// Watched Secrets, filled by [`start`]. As for [`Ctx::cms`], readers must + /// [`Store::wait_until_ready`] first. + secrets: Store, } #[derive(Snafu, Debug, EnumDiscriminants)] @@ -79,26 +91,17 @@ pub enum Error { obj_ref: Box>, }, - #[snafu(display("configmap initializer was cancelled"))] - ConfigMapsUninitialized { source: InitDropped }, + #[snafu(display("configmap store was dropped before its initial list completed"))] + ConfigMapsUninitialized { source: WriterDropped }, - #[snafu(display("secrets initializer was cancelled"))] - SecretsUninitialized { source: InitDropped }, + #[snafu(display("secret store was dropped before its initial list completed"))] + SecretsUninitialized { source: WriterDropped }, #[snafu(display("failed to build annotation key for object {object_name:?}"))] InvalidAnnotationKey { source: KeyError, object_name: String, }, - - #[snafu(display("failed to fetch {obj_ref} to digest its content"))] - FetchContentFailed { - source: stackable_operator::client::Error, - obj_ref: Box>, - }, - - #[snafu(display("failed to load the key for content digests"))] - LoadDigestKey { source: digest_key::Error }, } impl ReconcilerError for Error { @@ -113,52 +116,43 @@ impl ReconcilerError for Error { Error::ConfigMapsUninitialized { .. } => None, Error::SecretsUninitialized { .. } => None, Error::InvalidAnnotationKey { .. } => None, - Error::FetchContentFailed { obj_ref, .. } => Some(*obj_ref.clone()), - Error::LoadDigestKey { .. } => None, } } } -#[allow(clippy::type_complexity)] -pub fn create_context( - client: Client, - operator_namespace: String, -) -> ( - Arc, - Initializer>>, - Initializer>>, -) { - let (cm_store_tx, cm_store_delayed) = DelayedInit::new(); - let (secret_store_tx, secret_store_delayed) = DelayedInit::new(); +/// Returns the context, along with the writers of its ConfigMap and Secret stores, which +/// [`start`] fills. +pub fn create_context(client: Client) -> (Arc, Writer, Writer) { + let cm_store = Writer::::new(()); + let secret_store = Writer::::new(()); let ctx = Arc::new(Ctx { - client: client.clone(), - cms: cm_store_delayed, - secrets: secret_store_delayed, - cm_digests: DigestCache::default(), - secret_digests: DigestCache::default(), - digest_key: DigestKeyStore::new(client, operator_namespace), + client, + cms: cm_store.as_reader(), + secrets: secret_store.as_reader(), }); - (ctx, cm_store_tx, secret_store_tx) + (ctx, cm_store, secret_store) } +/// Starts the controller. +/// +/// It watches the full ConfigMaps and Secrets, but replaces their content by its digest, keyed +/// with `digest_key`, before storing them in `cm_store` and `secret_store`. pub async fn start( ctx: Arc, - cm_store_tx: Initializer>>, - secret_store_tx: Initializer>>, + cm_store: Writer, + secret_store: Writer, + digest_key: DigestKey, watch_namespace: &WatchNamespace, shutdown_signal: F, ) where F: Future, { let stses = watch_namespace.get_api::>(&ctx.client); - let cms = watch_namespace.get_api::>(&ctx.client); - let secrets = watch_namespace.get_api::>(&ctx.client); - let sts_store = reflector::store::Writer::>::new(()); - let cm_store = reflector::store::Writer::>::new(()); - let secret_store = reflector::store::Writer::>::new(()); - let mut cm_store_tx = Some(cm_store_tx); - let mut secret_store_tx = Some(secret_store_tx); + let cms = watch_namespace.get_api::(&ctx.client); + let secrets = watch_namespace.get_api::(&ctx.client); + let sts_store = Writer::>::new(()); + let cm_digest_key = digest_key.clone(); let ctx2 = ctx.clone(); let event_recorder = Arc::new(Recorder::new( ctx.client.as_kube_client(), @@ -176,43 +170,31 @@ pub async fn start( stream::select( stream::select( trigger_all( - { - let cm_reader = cm_store.as_reader(); - reflector::reflector( - cm_store, - watcher( - cms, - watcher::Config::default() - .labels("restarter.stackable.tech/ignore != true"), - ), + reflector::reflector( + cm_store, + watcher( + cms, + watcher::Config::default() + .labels("restarter.stackable.tech/ignore != true") + .page_size(CONTENT_WATCH_PAGE_SIZE), ) - .inspect(move |_| { - if let Some(tx) = cm_store_tx.take() { - tx.init(cm_reader.clone()); - } - }) - .touched_objects() - }, + .modify(move |cm| replace_content_by_digest(cm, &cm_digest_key)), + ) + .touched_objects(), sts_store.as_reader(), ), trigger_all( - { - let secret_reader = secret_store.as_reader(); - reflector::reflector( - secret_store, - watcher( - secrets, - watcher::Config::default() - .labels("restarter.stackable.tech/ignore != true"), - ), + reflector::reflector( + secret_store, + watcher( + secrets, + watcher::Config::default() + .labels("restarter.stackable.tech/ignore != true") + .page_size(CONTENT_WATCH_PAGE_SIZE), ) - .inspect(move |_| { - if let Some(tx) = secret_store_tx.take() { - tx.init(secret_reader.clone()); - } - }) - .touched_objects() - }, + .modify(move |secret| replace_content_by_digest(secret, &digest_key)), + ) + .touched_objects(), sts_store.as_reader(), ), ), @@ -332,49 +314,36 @@ fn unchanged_resource_version_value( /// Value of the Pod template annotation tracking `object`. /// -/// `previous_value` is the value the Pod template annotation currently has, if any. This fetches -/// the object to digest its content, unless `digests` already holds the digest for its current -/// resourceVersion, or `previous_value` is still up to date, see -/// [`unchanged_resource_version_value`]. +/// `previous_value` is the value the Pod template annotation currently has, if any. It is kept if +/// it is still up to date, see [`unchanged_resource_version_value`]. Otherwise the value is the +/// uid of the object followed by the digest of its content (see +/// [`crate::restart_controller::content_digest`]). /// /// The value is `changes-ignored` if the object is `ignored` via the StatefulSet annotations, or -/// missing from the store (`None`) or the API, i.e. it doesn't exist (yet), e.g. because the -/// StatefulSet was created before it, or it has the label `restarter.stackable.tech/ignore=true` -/// (filtered out by the watcher). This is intended: once the object shows up, the value changes -/// to its digest (unless ignored via the StatefulSet annotations), which restarts the Pods so that -/// they pick it up. Leaving out the annotation instead would not avoid any restart, but cause -/// additional ones, e.g. when an object ignored via a StatefulSet annotation is created after the -/// StatefulSet. -async fn tracking_value( - ctx: &Ctx, - digests: &DigestCache, - object: Option<&PartialObjectMeta>, +/// missing from the store (`None`), i.e. it doesn't exist (yet), e.g. because the StatefulSet was +/// created before it, or it has the label `restarter.stackable.tech/ignore=true` (filtered out by +/// the watcher). This is intended: once the object shows up, the value changes to its digest +/// (unless ignored via the StatefulSet annotations), which restarts the Pods so that they pick it +/// up. Leaving out the annotation instead would not avoid any restart, but cause additional ones, +/// e.g. when an object ignored via a StatefulSet annotation is created after the StatefulSet. +fn tracking_value( + object: Option<&K>, ignored: bool, previous_value: Option<&str>, -) -> Result -where - K: ContentDigest + Resource + Clone + Debug + DeserializeOwned, -{ - let changes_ignored = || "changes-ignored".to_owned(); - let Some(object) = object.filter(|_| !ignored) else { - return Ok(changes_ignored()); +) -> String { + if ignored { + return "changes-ignored".to_owned(); + } + let Some(metadata) = object.map(Resource::meta) else { + return "changes-ignored".to_owned(); }; - let metadata = &object.metadata; if let Some(value) = unchanged_resource_version_value(metadata, previous_value) { - return Ok(value); + return value; + } + match (metadata.uid.as_deref(), stored_digest(metadata)) { + (Some(uid), Some(digest)) => format!("{uid}/{digest}"), + _ => "changes-ignored".to_owned(), } - let digest_key = ctx.digest_key.get().await.context(LoadDigestKeySnafu)?; - let cached = digests - .get_or_fetch(metadata, digest_key, |name, namespace| { - ctx.client.get_opt::(name, namespace) - }) - .await - .with_context(|_| FetchContentFailedSnafu { - obj_ref: ObjectRef::from_obj(object).erase(), - })?; - Ok(cached.map_or_else(changes_ignored, |cached| { - format!("{}/{}", cached.uid, cached.digest) - })) } pub async fn get_updated_restarter_annotations( @@ -402,12 +371,12 @@ pub async fn get_updated_restarter_annotations( find_pod_refs( pod_spec, |volume| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( &volume.config_map.as_ref()?.name, )) }, |env_var| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( &env_var .value_from .as_ref()? @@ -417,14 +386,17 @@ pub async fn get_updated_restarter_annotations( )) }, |env_from| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( &env_from.config_map_ref.as_ref()?.name, )) }, ) }) .map(|cm_ref| cm_ref.within(ns)); - let cms = ctx.cms.get().await.context(ConfigMapsUninitializedSnafu)?; + ctx.cms + .wait_until_ready() + .await + .context(ConfigMapsUninitializedSnafu)?; let ignored_cms = sts .metadata .annotations @@ -438,13 +410,10 @@ pub async fn get_updated_restarter_annotations( for cm_ref in cm_refs { let key = annotation_key(CONFIGMAP_ANNOTATION_PREFIX, &cm_ref.name)?; let value = tracking_value( - &ctx, - &ctx.cm_digests, - cms.get(&cm_ref).as_deref(), + ctx.cms.get(&cm_ref).as_deref(), ignored_cms.contains(&cm_ref.name), previous_annotations.and_then(|previous| previous.get(&key).map(String::as_str)), - ) - .await?; + ); annotations.insert(key, value); } @@ -453,24 +422,27 @@ pub async fn get_updated_restarter_annotations( find_pod_refs( pod_spec, |volume| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( volume.secret.as_ref()?.secret_name.as_deref()?, )) }, |env_var| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( &env_var.value_from.as_ref()?.secret_key_ref.as_ref()?.name, )) }, |env_from| { - Some(ObjectRef::>::new( + Some(ObjectRef::::new( &env_from.secret_ref.as_ref()?.name, )) }, ) }) .map(|secret_ref| secret_ref.within(ns)); - let secrets = ctx.secrets.get().await.context(SecretsUninitializedSnafu)?; + ctx.secrets + .wait_until_ready() + .await + .context(SecretsUninitializedSnafu)?; let ignored_secrets = sts .metadata .annotations @@ -486,13 +458,10 @@ pub async fn get_updated_restarter_annotations( for secret_ref in secret_refs { let key = annotation_key(SECRET_ANNOTATION_PREFIX, &secret_ref.name)?; let value = tracking_value( - &ctx, - &ctx.secret_digests, - secrets.get(&secret_ref).as_deref(), + ctx.secrets.get(&secret_ref).as_deref(), ignored_secrets.contains(&secret_ref.name), previous_annotations.and_then(|previous| previous.get(&key).map(String::as_str)), - ) - .await?; + ); annotations.insert(key, value); } @@ -620,4 +589,61 @@ mod tests { None ); } + + #[test] + fn tracking_value_prefers_unchanged_value_then_digest() { + let uid = "f9dc0a8f-5f4b-4f52-9d0f-1a0ba1e0bd2c"; + let digest_key = DigestKey::new([42; 32]); + let mut stored = ConfigMap { + metadata: ObjectMeta { + uid: Some(uid.to_owned()), + resource_version: Some("12345".to_owned()), + ..ObjectMeta::default() + }, + data: Some([("foo".to_owned(), "bar".to_owned())].into()), + ..ConfigMap::default() + }; + replace_content_by_digest(&mut stored, &digest_key); + let digest_value = format!( + "{uid}/{}", + stored_digest(&stored.metadata).expect("the digest should be stored") + ); + let legacy_value = format!("{uid}/12345"); + + for (object, ignored, previous_value, expected) in [ + (None, false, None, "changes-ignored"), + ( + Some(&stored), + true, + Some(digest_value.as_str()), + "changes-ignored", + ), + (Some(&stored), false, None, digest_value.as_str()), + ( + Some(&stored), + false, + Some("changes-ignored"), + digest_value.as_str(), + ), + ( + Some(&stored), + false, + Some(&legacy_value), + legacy_value.as_str(), + ), + ( + Some(&stored), + false, + Some(&format!("{uid}/12344")), + digest_value.as_str(), + ), + (Some(&ConfigMap::default()), false, None, "changes-ignored"), + ] { + assert_eq!( + tracking_value(object, ignored, previous_value), + expected, + "ignored {ignored}, previous value {previous_value:?}" + ); + } + } } diff --git a/rust/operator-binary/src/utils/delayed_init.rs b/rust/operator-binary/src/utils/delayed_init.rs deleted file mode 100644 index 6cf56b16..00000000 --- a/rust/operator-binary/src/utils/delayed_init.rs +++ /dev/null @@ -1,212 +0,0 @@ -// use tokio::sync::RwLock; -#[cfg(test)] -use std::sync::RwLockWriteGuard; -use std::{fmt::Debug, sync::RwLock, task::Poll}; - -use futures::{Future, FutureExt, channel}; -use snafu::Snafu; -use tracing::trace; - -/// The sending counterpart to a [`DelayedInit`] -pub struct Initializer(channel::oneshot::Sender); -impl Initializer { - /// Sends `value` to the linked [`DelayedInit`]. - pub fn init(self, value: T) { - // oneshot::Sender::send fails if no recipients remain, this is not really a relevant - // case to signal for our use case - let _ = self.0.send(value); - } -} - -/// A value that must be initialized by an external writer -/// -/// Can be considered equivalent to a [`channel::oneshot`] channel, except for that -/// the value produced is retained for subsequent calls to [`Self::get`]. -pub struct DelayedInit { - state: RwLock>, - // A test-only hook to let us create artificial race conditions - #[cfg(test)] - #[allow(clippy::type_complexity)] - test_hook_start_of_slow_path: - Box>) + Send + Sync>, -} -enum ReceiverState { - Waiting(channel::oneshot::Receiver), - Ready(Result), -} -impl DelayedInit { - /// Returns an empty `DelayedInit` that has no value, along with a linked [`Initializer`] - pub fn new() -> (Initializer, Self) { - let (tx, rx) = channel::oneshot::channel(); - ( - Initializer(tx), - DelayedInit { - state: RwLock::new(ReceiverState::Waiting(rx)), - #[cfg(test)] - test_hook_start_of_slow_path: Box::new(|_| ()), - }, - ) - } -} -impl DelayedInit { - /// Wait for the value to be available and then return it - /// - /// Calling `get` again if a value has already been returned is guaranteed to return (a clone of) - /// the same value. - pub async fn get(&self) -> Result { - DelayedInitGet(self).await - } -} - -// Using a manually implemented future because we don't want to hold the lock across poll calls -// since that would mean that an unpolled writer would stall all other tasks from being able to poll it -struct DelayedInitGet<'a, T>(&'a DelayedInit); -impl<'a, T> Future for DelayedInitGet<'a, T> -where - T: Clone, -{ - type Output = Result; - - #[tracing::instrument(name = "DelayedInit::get", level = "trace", skip(self, cx))] - fn poll( - self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll { - let read_lock = self.0.state.read().unwrap(); - if let ReceiverState::Ready(v) = &*read_lock { - trace!("using fast path, value is already ready"); - Poll::Ready(v.clone()) - } else { - trace!("using slow path, need to wait for the channel"); - // IMPORTANT: Make sure that the optimistic read lock has been released already - drop(read_lock); - let mut state = self.0.state.write().unwrap(); - trace!("got write lock"); - #[cfg(test)] - (self.0.test_hook_start_of_slow_path)(&mut state); - match &mut *state { - ReceiverState::Waiting(rx) => { - trace!("channel still active, polling"); - if let Poll::Ready(value) = rx.poll_unpin(cx).map_err(|_| InitDropped) { - trace!("got value on slow path, memoizing"); - *state = ReceiverState::Ready(value.clone()); - Poll::Ready(value) - } else { - trace!("channel is still pending"); - Poll::Pending - } - } - ReceiverState::Ready(v) => { - trace!( - "slow path but value was already initialized, another writer already initialized" - ); - Poll::Ready(v.clone()) - } - } - } - } -} - -#[derive(Debug, Snafu, Clone, Copy, PartialEq, Eq)] -#[snafu(display("initializer was dropped before value was initialized"))] -pub struct InitDropped; - -#[cfg(test)] -mod tests { - use std::{ - sync::{Arc, Mutex}, - task::Poll, - }; - - use futures::{pin_mut, poll}; - - // use tracing::Level; - - // use tracing_subscriber::util::SubscriberInitExt; - use super::DelayedInit; - use crate::utils::delayed_init::ReceiverState; - - // fn setup_tracing() -> tracing::dispatcher::DefaultGuard { - // tracing_subscriber::fmt() - // .with_max_level(Level::TRACE) - // .with_test_writer() - // .finish() - // .set_default() - // } - - #[tokio::test] - async fn must_allow_single_reader() { - // let _tracing = setup_tracing(); - let (tx, rx) = DelayedInit::::new(); - let get1 = rx.get(); - pin_mut!(get1); - assert_eq!(poll!(get1.as_mut()), Poll::Pending); - tx.init(1); - assert_eq!(poll!(get1), Poll::Ready(Ok(1))); - } - - #[tokio::test] - async fn must_allow_concurrent_readers_while_waiting() { - // let _tracing = setup_tracing(); - let (tx, rx) = DelayedInit::::new(); - let get1 = rx.get(); - let get2 = rx.get(); - let get3 = rx.get(); - pin_mut!(get1, get2, get3); - assert_eq!(poll!(get1.as_mut()), Poll::Pending); - assert_eq!(poll!(get2.as_mut()), Poll::Pending); - assert_eq!(poll!(get3.as_mut()), Poll::Pending); - tx.init(1); - assert_eq!(poll!(get1), Poll::Ready(Ok(1))); - assert_eq!(poll!(get2), Poll::Ready(Ok(1))); - assert_eq!(poll!(get3), Poll::Ready(Ok(1))); - } - - #[tokio::test] - async fn must_allow_reading_after_init() { - // let _tracing = setup_tracing(); - let (tx, rx) = DelayedInit::::new(); - let get1 = rx.get(); - pin_mut!(get1); - assert_eq!(poll!(get1.as_mut()), Poll::Pending); - tx.init(1); - assert_eq!(poll!(get1), Poll::Ready(Ok(1))); - assert_eq!(rx.get().await, Ok(1)); - assert_eq!(rx.get().await, Ok(1)); - } - - #[tokio::test] - async fn must_allow_concurrent_readers_in_any_order() { - // let _tracing = setup_tracing(); - let (tx, rx) = DelayedInit::::new(); - let get1 = rx.get(); - let get2 = rx.get(); - let get3 = rx.get(); - pin_mut!(get1, get2, get3); - assert_eq!(poll!(get1.as_mut()), Poll::Pending); - assert_eq!(poll!(get2.as_mut()), Poll::Pending); - assert_eq!(poll!(get3.as_mut()), Poll::Pending); - tx.init(1); - assert_eq!(poll!(get3), Poll::Ready(Ok(1))); - assert_eq!(poll!(get2), Poll::Ready(Ok(1))); - assert_eq!(poll!(get1), Poll::Ready(Ok(1))); - } - - #[tokio::test] - async fn must_work_despite_writer_race() { - // let _tracing = setup_tracing(); - let (_tx, mut rx) = DelayedInit::::new(); - let slow_path_calls = Arc::new(Mutex::new(0)); - let slow_path_calls2 = slow_path_calls.clone(); - // This emulates two racing get() calls, where a fake get() memoizes a value while the true get() - // is waiting to upgrade its read lock to a write lock. - rx.test_hook_start_of_slow_path = Box::new(move |state| { - *slow_path_calls2.lock().unwrap() += 1; - **state = ReceiverState::Ready(Ok(1)); - }); - assert_eq!(rx.get().await, Ok(1)); - assert_eq!(rx.get().await, Ok(1)); - assert_eq!(rx.get().await, Ok(1)); - assert_eq!(*slow_path_calls.lock().unwrap(), 1); - } -} diff --git a/rust/operator-binary/src/utils/mod.rs b/rust/operator-binary/src/utils/mod.rs deleted file mode 100644 index 2e542e1b..00000000 --- a/rust/operator-binary/src/utils/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod delayed_init; diff --git a/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs b/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs index 2db9daa5..afa08303 100644 --- a/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs +++ b/rust/operator-binary/src/webhooks/restarter_mutate_sts.rs @@ -24,7 +24,7 @@ use stackable_operator::{ use crate::{ FIELD_MANAGER, OPERATOR_NAME, - restart_controller::statefulset::{Ctx, Error, get_updated_restarter_annotations}, + restart_controller::statefulset::{Ctx, get_updated_restarter_annotations}, }; pub fn create_webhook( @@ -95,9 +95,9 @@ fn get_sts_restarter_mutating_webhook_configuration() -> MutatingWebhookConfigur // > Webhooks typically operate only on the content of the AdmissionReview sent to them. // > Some webhooks, however, make out-of-band changes as part of processing admission requests. // - // We read in the state of the world using the ConfigMap and Secret store and by - // fetching the referenced objects. The only object we may create is the idempotent - // digest key Secret (see `DigestKeyStore`), so we consider this side-effect free. + // We read in the state of the world using the ConfigMap and Secret store. + // So, technically our outcome depends on external factors, *but* this webhook is not + // creating any external objects, so from our understanding it's side-effect free. side_effects: "None".to_owned(), ..Default::default() }]), @@ -136,13 +136,6 @@ async fn add_sts_restarter_annotations_handler( let annotations = match get_updated_restarter_annotations(sts, ctx).await { Ok(annotations) => annotations, - Err(err @ (Error::FetchContentFailed { .. } | Error::LoadDigestKey { .. })) => { - tracing::warn!( - error = &err as &dyn std::error::Error, - "Admitting StatefulSet without restarter annotations, the controller adds them later" - ); - return AdmissionResponse::from(&request); - } Err(err) => { return AdmissionResponse::invalid(format!( "failed to get updated restarted annotations: {err:#}" From 9efe76a1534cc85467843510182566549634ad3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20M=C3=BCller?= Date: Wed, 25 Nov 2026 13:39:18 +0100 Subject: [PATCH 3/3] chore: cargo-deny --- Cargo.lock | 93 +++++++++++++++++-------- Cargo.nix | 197 ++++++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 223 insertions(+), 67 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b195dd3b..c7be06e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -943,9 +943,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -1107,9 +1107,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" +checksum = "9bd04d0d9c7079b416b458d2317aea4aa964c81938cb7c20f559758c4f422dc8" dependencies = [ "arraydeque", "smallvec", @@ -1283,7 +1283,6 @@ dependencies = [ "hyper-util", "log", "rustls", - "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", @@ -1726,9 +1725,9 @@ checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" [[package]] name = "kube" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c73b082f549411623a4f8949bd24dcaedacb1511379c461c76d579fde301d021" +checksum = "f95e1a9107878bef32cfbe2e5e084584db832c9616df9981adc4673f9fb1c853" dependencies = [ "k8s-openapi", "kube-client", @@ -1739,9 +1738,9 @@ dependencies = [ [[package]] name = "kube-client" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae56b223bca490db1f1b115bfc606d411177511d7748d8cc019a7e3b2935430b" +checksum = "703ee17477c86501627e83492895c06ab6fc2c55a319bb2fbc582ccae739ba67" dependencies = [ "base64 0.23.1", "bytes", @@ -1776,9 +1775,9 @@ dependencies = [ [[package]] name = "kube-core" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6de84b47fc1aa35ba0ef9059ef54b47c8b47f0979afd15487e525282f2d73fb9" +checksum = "b5e9a9aa533b2f4106ac1ac45e168bb452325eb9e918d57335444f60bef34ffc" dependencies = [ "derive_more", "form_urlencoded", @@ -1795,9 +1794,9 @@ dependencies = [ [[package]] name = "kube-derive" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de1fb46ac34371491ac0277c13e0e1bb9288000e64c86ca3d91343754818e64e" +checksum = "cedc991dbe7757a646098dead35e070e13ce66e2996b02162ac7f97eb97f4d6e" dependencies = [ "darling", "proc-macro2", @@ -1809,9 +1808,9 @@ dependencies = [ [[package]] name = "kube-runtime" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dea60005024b6ec1819c426209aa29b9eaca64f6b3988ab73c55f43fa484392" +checksum = "ca78d9eeb4674eb75e381e6a956e8a5005942928dec87de4db9ef9701af8a637" dependencies = [ "ahash", "async-broadcast", @@ -1824,7 +1823,7 @@ dependencies = [ "json-patch", "k8s-openapi", "kube-client", - "parking_lot", + "parking_lot 0.13.0", "pin-project", "serde", "serde_json", @@ -1866,9 +1865,9 @@ checksum = "2e126dda6f34391ab7b444f9922055facc83c07a910da3eb16f1e4d9c45dc777" [[package]] name = "libz-sys" -version = "1.1.31" +version = "1.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" dependencies = [ "cc", "libc", @@ -1891,6 +1890,15 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "lock_api" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.35" @@ -2138,8 +2146,18 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api", - "parking_lot_core", + "lock_api 0.4.14", + "parking_lot_core 0.9.12", +] + +[[package]] +name = "parking_lot" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" +dependencies = [ + "lock_api 0.5.0", + "parking_lot_core 0.10.0", ] [[package]] @@ -2150,7 +2168,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parking_lot_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" +dependencies = [ + "libc", + "redox_syscall 0.9.5", "smallvec", "windows-link", ] @@ -2478,6 +2508,15 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -2814,12 +2853,12 @@ dependencies = [ [[package]] name = "serde-saphyr" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f4dc2714fc5632417a6e979602d7044bad8f2880c63fc7217087180acec31b6" +checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", - "base64 0.23.1", + "base64 0.22.1", "encoding_rs_io", "granit-parser", "nohash-hasher", @@ -3505,7 +3544,7 @@ dependencies = [ "bytes", "libc", "mio", - "parking_lot", + "parking_lot 0.12.5", "pin-project-lite", "signal-hook-registry", "socket2", @@ -3834,9 +3873,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/Cargo.nix b/Cargo.nix index 79c87ff6..41adefe9 100644 --- a/Cargo.nix +++ b/Cargo.nix @@ -3002,9 +3002,9 @@ rec { }; "form_urlencoded" = rec { crateName = "form_urlencoded"; - version = "1.2.2"; + version = "1.2.3"; edition = "2018"; - sha256 = "1kqzb2qn608rxl3dws04zahcklpplkd5r1vpabwga5l50d2v4k6b"; + sha256 = "0vph40jb1qvkvl52aigslr0hvbg1dhiwdwaxg48i5yxgkqcqk95g"; license = "MIT OR Apache-2.0"; authors = [ "The rust-url developers" @@ -3612,10 +3612,10 @@ rec { }; "granit-parser" = rec { crateName = "granit-parser"; - version = "2.1.0"; + version = "2.2.0"; edition = "2021"; crateBin = []; - sha256 = "1pq1ljzfc7n0sfx0f6la8f5p4lmj81n841rj293kvpylsj35bw05"; + sha256 = "1j1d897qqxarylh7rjrq37469aaax9x33ljqnhbb8ybhkh6lvl4v"; libName = "granit_parser"; license = "MIT OR Apache-2.0"; authors = [ @@ -4180,11 +4180,6 @@ rec { packageId = "rustls"; usesDefaultFeatures = false; } - { - name = "rustls-native-certs"; - packageId = "rustls-native-certs"; - optional = true; - } { name = "tokio"; packageId = "tokio"; @@ -4234,7 +4229,7 @@ rec { "webpki-roots" = [ "dep:webpki-roots" ]; "webpki-tokio" = [ "webpki-roots" ]; }; - resolvedDefaultFeatures = [ "http1" "log" "logging" "native-tokio" "ring" "rustls-native-certs" "tls12" ]; + resolvedDefaultFeatures = [ "http1" "log" "logging" "ring" "tls12" ]; }; "hyper-timeout" = rec { crateName = "hyper-timeout"; @@ -5678,9 +5673,9 @@ rec { }; "kube" = rec { crateName = "kube"; - version = "5.0.0"; + version = "5.2.0"; edition = "2024"; - sha256 = "08fh07izsyfmfqf4d71p24awpnmfvhjbsjc99wx644clahphhfy7"; + sha256 = "0ly8n6gkyry4mn0rkpqnjqn87nw48l45wbmyrwrfz2w70y8ilppr"; license = "Apache-2.0"; authors = [ "clux " @@ -5755,9 +5750,9 @@ rec { }; "kube-client" = rec { crateName = "kube-client"; - version = "5.0.0"; + version = "5.2.0"; edition = "2024"; - sha256 = "02s36llknzls076dhj3p3m8pf4a1dmhgqnqi3cgxp454phiv4mmf"; + sha256 = "0rxs77kwlb2qphpvn6d3alngrdkaq2ajhjc3gri02rf8fxsf2gkh"; libName = "kube_client"; license = "Apache-2.0"; authors = [ @@ -5813,7 +5808,7 @@ rec { packageId = "hyper-rustls"; optional = true; usesDefaultFeatures = false; - features = [ "http1" "logging" "native-tokio" "tls12" ]; + features = [ "http1" "logging" "tls12" ]; } { name = "hyper-timeout"; @@ -5893,7 +5888,7 @@ rec { name = "tokio"; packageId = "tokio"; optional = true; - features = [ "time" "signal" "sync" "rt" ]; + features = [ "time" "sync" "rt" ]; } { name = "tokio-util"; @@ -5970,8 +5965,8 @@ rec { "jsonpatch" = [ "kube-core/jsonpatch" ]; "jsonpath-rust" = [ "dep:jsonpath-rust" ]; "kubelet-debug" = [ "ws" "kube-core/kubelet-debug" ]; - "oauth" = [ "client" "tame-oauth" ]; - "oidc" = [ "client" "form_urlencoded" ]; + "oauth" = [ "client" "hyper-rustls?/native-tokio" "tame-oauth" ]; + "oidc" = [ "client" "form_urlencoded" "hyper-rustls?/native-tokio" ]; "openssl" = [ "dep:openssl" ]; "openssl-tls" = [ "openssl" "hyper-openssl" ]; "pem" = [ "dep:pem" ]; @@ -5995,9 +5990,9 @@ rec { }; "kube-core" = rec { crateName = "kube-core"; - version = "5.0.0"; + version = "5.2.0"; edition = "2024"; - sha256 = "1f9zszr84ljjgr41bzcsjzq4g2vwniafynchxyh5p8qszi3lps3d"; + sha256 = "1z2gyfz60ks46mrxa679p5g34lmlicb5xi0smh342brvafmaksdm"; libName = "kube_core"; license = "Apache-2.0"; authors = [ @@ -6079,9 +6074,9 @@ rec { }; "kube-derive" = rec { crateName = "kube-derive"; - version = "5.0.0"; + version = "5.2.0"; edition = "2024"; - sha256 = "0kp63147ahqkv6inrj341q08i4mvw7h16z17q0d4jwa3qdmb87yy"; + sha256 = "0vjdgywpxyf758b04swrw9kcw4qf0xgd7sld153acmvppqfrkp6f"; procMacro = true; libName = "kube_derive"; license = "Apache-2.0"; @@ -6129,9 +6124,9 @@ rec { }; "kube-runtime" = rec { crateName = "kube-runtime"; - version = "5.0.0"; + version = "5.2.0"; edition = "2024"; - sha256 = "14j393x46py5ffmqhfbb9ykar7lvlad209n434cfrdi4a0061slx"; + sha256 = "0dx6z0d71ycyvgj7vj6y50lr81ahi9p9ashy71gbfkk7nkpdjy6a"; libName = "kube_runtime"; license = "Apache-2.0"; authors = [ @@ -6175,6 +6170,7 @@ rec { { name = "hostname"; packageId = "hostname"; + target = { target, features }: ((target."unix" or false) || (target."windows" or false)); } { name = "json-patch"; @@ -6193,7 +6189,7 @@ rec { } { name = "parking_lot"; - packageId = "parking_lot"; + packageId = "parking_lot 0.13.0"; } { name = "pin-project"; @@ -6216,6 +6212,12 @@ rec { packageId = "tokio"; features = [ "time" ]; } + { + name = "tokio"; + packageId = "tokio"; + target = { target, features }: (((target."unix" or false) || (target."windows" or false)) && (!("emscripten" == target."os" or null))); + features = [ "signal" ]; + } { name = "tokio-util"; packageId = "tokio-util"; @@ -6336,10 +6338,10 @@ rec { }; "libz-sys" = rec { crateName = "libz-sys"; - version = "1.1.31"; + version = "1.1.33"; edition = "2018"; links = "z"; - sha256 = "1cjw8nisxy5iv8yms7dsxwhclb26djl38n6xq4nmlqxxra73087z"; + sha256 = "0ic0jc13vgz6fwcm12p7ss5bvl09mbkl52c2ip3v1ni18fgzbqzy"; libName = "libz_sys"; license = "MIT OR Apache-2.0"; authors = [ @@ -6394,7 +6396,7 @@ rec { "yoke" = [ "dep:yoke" ]; }; }; - "lock_api" = rec { + "lock_api 0.4.14" = rec { crateName = "lock_api"; version = "0.4.14"; edition = "2021"; @@ -6417,6 +6419,29 @@ rec { }; resolvedDefaultFeatures = [ "atomic_usize" "default" ]; }; + "lock_api 0.5.0" = rec { + crateName = "lock_api"; + version = "0.5.0"; + edition = "2024"; + sha256 = "1bsr9bn8b8fh1nq077l4yris6lizar4q7v6nykf175hpv8i1pnb5"; + license = "MIT OR Apache-2.0"; + authors = [ + "Amanieu d'Antras " + ]; + dependencies = [ + { + name = "scopeguard"; + packageId = "scopeguard"; + usesDefaultFeatures = false; + } + ]; + features = { + "default" = [ "atomic_usize" ]; + "owning_ref" = [ "dep:owning_ref" ]; + "serde" = [ "dep:serde" ]; + }; + resolvedDefaultFeatures = [ "atomic_usize" "default" ]; + }; "log" = rec { crateName = "log"; version = "0.4.35"; @@ -7341,7 +7366,7 @@ rec { "loom" = [ "dep:loom" ]; }; }; - "parking_lot" = rec { + "parking_lot 0.12.5" = rec { crateName = "parking_lot"; version = "0.12.5"; edition = "2021"; @@ -7353,11 +7378,11 @@ rec { dependencies = [ { name = "lock_api"; - packageId = "lock_api"; + packageId = "lock_api 0.4.14"; } { name = "parking_lot_core"; - packageId = "parking_lot_core"; + packageId = "parking_lot_core 0.9.12"; } ]; features = { @@ -7369,7 +7394,76 @@ rec { }; resolvedDefaultFeatures = [ "default" ]; }; - "parking_lot_core" = rec { + "parking_lot 0.13.0" = rec { + crateName = "parking_lot"; + version = "0.13.0"; + edition = "2024"; + sha256 = "09njdx4da5163x3h43x0qpkrmhrg89ir0mc4hxbvgl71liy97kx9"; + license = "MIT OR Apache-2.0"; + authors = [ + "Amanieu d'Antras " + ]; + dependencies = [ + { + name = "lock_api"; + packageId = "lock_api 0.5.0"; + } + { + name = "parking_lot_core"; + packageId = "parking_lot_core 0.10.0"; + } + ]; + features = { + "arc_lock" = [ "lock_api/arc_lock" ]; + "deadlock_detection" = [ "parking_lot_core/deadlock_detection" ]; + "nightly" = [ "parking_lot_core/nightly" ]; + "owning_ref" = [ "lock_api/owning_ref" ]; + "serde" = [ "lock_api/serde" ]; + }; + resolvedDefaultFeatures = [ "default" ]; + }; + "parking_lot_core 0.10.0" = rec { + crateName = "parking_lot_core"; + version = "0.10.0"; + edition = "2024"; + sha256 = "09lqs4hjq55zz70gbiszx2wpz366h2pzq42hh6kqmhcc0rhg1zww"; + license = "MIT OR Apache-2.0"; + authors = [ + "Amanieu d'Antras " + ]; + dependencies = [ + { + name = "libc"; + packageId = "libc"; + target = { target, features }: (((target."unix" or false) && (!("aix" == target."os" or null))) || ("wasi" == target."os" or null)); + } + { + name = "libc"; + packageId = "libc"; + target = { target, features }: ("aix" == target."os" or null); + } + { + name = "redox_syscall"; + packageId = "redox_syscall 0.9.5"; + target = { target, features }: ("redox" == target."os" or null); + } + { + name = "smallvec"; + packageId = "smallvec"; + } + { + name = "windows-link"; + packageId = "windows-link"; + target = { target, features }: (target."windows" or false); + } + ]; + features = { + "backtrace" = [ "dep:backtrace" ]; + "deadlock_detection" = [ "petgraph" "backtrace" ]; + "petgraph" = [ "dep:petgraph" ]; + }; + }; + "parking_lot_core 0.9.12" = rec { crateName = "parking_lot_core"; version = "0.9.12"; edition = "2021"; @@ -7390,7 +7484,7 @@ rec { } { name = "redox_syscall"; - packageId = "redox_syscall"; + packageId = "redox_syscall 0.5.18"; target = { target, features }: ("redox" == target."os" or null); } { @@ -8337,7 +8431,7 @@ rec { }; resolvedDefaultFeatures = [ "os_rng" "std" ]; }; - "redox_syscall" = rec { + "redox_syscall 0.5.18" = rec { crateName = "redox_syscall"; version = "0.5.18"; edition = "2021"; @@ -8360,6 +8454,29 @@ rec { }; resolvedDefaultFeatures = [ "default" "userspace" ]; }; + "redox_syscall 0.9.5" = rec { + crateName = "redox_syscall"; + version = "0.9.5"; + edition = "2021"; + sha256 = "1zb8g34sfgrbvja7lgay2isggkj461qf86mdchawn7ml8mc8f32q"; + libName = "syscall"; + license = "MIT"; + authors = [ + "Jeremy Soller " + ]; + dependencies = [ + { + name = "bitflags"; + packageId = "bitflags 2.13.2"; + } + ]; + features = { + "core" = [ "dep:core" ]; + "default" = [ "userspace" ]; + "rustc-dep-of-std" = [ "core" "bitflags/rustc-dep-of-std" ]; + }; + resolvedDefaultFeatures = [ "default" "userspace" ]; + }; "ref-cast" = rec { crateName = "ref-cast"; version = "1.0.27"; @@ -9678,10 +9795,10 @@ rec { }; "serde-saphyr" = rec { crateName = "serde-saphyr"; - version = "2.1.0"; + version = "2.2.0"; edition = "2024"; crateBin = []; - sha256 = "1diixjn80w882xrgqqqci3rdifj4f0nn0yg9lqbj8qy59xqw4k9z"; + sha256 = "1n87f1lfymy00y0fnr4kjq9xn1pqp2zsv6szigsvnk9l941xx74n"; libName = "serde_saphyr"; license = "MIT OR Apache-2.0"; dependencies = [ @@ -9692,7 +9809,7 @@ rec { } { name = "base64"; - packageId = "base64 0.23.1"; + packageId = "base64 0.22.1"; optional = true; } { @@ -12017,7 +12134,7 @@ rec { } { name = "parking_lot"; - packageId = "parking_lot"; + packageId = "parking_lot 0.12.5"; optional = true; } { @@ -13372,9 +13489,9 @@ rec { }; "url" = rec { crateName = "url"; - version = "2.5.8"; + version = "2.5.9"; edition = "2018"; - sha256 = "1v8f7nx3hpr1qh76if0a04sj08k86amsq4h8cvpw6wvk76jahrzz"; + sha256 = "06ivkcv3ljdrp34vlr8n2byyzk7m43q4r3g8ggqhwb5lgd0d437h"; license = "MIT OR Apache-2.0"; authors = [ "The rust-url developers"