diff --git a/CHANGELOG.md b/CHANGELOG.md index c9436caaf..90d064996 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ All notable changes to this project will be documented in this file. See [our internal issue](https://github.com/stackabletech/hdfs-operator/issues/626) and [the fix](https://github.com/kube-rs/kube/pull/2042) for details ([#925]). - `S3Connection`s without a `tls` section are accepted again and configured as `s3.endpoint=http://...`. Trino's native S3 file system takes the transport from the endpoint scheme, so requiring TLS was never necessary ([#928]). +- The operator now watches all resources that it creates and early-exits the reconcile action when the + cluster is marked for deletion ([#934]). [#909]: https://github.com/stackabletech/trino-operator/pull/909 [#913]: https://github.com/stackabletech/trino-operator/pull/913 @@ -43,6 +45,7 @@ All notable changes to this project will be documented in this file. [#925]: https://github.com/stackabletech/trino-operator/pull/925 [#928]: https://github.com/stackabletech/trino-operator/pull/928 [#932]: https://github.com/stackabletech/trino-operator/pull/932 +[#934]: https://github.com/stackabletech/trino-operator/pull/934 ## [26.7.0] - 2026-07-21 diff --git a/deploy/helm/trino-operator/templates/clusterrole-operator.yaml b/deploy/helm/trino-operator/templates/clusterrole-operator.yaml index 6e14e6969..e96c146da 100644 --- a/deploy/helm/trino-operator/templates/clusterrole-operator.yaml +++ b/deploy/helm/trino-operator/templates/clusterrole-operator.yaml @@ -13,13 +13,15 @@ rules: - nodes/proxy verbs: - get - # Manage core workload resources created per TrinoCluster. - # All resources are applied via Server-Side Apply (create + patch) and tracked for - # orphan cleanup (list + delete). + # Manage core workload resources created per TrinoCluster (the ServiceAccount + # provides workload pod identity). All resources are applied via Server-Side Apply + # (create + patch), tracked for orphan cleanup (list + delete) and watched by the + # controller. - apiGroups: - "" resources: - configmaps + - serviceaccounts - services verbs: - create @@ -28,18 +30,6 @@ rules: - list - patch - watch - # ServiceAccount created per TrinoCluster for workload pod identity. - # Applied via SSA and tracked for orphan cleanup. - - apiGroups: - - "" - resources: - - serviceaccounts - verbs: - - create - - delete - - get - - list - - patch # Shared internal authentication secrets (communication key and spooling secret). # Delete is needed to migrate immutable secrets to mutable ones. # Orphan cleanup not needed (instead, Kubernetes GC via owner reference). @@ -53,7 +43,8 @@ rules: - get - patch # RoleBinding created per TrinoCluster to bind the product ClusterRole to the workload - # ServiceAccount. Applied via SSA and tracked for orphan cleanup. + # ServiceAccount. Applied via SSA and tracked for orphan cleanup and watched by the + # controller. - apiGroups: - rbac.authorization.k8s.io resources: @@ -64,6 +55,7 @@ rules: - get - list - patch + - watch # Required to bind the product ClusterRole to the per-cluster ServiceAccount. - apiGroups: - rbac.authorization.k8s.io @@ -86,7 +78,8 @@ rules: - list - patch - watch - # PodDisruptionBudget created per role. Applied via SSA and tracked for orphan cleanup. + # PodDisruptionBudget created per role. Applied via SSA and tracked for orphan cleanup + # and watched by the controller. - apiGroups: - policy resources: @@ -97,6 +90,7 @@ rules: - get - list - patch + - watch # Required for maintaining the CRDs within the operator (including the conversion webhook info). # Also for the startup condition check before the controller can run. - apiGroups: @@ -114,7 +108,7 @@ rules: - list - watch # Listener created per role group for external access. Applied via SSA and tracked for orphan - # cleanup. + # cleanup and watched by the controller. - apiGroups: - listeners.stackable.tech resources: @@ -125,6 +119,7 @@ rules: - get - list - patch + - watch # Required to report reconciliation results and warnings back to the TrinoCluster object. - apiGroups: - events.k8s.io diff --git a/rust/operator-binary/src/main.rs b/rust/operator-binary/src/main.rs index 80cb9b2d0..415981636 100644 --- a/rust/operator-binary/src/main.rs +++ b/rust/operator-binary/src/main.rs @@ -9,11 +9,13 @@ use futures::{FutureExt, TryFutureExt, stream::StreamExt}; use stackable_operator::{ YamlSchema, cli::{Command, RunArguments}, - crd::authentication::core, + crd::{authentication::core, listener}, eos::EndOfSupportChecker, k8s_openapi::api::{ apps::v1::StatefulSet, - core::v1::{ConfigMap, Service}, + core::v1::{ConfigMap, Service, ServiceAccount}, + policy::v1::PodDisruptionBudget, + rbac::v1::RoleBinding, }, kube::{ CustomResourceExt as _, ResourceExt, @@ -137,16 +139,33 @@ async fn main() -> anyhow::Result<()> { let config_map_cluster_store = cluster_controller.store(); let trino_controller = cluster_controller + .owns( + watch_namespace.get_api::>(&client), + watcher::Config::default(), + ) + .owns( + watch_namespace + .get_api::>(&client), + watcher::Config::default(), + ) + .owns( + watch_namespace.get_api::>(&client), + watcher::Config::default(), + ) + .owns( + watch_namespace.get_api::>(&client), + watcher::Config::default(), + ) .owns( watch_namespace.get_api::>(&client), watcher::Config::default(), ) .owns( - watch_namespace.get_api::>(&client), + watch_namespace.get_api::>(&client), watcher::Config::default(), ) .owns( - watch_namespace.get_api::>(&client), + watch_namespace.get_api::>(&client), watcher::Config::default(), ) .watches( diff --git a/rust/operator-binary/src/trino_controller.rs b/rust/operator-binary/src/trino_controller.rs index 98da19edc..ca6339046 100644 --- a/rust/operator-binary/src/trino_controller.rs +++ b/rust/operator-binary/src/trino_controller.rs @@ -14,6 +14,7 @@ use stackable_operator::{ cluster_resources::ClusterResourceApplyStrategy, constant, kube::{ + Resource, core::{DeserializeGuard, error_boundary}, runtime::controller::Action, }, @@ -89,6 +90,10 @@ pub async fn reconcile_trino( ) -> Result { tracing::info!("Starting reconcile"); + if trino.meta().deletion_timestamp.is_some() { + return Ok(Action::await_change()); + } + let trino = trino .0 .as_ref() @@ -155,8 +160,12 @@ mod tests { use std::str::FromStr; use stackable_operator::{ - cli::OperatorEnvironmentOptions, commons::networking::DomainName, - k8s_openapi::api::core::v1::ConfigMap, utils::cluster_info::KubernetesClusterInfo, + cli::OperatorEnvironmentOptions, + client::Client, + commons::networking::DomainName, + k8s_openapi::api::core::v1::ConfigMap, + kube::{Client as KubeClient, Config}, + utils::cluster_info::KubernetesClusterInfo, v2::builder::pod::container::EnvVarName, }; @@ -489,4 +498,54 @@ mod tests { assert_eq!(value("GROUP_VAR").as_deref(), Some("group-value")); assert_eq!(value("ROLE_VAR").as_deref(), Some("role-value")); } + + /// The client points at a closed port, so any API call would fail the reconciliation: an `Ok` + /// proves that a cluster being deleted returns before the reconciler touches the Kubernetes + /// API, and because the spec is invalid, before the [`DeserializeGuard`] is unwrapped. + #[test] + fn reconcile_exits_early_for_deleted_cluster() { + let trino = serde_yaml::from_str( + r#" +apiVersion: trino.stackable.tech/v1alpha1 +kind: TrinoCluster +metadata: + name: trino + namespace: default + deletionTimestamp: "2026-08-14T12:00:00Z" +spec: {} +"#, + ) + .expect("YAML parses; the invalid spec is captured inside the DeserializeGuard"); + + let action = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current-thread tokio runtime") + .block_on(async { + let ctx = Arc::new(Ctx { + client: Client::new( + KubeClient::try_from(Config::new( + "http://127.0.0.1:1".parse().expect("valid static URI"), + )) + .expect("client from static config"), + None, + "default".to_owned(), + KubernetesClusterInfo { + cluster_domain: DomainName::from_str("cluster.local") + .expect("valid cluster domain"), + }, + ), + operator_environment: OperatorEnvironmentOptions { + operator_namespace: "stackable-operators".to_owned(), + operator_service_name: "trino-operator".to_owned(), + image_repository: "oci.stackable.tech/sdp".to_owned(), + }, + }); + + reconcile_trino(Arc::new(trino), ctx).await + }) + .expect("a deleted cluster reconciles without any API call"); + + assert_eq!(action, Action::await_change()); + } } diff --git a/tests/templates/kuttl/cluster-operation/50-assert.yaml b/tests/templates/kuttl/cluster-operation/50-assert.yaml new file mode 100644 index 000000000..d20f19f60 --- /dev/null +++ b/tests/templates/kuttl/cluster-operation/50-assert.yaml @@ -0,0 +1,107 @@ +--- +# The recreated StatefulSets must bring the cluster back to ready, and the recreated +# objects must carry an owner reference back to the TrinoCluster so that garbage +# collection still works for them. +apiVersion: kuttl.dev/v1beta1 +kind: TestAssert +metadata: + name: recreate-owned-resources +timeout: 600 +commands: + - script: kubectl -n $NAMESPACE wait --for=condition=available trinoclusters.trino.stackable.tech/trino --timeout 601s +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: trino-coordinator-default + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +status: + readyReplicas: 1 + replicas: 1 +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: trino-worker-default + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +status: + readyReplicas: 1 + replicas: 1 +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: trino-serviceaccount + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: trino-rolebinding + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: trino-coordinator + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: trino-worker + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: listeners.stackable.tech/v1alpha1 +kind: Listener +metadata: + name: trino-coordinator + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: v1 +kind: Service +metadata: + name: trino-coordinator-default-headless + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino +--- +apiVersion: v1 +kind: Service +metadata: + name: trino-worker-default-headless + ownerReferences: + - apiVersion: trino.stackable.tech/v1alpha1 + controller: true + kind: TrinoCluster + name: trino diff --git a/tests/templates/kuttl/cluster-operation/50-delete-owned-resources.yaml b/tests/templates/kuttl/cluster-operation/50-delete-owned-resources.yaml new file mode 100644 index 000000000..eaaf3c5d2 --- /dev/null +++ b/tests/templates/kuttl/cluster-operation/50-delete-owned-resources.yaml @@ -0,0 +1,66 @@ +--- +# Every resource the operator applies carries an ownerReference and a `.owns()` watch +# (main.rs): deleting it must trigger a reconcile of the TrinoCluster that re-applies it, +# proving the `.owns()` routing and the ClusterRole `watch` verbs end to end. +# `.watches()` registrations (AuthenticationClasses, TrinoCatalogs and +# referenced-but-unowned ConfigMaps) can't be tested this way: the operator never +# recreates what it didn't apply. +# +# Resources are discovered by label (ClusterResources::add enforces the labels on +# everything the operator applies), so new resources and kinds are covered +# automatically. Labels over-match on derived objects, so each match must also carry +# a controller ownerReference pointing at the TrinoCluster; kinds that can never pass +# that gate are excluded up front. Recreation is proven by UID change, and a floor +# guard catches a selector that silently matches nothing. +# +# Secrets are excluded: the internal shared Secret is deliberately not +# `.owns()`-registered (the ClusterRole intentionally grants no `list`/`watch` on +# Secrets), so deleting it would not trigger a recreation. +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +metadata: + name: delete-owned-resources +timeout: 300 +commands: + - script: | + set -eu + + delete_and_await_recreation() { + resource=$1 + old_uid=$(kubectl get -n "$NAMESPACE" "$resource" -o jsonpath='{.metadata.uid}') + kubectl delete -n "$NAMESPACE" "$resource" --wait=false + # Recreation is a single reconcile away, so this normally succeeds on the + # first iteration; 30s is a generous upper bound well below the step timeout. + for _ in $(seq 1 30); do + new_uid=$(kubectl get -n "$NAMESPACE" "$resource" -o jsonpath='{.metadata.uid}' 2>/dev/null || true) + if [ -n "$new_uid" ] && [ "$new_uid" != "$old_uid" ]; then + return 0 + fi + sleep 1 + done + echo "$resource was not recreated (old uid: $old_uid, current: '${new_uid:-}')" >&2 + return 1 + } + + selector="app.kubernetes.io/instance=trino,app.kubernetes.io/managed-by=trino.stackable.tech_trinocluster" + excluded="^(pods|persistentvolumeclaims|endpoints|events|secrets)$|^endpointslices\.|^controllerrevisions\.|^events\." + + deleted=0 + for kind in $(kubectl api-resources --verbs=list --namespaced -o name | grep -Ev "$excluded" | sort); do + for resource in $(kubectl get -n "$NAMESPACE" "$kind" -l "$selector" -o name 2>/dev/null); do + owner=$(kubectl get -n "$NAMESPACE" "$resource" -o jsonpath='{.metadata.ownerReferences[?(@.controller==true)].kind}/{.metadata.ownerReferences[?(@.controller==true)].name}' 2>/dev/null || true) + if [ "$owner" != "TrinoCluster/trino" ]; then + echo "skipping $resource: controller owner is '${owner:-none}', not the TrinoCluster" + continue + fi + delete_and_await_recreation "$resource" + deleted=$((deleted + 1)) + done + done + + # Guard against the sweep silently matching nothing (wrong selector, renamed + # labels): the fixture is known to produce well over this many owned resources. + if [ "$deleted" -lt 8 ]; then + echo "only $deleted labelled resources were swept - the label selector is broken" >&2 + exit 1 + fi