diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c0be262..34730ca3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,9 +27,12 @@ All notable changes to this project will be documented in this file. status was discarded and the container always exited `0`, so a crashed ZooKeeper was reported to Kubernetes as a clean exit. A container terminated by `SIGTERM` on Pod deletion now reports `143`, which `kubectl` shows as `Reason: Error` ([#1116]). +- When a ZNode is deleted, the ZooKeeper path derived from the node's `metadata.uid` is deleted. + Previously, any existing `status.znodePath` was deleted instead ([#1118]). [#1108]: https://github.com/stackabletech/zookeeper-operator/pull/1108 [#1116]: https://github.com/stackabletech/zookeeper-operator/pull/1116 +[#1118]: https://github.com/stackabletech/zookeeper-operator/pull/1118 ## [26.11.0] - 2026-11-20 diff --git a/docs/modules/zookeeper/pages/usage_guide/isolating_clients_with_znodes.adoc b/docs/modules/zookeeper/pages/usage_guide/isolating_clients_with_znodes.adoc index f5541987..2ca75b7d 100644 --- a/docs/modules/zookeeper/pages/usage_guide/isolating_clients_with_znodes.adoc +++ b/docs/modules/zookeeper/pages/usage_guide/isolating_clients_with_znodes.adoc @@ -123,4 +123,6 @@ kubectl get zookeeperznode/test-znode -o json -n $NAMESPACE \ | kubectl replace -f- --subresource=status ---- -NOTE: The auto-generated ZNode will still be kept, and should be cleaned up by an administrator. +When the ZookeeperZnode is deleted, the operator deletes only the auto-generated ZNode. +The ZNode set through `status.znodePath` is kept in ZooKeeper, and the operator emits a `ZnodeKept` event on the ZookeeperZnode. +Delete it manually if it is no longer needed. diff --git a/rust/operator-binary/src/main.rs b/rust/operator-binary/src/main.rs index 2660edec..93fdc36a 100644 --- a/rust/operator-binary/src/main.rs +++ b/rust/operator-binary/src/main.rs @@ -254,6 +254,7 @@ async fn main() -> anyhow::Result<()> { Arc::new(znode_controller::Ctx { client: client.clone(), operator_environment, + event_recorder: znode_event_recorder.clone(), }), ) // We can let the reporting happen in the background diff --git a/rust/operator-binary/src/znode_controller.rs b/rust/operator-binary/src/znode_controller.rs index 2026e3c8..f57eff27 100644 --- a/rust/operator-binary/src/znode_controller.rs +++ b/rust/operator-binary/src/znode_controller.rs @@ -16,9 +16,15 @@ use stackable_operator::{ constant, k8s_openapi::api::core::v1::ConfigMap, kube::{ + Resource, api::ObjectMeta, core::{DeserializeGuard, DynamicObject, error_boundary}, - runtime::{controller, finalizer, reflector::ObjectRef}, + runtime::{ + controller, + events::{Event, EventType, Recorder}, + finalizer, + reflector::ObjectRef, + }, }, logging::controller::ReconcilerError, shared::time::Duration, @@ -29,7 +35,7 @@ use stackable_operator::{ }, }; use strum::{EnumDiscriminants, IntoStaticStr}; -use tracing::{debug, info}; +use tracing::{debug, info, warn}; use crate::{ ZOOKEEPER_OPERATOR_NAME, @@ -51,6 +57,7 @@ constant!(pub(crate) CONTROLLER_NAME: ControllerName = ZNODE_CONTROLLER_NAME); pub struct Ctx { pub client: stackable_operator::client::Client, pub operator_environment: OperatorEnvironmentOptions, + pub event_recorder: Arc, } #[derive(Snafu, Debug, EnumDiscriminants)] @@ -187,7 +194,10 @@ pub async fn reconcile_znode( // Capturing the Result here (rather than the inner value) is intentional as ZkDoesNotExist will be handled explicitly below let dereferenced_objects = dereference::dereference(client, znode).await; let mut default_status_updates: Option = None; - // Store the znode path in the status rather than the object itself, to ensure that only K8s administrators can override it + // The znode path is stored in the status rather than the spec, so overriding it needs the + // RBAC permission to write the `zookeeperznodes/status` subresource. Whoever holds that + // permission can point the path at any znode, so the cleanup step never deletes an + // overridden path (see `CleanupPlan`). let znode_path = match znode.status.as_ref().and_then(|s| s.znode_path.as_deref()) { Some(znode_path) => { debug!(znode.path = znode_path, "Using configured znode path"); @@ -196,7 +206,7 @@ pub async fn reconcile_znode( None => { // Default to the uid (managed by k8s itself) rather than the object name, to ensure that malicious users can't trick the controller // into letting them take over a znode owned by someone else - let znode_path = format!("/znode-{}", uid); + let znode_path = DerivedZnodePath::from_uid(uid).into_string(); info!( znode.path = znode_path, "No znode path set, setting to default" @@ -229,7 +239,7 @@ pub async fn reconcile_znode( .context(ValidateClusterSnafu)?; reconcile_apply(client, &validated_znode, &dereferenced, &znode_path).await } - finalizer::Event::Cleanup(_znode) => { + finalizer::Event::Cleanup(znode) => { let dereferenced = match dereferenced_objects { Ok(d) => d, Err(dereference::Error::ZkDoesNotExist { zk, .. }) => { @@ -245,8 +255,18 @@ pub async fn reconcile_znode( &dereferenced.zk, dereferenced.authentication_classes.clone(), ); - reconcile_cleanup(client, &dereferenced, &zookeeper_security, &znode_path) - .await + let cleanup_plan = CleanupPlan::new(uid, &znode_path); + if let Some(kept_znode_path) = cleanup_plan.keep { + publish_kept_znode_event(&ctx.event_recorder, &znode, kept_znode_path) + .await; + } + reconcile_cleanup( + client, + &dereferenced, + &zookeeper_security, + &cleanup_plan.delete, + ) + .await } } }, @@ -255,6 +275,79 @@ pub async fn reconcile_znode( .map_err(Error::extract_finalizer_err) } +/// The znode path that the controller derives for a ZookeeperZnode from its uid. +/// +/// Kubernetes assigns the uid, so nobody can choose it to name a znode that belongs to someone +/// else. This is the only kind of path that [`reconcile_cleanup`] accepts, so a path taken from +/// `status.znodePath` cannot be deleted by mistake: anyone who may write the status subresource +/// could otherwise make the operator delete any znode in the referenced ensemble. +/// +/// Construct it only through [`DerivedZnodePath::from_uid`], never through the tuple field. +#[derive(Debug, Eq, PartialEq)] +struct DerivedZnodePath(String); + +impl DerivedZnodePath { + fn from_uid(uid: &str) -> Self { + Self(format!("/znode-{uid}")) + } + + fn as_str(&self) -> &str { + &self.0 + } + + fn into_string(self) -> String { + self.0 + } +} + +/// What the cleanup step does with the znodes of a ZookeeperZnode that is being deleted. +#[derive(Debug, Eq, PartialEq)] +struct CleanupPlan<'a> { + /// The znode that is deleted recursively. + delete: DerivedZnodePath, + + /// The znode set through `status.znodePath`, if it differs from the derived one. + /// + /// The override exists to adopt existing data, such as a restored backup, so this znode is + /// kept in ZooKeeper. + keep: Option<&'a str>, +} + +impl<'a> CleanupPlan<'a> { + fn new(uid: &str, znode_path: &'a str) -> Self { + let delete = DerivedZnodePath::from_uid(uid); + let keep = (znode_path != delete.as_str()).then_some(znode_path); + Self { delete, keep } + } +} + +/// Tells the owner of `znode` that its overridden znode is kept in ZooKeeper. +/// +/// A failure to publish is only logged, so that it cannot block the removal of the finalizer. +async fn publish_kept_znode_event( + recorder: &Recorder, + znode: &v1alpha1::ZookeeperZnode, + kept_znode_path: &str, +) { + let event = Event { + type_: EventType::Warning, + reason: "ZnodeKept".to_owned(), + note: Some(format!( + "Kept the ZNode {kept_znode_path:?} in ZooKeeper, because it was set through \ + status.znodePath. Delete it manually if it is no longer needed." + )), + action: "Cleanup".to_owned(), + secondary: None, + }; + if let Err(error) = recorder.publish(&event, &znode.object_ref(&())).await { + warn!( + %error, + znode.path = kept_znode_path, + "Failed to publish the event about the kept ZNode" + ); + } +} + async fn reconcile_apply( client: &stackable_operator::client::Client, validated_znode: &validate::ValidatedZnode, @@ -295,7 +388,7 @@ async fn reconcile_cleanup( client: &stackable_operator::client::Client, dereferenced: &dereference::DereferencedObjects, zookeeper_security: &ZookeeperSecurity, - znode_path: &str, + znode_path: &DerivedZnodePath, ) -> Result { // Clean up znode from the ZooKeeper cluster before letting Kubernetes delete the object znode_mgmt::ensure_znode_missing( @@ -305,12 +398,12 @@ async fn reconcile_cleanup( zookeeper_security, &client.kubernetes_cluster_info, ), - znode_path, + znode_path.as_str(), ) .await .with_context(|_| EnsureZnodeMissingSnafu { zk: ObjectRef::from_obj(&dereferenced.zk), - znode_path, + znode_path: znode_path.as_str(), })?; // No need to delete the ConfigMap, since that has an OwnerReference on the ZookeeperZnode object Ok(controller::Action::await_change()) @@ -462,13 +555,41 @@ pub(crate) mod test_support { #[cfg(test)] mod tests { - use super::CONTROLLER_NAME; + use super::{CONTROLLER_NAME, CleanupPlan, DerivedZnodePath}; + + const UID: &str = "e5dbf9c2-d8b0-4c1e-9f4a-1d2e3f4a5b6c"; #[test] fn test_constants() { // Test that dereferencing the constants does not panic. let _ = *CONTROLLER_NAME; } + + #[test] + fn cleanup_deletes_the_derived_znode_path() { + assert_eq!( + CleanupPlan::new(UID, &format!("/znode-{UID}")), + CleanupPlan { + delete: DerivedZnodePath::from_uid(UID), + keep: None, + } + ); + } + + #[test] + fn cleanup_keeps_an_overridden_znode_path() { + // `status.znodePath` names someone else's znode, e.g. another ZookeeperZnode's path or + // a well-known one. Only the path derived from this object's uid may be deleted. + for overridden_path in ["/znode-0b5b8f8e-3d4c-4b59-8f10-6f1c2a3b4c5d", "/hbase", "/"] { + assert_eq!( + CleanupPlan::new(UID, overridden_path), + CleanupPlan { + delete: DerivedZnodePath::from_uid(UID), + keep: Some(overridden_path), + } + ); + } + } } mod znode_mgmt { diff --git a/tests/templates/kuttl/znode/30-assert.yaml b/tests/templates/kuttl/znode/30-assert.yaml new file mode 100644 index 00000000..1de79f7d --- /dev/null +++ b/tests/templates/kuttl/znode/30-assert.yaml @@ -0,0 +1,19 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +timeout: 300 +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: other-znode +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: overriding-znode +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: plain-znode diff --git a/tests/templates/kuttl/znode/30-install-znodes.yaml b/tests/templates/kuttl/znode/30-install-znodes.yaml new file mode 100644 index 00000000..f339e766 --- /dev/null +++ b/tests/templates/kuttl/znode/30-install-znodes.yaml @@ -0,0 +1,26 @@ +--- +# other-znode owns the data that must survive. overriding-znode later points its status.znodePath +# at it. plain-znode is the positive control without an override. +apiVersion: zookeeper.stackable.tech/v1alpha1 +kind: ZookeeperZnode +metadata: + name: other-znode +spec: + clusterRef: + name: test-zk +--- +apiVersion: zookeeper.stackable.tech/v1alpha1 +kind: ZookeeperZnode +metadata: + name: overriding-znode +spec: + clusterRef: + name: test-zk +--- +apiVersion: zookeeper.stackable.tech/v1alpha1 +kind: ZookeeperZnode +metadata: + name: plain-znode +spec: + clusterRef: + name: test-zk diff --git a/tests/templates/kuttl/znode/31-write-other-znode-data.yaml b/tests/templates/kuttl/znode/31-write-other-znode-data.yaml new file mode 100644 index 00000000..622d5ad1 --- /dev/null +++ b/tests/templates/kuttl/znode/31-write-other-znode-data.yaml @@ -0,0 +1,11 @@ +--- +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - script: | + set -euo pipefail + OTHER_PATH=$(kubectl get zookeeperznode other-znode -n "$NAMESPACE" -o jsonpath='{.status.znodePath}') + bash zk_cli.sh "$NAMESPACE" create "$OTHER_PATH/data" x + bash zk_cli.sh "$NAMESPACE" create "$OTHER_PATH/data/child" y + [ "$(bash znode_state.sh "$NAMESPACE" "$OTHER_PATH/data/child")" = exists ] + timeout: 120 diff --git a/tests/templates/kuttl/znode/32-delete-overriding-znode.yaml b/tests/templates/kuttl/znode/32-delete-overriding-znode.yaml new file mode 100644 index 00000000..d39a530f --- /dev/null +++ b/tests/templates/kuttl/znode/32-delete-overriding-znode.yaml @@ -0,0 +1,46 @@ +--- +# Deleting a ZookeeperZnode whose status.znodePath was overridden must keep the overridden ZNode +# (here: the ZNode of other-znode, with its data) and delete only the ZNode derived from its own +# uid. +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - script: | + set -euo pipefail + OTHER_PATH=$(kubectl get zookeeperznode other-znode -n "$NAMESPACE" -o jsonpath='{.status.znodePath}') + OWN_PATH=/znode-$(kubectl get zookeeperznode overriding-znode -n "$NAMESPACE" -o jsonpath='{.metadata.uid}') + echo "overridden path: $OTHER_PATH, own path: $OWN_PATH" + [ "$(bash znode_state.sh "$NAMESPACE" "$OWN_PATH")" = exists ] + + kubectl patch zookeeperznode overriding-znode -n "$NAMESPACE" --subresource=status --type=merge \ + -p "{\"status\":{\"znodePath\":\"$OTHER_PATH\"}}" + + # Wait until the operator has reconciled the override. + CHROOT= + for _ in $(seq 60); do + CHROOT=$(kubectl get configmap overriding-znode -n "$NAMESPACE" -o jsonpath='{.data.ZOOKEEPER_CHROOT}') + [ "$CHROOT" = "$OTHER_PATH" ] && break + sleep 2 + done + if [ "$CHROOT" != "$OTHER_PATH" ]; then + echo "[ERROR] The discovery ConfigMap never advertised the overridden path $OTHER_PATH" + exit 1 + fi + + kubectl delete zookeeperznode overriding-znode -n "$NAMESPACE" --wait --timeout=120s + + FAILED=0 + if [ "$(bash znode_state.sh "$NAMESPACE" "$OTHER_PATH/data/child")" != exists ]; then + echo "[ERROR] The overridden ZNode $OTHER_PATH was deleted together with its data" + FAILED=1 + fi + if [ "$(bash znode_state.sh "$NAMESPACE" "$OWN_PATH")" != missing ]; then + echo "[ERROR] The derived ZNode $OWN_PATH was left behind" + FAILED=1 + fi + if [ -z "$(kubectl get events -n "$NAMESPACE" --field-selector reason=ZnodeKept -o name)" ]; then + echo "[ERROR] No ZnodeKept event was emitted" + FAILED=1 + fi + exit "$FAILED" + timeout: 300 diff --git a/tests/templates/kuttl/znode/33-delete-plain-znode.yaml b/tests/templates/kuttl/znode/33-delete-plain-znode.yaml new file mode 100644 index 00000000..c02ec37d --- /dev/null +++ b/tests/templates/kuttl/znode/33-delete-plain-znode.yaml @@ -0,0 +1,17 @@ +--- +# Positive control: deleting a ZookeeperZnode without an override deletes its own ZNode. +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +commands: + - script: | + set -euo pipefail + PLAIN_PATH=$(kubectl get zookeeperznode plain-znode -n "$NAMESPACE" -o jsonpath='{.status.znodePath}') + [ "$(bash znode_state.sh "$NAMESPACE" "$PLAIN_PATH")" = exists ] + + kubectl delete zookeeperznode plain-znode -n "$NAMESPACE" --wait --timeout=120s + + if [ "$(bash znode_state.sh "$NAMESPACE" "$PLAIN_PATH")" != missing ]; then + echo "[ERROR] The ZNode $PLAIN_PATH was not deleted" + exit 1 + fi + timeout: 300 diff --git a/tests/templates/kuttl/znode/zk_cli.sh b/tests/templates/kuttl/znode/zk_cli.sh new file mode 100644 index 00000000..416c7fa4 --- /dev/null +++ b/tests/templates/kuttl/znode/zk_cli.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Usage: zk_cli.sh +# +# Runs one zkCli.sh command inside the ZooKeeper server Pod and prints its output. +set -euo pipefail + +NAMESPACE=$1 +shift + +# The script is single-quoted on purpose: it must be expanded by the shell inside the Pod, where +# zoo.cfg exists, not by the local one. +# shellcheck disable=SC2016 +kubectl exec -n "$NAMESPACE" test-zk-server-default-0 -c zookeeper -- bash -c ' + PORT=$(grep "^clientPort=" /stackable/rwconfig/zoo.cfg | cut -d= -f2) + /stackable/zookeeper/bin/zkCli.sh -server "localhost:${PORT}" "$@" 2>&1 +' zk_cli "$@" diff --git a/tests/templates/kuttl/znode/znode_state.sh b/tests/templates/kuttl/znode/znode_state.sh new file mode 100644 index 00000000..9c2739b7 --- /dev/null +++ b/tests/templates/kuttl/znode/znode_state.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Usage: znode_state.sh +# +# Prints "exists" or "missing" for the ZNode at , and fails if zkCli.sh gives neither +# answer (e.g. because ZooKeeper could not be reached), so that a missing ZNode is never confused +# with a failed lookup. +set -uo pipefail + +OUTPUT=$(bash "$(dirname "$0")/zk_cli.sh" "$1" stat "$2") + +if grep -q "cZxid" <<< "$OUTPUT"; then + echo exists +elif grep -q "Node does not exist" <<< "$OUTPUT"; then + echo missing +else + echo "[ERROR] Could not determine the state of ZNode $2:" >&2 + echo "$OUTPUT" >&2 + exit 1 +fi