gpu-operator icon indicating copy to clipboard operation
gpu-operator copied to clipboard

[Feature]: CEL validation rejecting reserved label keys in operand label maps

Open CloneOfAlex opened this issue 1 month ago • 4 comments

Motivation User label maps are merged into operand DaemonSets, and reserved keys (app, app.kubernetes.io/component, app.kubernetes.io/name, app.kubernetes.io/part-of) either break the selector or detach the operand from the code that finds it (#3059, NVIDIA/gpu-operator#2955). Today this is silent: the ClusterPolicy path drops such keys with a log line, and the NVIDIADriver/GPUCluster templates let them win.

Proposal Add x-kubernetes-validations on the label maps (NVIDIADriverSpec.Labels, GPUCluster daemonsets.labels, ClusterPolicy daemonsets.labels), for example:

// +kubebuilder:validation:XValidation:rule="!self.exists(k, k in ['app','app.kubernetes.io/component','app.kubernetes.io/name','app.kubernetes.io/part-of'])",message="reserved operand label keys cannot be set"

Ratcheting validation (GA in Kubernetes 1.33) lets existing objects keep reconciling; for ClusterPolicy it could start as a warning-only change. This is a lighter alternative to the admission webhook in NVIDIA/cloud-native-team#741 for this one check.

Related: NVIDIA/gpu-operator#3059, NVIDIA/gpu-operator#2955, NVIDIA/cloud-native-team#741, NVIDIA/gpu-operator#3066.

CloneOfAlex avatar Oct 13 '26 18:10 CloneOfAlex

@CloneOfAlex

Could you provide more details about the problem you encountered and your proposed solution?

francisguillier avatar Oct 19 '26 23:10 francisguillier

Thanks @francisguillier. To answer this properly I rendered every operand template with each proposed reserved key in the user label map. The results support the problem but change the proposal: the reserved list I proposed is too broad, it differs per CR, and two parts of the plan (a shared field marker, warning-only for ClusterPolicy) won't work with CRD CEL as described.

The problem

User label maps (NVIDIADriverSpec.Labels, GPUClusterSpec.Daemonsets.Labels, ClusterPolicySpec.Daemonsets.Labels) are merged into operand workloads. When a user key collides with an operator-owned key, the user value silently wins, through YAML last-wins in internal/render (#3068) or because a template doesn't filter the key. The result is either a broken selector (the workload can't be created/updated) or an operand the operator's own lookups can no longer find (#3059: upgrade controller, orphaned-pod detection, validator). Nothing tells the user. The ClusterPolicy path is the exception: applyCommonDaemonsetLabel (controllers/object_controls.go:810) keeps component and the pod-selector labels intact and logs. It still applies app/part-of to DaemonSet metadata.

What actually happens today

Here's the matrix from a render test against current main. It sets each key to user-value and compares against a render without it. "Not operator-owned" means the template doesn't set that key at all, so the user label is simply added.

CR / operand Workload User key Result
GPUCluster dcgm DaemonSet/nvidia-dcgm-dra app metadata overridden
GPUCluster dcgm DaemonSet/nvidia-dcgm-dra app.kubernetes.io/component protected (template filters it)
GPUCluster dcgm DaemonSet/nvidia-dcgm-dra app.kubernetes.io/name not operator-owned (user label simply added)
GPUCluster dcgm DaemonSet/nvidia-dcgm-dra app.kubernetes.io/part-of not operator-owned (user label simply added)
GPUCluster dcgm-exporter DaemonSet/nvidia-dcgm-exporter-dra app metadata overridden
GPUCluster dcgm-exporter DaemonSet/nvidia-dcgm-exporter-dra app.kubernetes.io/component protected (template filters it)
GPUCluster dcgm-exporter DaemonSet/nvidia-dcgm-exporter-dra app.kubernetes.io/name not operator-owned (user label simply added)
GPUCluster dcgm-exporter DaemonSet/nvidia-dcgm-exporter-dra app.kubernetes.io/part-of not operator-owned (user label simply added)
GPUCluster dra-driver DaemonSet/nvidia-dra-driver-kubelet-plugin app metadata overridden
GPUCluster dra-driver DaemonSet/nvidia-dra-driver-kubelet-plugin app.kubernetes.io/component metadata overridden, pod overridden
GPUCluster dra-driver DaemonSet/nvidia-dra-driver-kubelet-plugin app.kubernetes.io/name metadata overridden, pod overridden
GPUCluster dra-driver DaemonSet/nvidia-dra-driver-kubelet-plugin app.kubernetes.io/part-of not operator-owned (user label simply added)
GPUCluster dra-driver Deployment/nvidia-dra-driver-controller app metadata overridden
GPUCluster dra-driver Deployment/nvidia-dra-driver-controller app.kubernetes.io/component metadata overridden, pod overridden
GPUCluster dra-driver Deployment/nvidia-dra-driver-controller app.kubernetes.io/name metadata overridden, pod overridden
GPUCluster dra-driver Deployment/nvidia-dra-driver-controller app.kubernetes.io/part-of not operator-owned (user label simply added)
GPUCluster dra-validator DaemonSet/nvidia-dra-validator app metadata overridden
GPUCluster dra-validator DaemonSet/nvidia-dra-validator app.kubernetes.io/component metadata overridden, pod overridden
GPUCluster dra-validator DaemonSet/nvidia-dra-validator app.kubernetes.io/name metadata overridden, pod overridden, SELECTOR MISMATCH
GPUCluster dra-validator DaemonSet/nvidia-dra-validator app.kubernetes.io/part-of not operator-owned (user label simply added)
NVIDIADriver driver DaemonSet/nvidia-gpu-driver-ubuntu22.04-7c6d7bd86b app metadata overridden, pod overridden, SELECTOR MISMATCH
NVIDIADriver driver DaemonSet/nvidia-gpu-driver-ubuntu22.04-7c6d7bd86b app.kubernetes.io/component metadata overridden, pod overridden
NVIDIADriver driver DaemonSet/nvidia-gpu-driver-ubuntu22.04-7c6d7bd86b app.kubernetes.io/name not operator-owned (user label simply added)
NVIDIADriver driver DaemonSet/nvidia-gpu-driver-ubuntu22.04-7c6d7bd86b app.kubernetes.io/part-of not operator-owned (user label simply added)
Test (internal/state/reserved_label_matrix_test.go, observational, uses the existing GPUCluster/driver render helpers)
package state

import (
	"context"
	"fmt"
	"sort"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/labels"

	nvidiav1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1"
	nvidiav1alpha1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1alpha1"
	"github.com/NVIDIA/gpu-operator/internal/render"
)

var reservedLabelKeys = []string{
	"app",
	"app.kubernetes.io/component",
	"app.kubernetes.io/name",
	"app.kubernetes.io/part-of",
}

// workloadLabels extracts metadata labels, pod-template labels and the selector
// from a rendered DaemonSet or Deployment.
func workloadLabels(t *testing.T, o *unstructured.Unstructured) (meta, pod, sel map[string]string) {
	t.Helper()
	meta = o.GetLabels()
	pod, _, _ = unstructured.NestedStringMap(o.Object, "spec", "template", "metadata", "labels")
	sel, _, _ = unstructured.NestedStringMap(o.Object, "spec", "selector", "matchLabels")
	return
}

// describeOverride reports what a user-supplied reserved key did to one workload.
func describeOverride(t *testing.T, base, withKey *unstructured.Unstructured, key string) string {
	bm, bp, _ := workloadLabels(t, base)
	m, p, sel := workloadLabels(t, withKey)
	var out []string
	if _, owned := bm[key]; owned && m[key] == "user-value" {
		out = append(out, "metadata overridden")
	}
	if _, owned := bp[key]; owned && p[key] == "user-value" {
		out = append(out, "pod overridden")
	}
	if !labels.SelectorFromSet(sel).Matches(labels.Set(p)) {
		out = append(out, "SELECTOR MISMATCH")
	}
	if len(out) == 0 {
		_, ownedMeta := bm[key]
		_, ownedPod := bp[key]
		if !ownedMeta && !ownedPod {
			return "not operator-owned (user label simply added)"
		}
		return "protected (template filters it)"
	}
	return strings.Join(out, ", ")
}

func workloads(objs []*unstructured.Unstructured) map[string]*unstructured.Unstructured {
	w := map[string]*unstructured.Unstructured{}
	for _, o := range objs {
		if o.GetKind() == "DaemonSet" || o.GetKind() == "Deployment" {
			w[o.GetKind()+"/"+o.GetName()] = o
		}
	}
	return w
}

// TestReservedLabelKeyMatrix renders every GPUCluster operand and the NVIDIADriver
// DaemonSet with each reserved key set in the user label map, and logs what happens
// to the operator-owned value. Observational: it documents current behavior.
func TestReservedLabelKeyMatrix(t *testing.T) {
	var rows []string

	gpuClusterStates := map[string]interface {
		getManifestObjects(context.Context, *nvidiav1alpha1.GPUCluster, InfoCatalog) ([]*unstructured.Unstructured, error)
	}{
		"GPUCluster dcgm":          newTestDCGMState(t),
		"GPUCluster dcgm-exporter": newTestDCGMExporterState(t, false),
		"GPUCluster dra-validator": newTestDRAValidationState(t),
		"GPUCluster dra-driver":    newTestDRAState(t),
	}
	gpuClusterRender := func(s interface {
		getManifestObjects(context.Context, *nvidiav1alpha1.GPUCluster, InfoCatalog) ([]*unstructured.Unstructured, error)
	}, lbls map[string]string) []*unstructured.Unstructured {
		cr := sampleGPUCluster()
		cr.Spec.DCGM = &nvidiav1.DCGMSpec{Enabled: new(true)}
		cr.Spec.DCGMExporter = &nvidiav1.DCGMExporterSpec{Enabled: new(true)}
		cr.Spec.DRADriver.ComputeDomains.Enabled = new(true)
		cr.Spec.Daemonsets.Labels = lbls
		objs, err := s.getManifestObjects(context.Background(), cr, draSupportedCatalog())
		require.NoError(t, err)
		return objs
	}
	for name, s := range gpuClusterStates {
		base := workloads(gpuClusterRender(s, nil))
		for _, key := range reservedLabelKeys {
			got := workloads(gpuClusterRender(s, map[string]string{key: "user-value"}))
			for wName, w := range got {
				rows = append(rows, fmt.Sprintf("%-26s %-58s %-28s %s", name, wName, key, describeOverride(t, base[wName], w, key)))
			}
		}
	}

	st, err := NewStateDriver(nil, "", nil, manifestDir)
	require.NoError(t, err)
	driver := st.(*stateDriver)
	driverRender := func(lbls map[string]string) []*unstructured.Unstructured {
		d := getMinimalDriverRenderData()
		d.Driver.Spec.Labels = lbls
		objs, err := driver.renderer.RenderObjects(&render.TemplatingData{Data: d})
		require.NoError(t, err)
		return objs
	}
	base := workloads(driverRender(nil))
	for _, key := range reservedLabelKeys {
		for wName, w := range workloads(driverRender(map[string]string{key: "user-value"})) {
			rows = append(rows, fmt.Sprintf("%-26s %-58s %-28s %s", "NVIDIADriver driver", wName, key, describeOverride(t, base[wName], w, key)))
		}
	}

	sort.Strings(rows)
	for _, r := range rows {
		t.Log(r)
	}
}

Takeaways:

  • Real breakage: app on NVIDIADriver and app.kubernetes.io/name on the DRA validator produce a selector/template mismatch, so the API server rejects the workload. app.kubernetes.io/component overrides discovery labels on the driver and all DRA workloads. app overrides DaemonSet/Deployment metadata on every GPUCluster operand (pod labels are filtered there).
  • The templates are inconsistent: dcgm/dcgm-exporter filter component from both metadata and pod labels, while dra-driver/dra-validator filter only app/part-of from pod labels and nothing from metadata.
  • app.kubernetes.io/part-of is never operator-owned on these paths, and app.kubernetes.io/name is owned only by the DRA workloads. Rejecting them everywhere, as I originally proposed, would block harmless and common labels. part-of in particular is a recommended label people set organization-wide, and the ClusterPolicy path deliberately applies it to DaemonSet metadata today.

Corrections to the proposal

  1. The reserved set should be per CR and match ownership: app and app.kubernetes.io/component for NVIDIADriver; add app.kubernetes.io/name for GPUCluster (DRA workloads). Not part-of.
  2. GPUCluster and ClusterPolicy share the same Go type. GPUClusterSpec.Daemonsets is nvidiav1.DaemonsetsSpec, so a marker on DaemonsetsSpec.Labels lands in both CRDs. To scope it to GPUCluster, the rule has to live on GPUClusterSpec instead:
    // +kubebuilder:validation:XValidation:rule="!has(self.daemonsets) || !has(self.daemonsets.labels) || (!('app' in self.daemonsets.labels) && !('app.kubernetes.io/component' in self.daemonsets.labels) && !('app.kubernetes.io/name' in self.daemonsets.labels))",message="daemonsets.labels must not set reserved operand label keys: app, app.kubernetes.io/component, app.kubernetes.io/name"
    
    For NVIDIADriver, a field-level marker on Labels works: !('app' in self) && !('app.kubernetes.io/component' in self). Map-key membership has constant estimated cost, so no maxProperties is needed. (I haven't run controller-gen on these; the tool isn't available in my environment, so the exact rule text needs a make manifests check.)
  3. CRD CEL rules have no warning mode. x-kubernetes-validations always rejects, so "ClusterPolicy warning-only" isn't possible through this mechanism. ClusterPolicy already handles these keys safely at reconcile time. If a user-visible signal is wanted there, options are a status condition/event from applyCommonDaemonsetLabel, or a chart-shipped ValidatingAdmissionPolicy with validationActions: [Warn]. I'd leave ClusterPolicy out of this change.
  4. Ratcheting helps less than I implied. It applies per field, and the label map is one field. An existing object that already contains a reserved key keeps reconciling as long as the map is untouched, but any edit to that map (even adding an unrelated label) gets rejected until the reserved key is removed. Users should be told that in the release notes. And on clusters older than the version where ratcheting is enabled, an existing object becomes un-updatable as soon as it's edited at all.

Proposed order

  1. Make the templates consistent: filter operator-owned keys from both metadata and pod labels in every operand template (this is NVIDIA/gpu-operator#3059's fix for NVIDIADriver, plus the DRA templates). That fixes the breakage for existing objects without rejecting anything.
  2. Add the CEL rules for NVIDIADriver and GPUCluster with the narrowed key sets, so new specs get immediate feedback instead of a silently filtered label.
  3. Keep this matrix as a regression test, with assertions instead of logging.

I'm happy to send step 1 for the DRA templates (and coordinate with whoever picks up NVIDIA/gpu-operator#3059 for the driver template), then step 2.

CloneOfAlex avatar Oct 20 '26 16:10 CloneOfAlex

@CloneOfAlex

I’m not sure I understand the deployment problem you’re trying to solve. Could you please provide:

  • Issue summary: What is happening, and what behavior do you expect?
  • Steps to reproduce: Include the relevant environment details and configuration.
  • Proposed fix: Explain how the fix addresses the problem. Without these details, we won’t be able to assess the issue and will close it. Thanks

francisguillier avatar Nov 05 '26 22:11 francisguillier

@francisguillier here it is in that format. One correction first: the NVIDIADriver rows in my matrix above are wrong. That test skipped getDriverSpec(), which already strips app and app.kubernetes.io/* (see #3059). This issue only applies to GPUCluster.

Issue summary On a GPUCluster, a user label in spec.daemonsets.labels that collides with an operator-owned key silently wins. With app.kubernetes.io/name, the nvidia-dra-validator DaemonSet's pod template label no longer matches its selector (matchLabels: app.kubernetes.io/name: nvidia-dra-validator), so the API server rejects the DaemonSet and DRA validation never runs. Expected: the operator's labels win, or the spec is rejected at admission with a clear message.

Steps to reproduce

  1. Install the operator with DRA / GPUCluster enabled (main @ a0a3651).
  2. Create a GPUCluster with spec.daemonsets.labels: {app.kubernetes.io/name: my-team}.
  3. The state-dra-validation state fails to apply: the DaemonSet is rejected with selector does not match template labels. Cause: manifests/state-dra-validation/*daemonset*.yaml filters only app and app.kubernetes.io/part-of from the pod labels, so the user's key overrides the selector key (YAML last-wins, #3068).

To be transparent: the render result comes from a unit test against main. I haven't run it on a cluster.

Proposed fix

  1. In the GPUCluster templates, filter operator-owned keys from both metadata and pod labels (this overlaps #2973).
  2. Add a CEL rule on GPUClusterSpec, not on the shared DaemonsetsSpec, so ClusterPolicy is unaffected. It rejects app, app.kubernetes.io/component and app.kubernetes.io/name in daemonsets.labels, so users get an immediate error instead of a failed state.

If #2973 already covers step 1, I'm fine folding this into it.

CloneOfAlex avatar Nov 05 '26 23:11 CloneOfAlex