Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions rust/operator-binary/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
143 changes: 132 additions & 11 deletions rust/operator-binary/src/znode_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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<Recorder>,
}

#[derive(Snafu, Debug, EnumDiscriminants)]
Expand Down Expand Up @@ -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<v1alpha1::ZookeeperZnodeStatus> = 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");
Expand All @@ -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"
Expand Down Expand Up @@ -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, .. }) => {
Expand All @@ -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
}
}
},
Expand All @@ -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,
Expand Down Expand Up @@ -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<controller::Action> {
// Clean up znode from the ZooKeeper cluster before letting Kubernetes delete the object
znode_mgmt::ensure_znode_missing(
Expand All @@ -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())
Expand Down Expand Up @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions tests/templates/kuttl/znode/30-assert.yaml
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions tests/templates/kuttl/znode/30-install-znodes.yaml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions tests/templates/kuttl/znode/31-write-other-znode-data.yaml
Original file line number Diff line number Diff line change
@@ -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
46 changes: 46 additions & 0 deletions tests/templates/kuttl/znode/32-delete-overriding-znode.yaml
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions tests/templates/kuttl/znode/33-delete-plain-znode.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading