• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NVIDIA / gpu-operator / 30407245132

28 Jul 2026 11:11PM UTC coverage: 37.789% (+1.9%) from 35.938%
30407245132

push

github

abrarshivani
Add unit tests for internal/validator Validate error paths

Cover the driver-list failure, an invalid nodeSelector on a listed driver,
and the node-list failure, using fake-client interceptors. internal/validator
reaches 100% statement coverage.

Signed-off-by: Abrar Shivani <ashivani@nvidia.com>

5507 of 14573 relevant lines covered (37.79%)

0.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.79
/controllers/gpucluster_controller.go
1
/**
2
# Copyright (c) NVIDIA CORPORATION.  All rights reserved.
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
**/
16

17
package controllers
18

19
import (
20
        "context"
21
        "fmt"
22
        "strings"
23
        "time"
24

25
        appsv1 "k8s.io/api/apps/v1"
26
        corev1 "k8s.io/api/core/v1"
27
        apierrors "k8s.io/apimachinery/pkg/api/errors"
28
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
29
        "k8s.io/apimachinery/pkg/runtime"
30
        "k8s.io/apimachinery/pkg/types"
31
        "k8s.io/client-go/tools/events"
32
        "k8s.io/client-go/util/workqueue"
33
        ctrl "sigs.k8s.io/controller-runtime"
34
        "sigs.k8s.io/controller-runtime/pkg/client"
35
        "sigs.k8s.io/controller-runtime/pkg/controller"
36
        "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
37
        "sigs.k8s.io/controller-runtime/pkg/handler"
38
        "sigs.k8s.io/controller-runtime/pkg/log"
39
        "sigs.k8s.io/controller-runtime/pkg/predicate"
40
        "sigs.k8s.io/controller-runtime/pkg/reconcile"
41
        "sigs.k8s.io/controller-runtime/pkg/source"
42

43
        gpuv1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1"
44
        nvidiav1alpha1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1alpha1"
45
        "github.com/NVIDIA/gpu-operator/controllers/clusterinfo"
46
        "github.com/NVIDIA/gpu-operator/internal/conditions"
47
        "github.com/NVIDIA/gpu-operator/internal/consts"
48
        "github.com/NVIDIA/gpu-operator/internal/state"
49
        "github.com/NVIDIA/gpu-operator/internal/utils"
50
)
51

52
// gpuClusterFinalizer holds the GPUCluster until reconcileDelete has ordered teardown.
53
const gpuClusterFinalizer = "gpucluster.nvidia.com/dra-resourceclaim"
54

55
// draAdminNamespaceLabelKey is the label the kube-scheduler requires on a namespace
56
// before it allows adminAccess: true in ResourceClaim/ResourceClaimTemplate objects.
57
const draAdminNamespaceLabelKey = "resource.kubernetes.io/admin-access"
58

59
// GPUClusterReconciler reconciles a GPUCluster object
60
type GPUClusterReconciler struct {
61
        client.Client
62
        Scheme      *runtime.Scheme
63
        ClusterInfo clusterinfo.Interface
64
        Namespace   string
65

66
        stateManager     state.Manager
67
        conditionUpdater conditions.Updater
68
        recorder         events.EventRecorder
69
}
70

71
//+kubebuilder:rbac:groups=nvidia.com,resources=gpuclusters,verbs=get;list;watch;create;update;patch;delete
72
//+kubebuilder:rbac:groups=nvidia.com,resources=gpuclusters/status,verbs=get;update;patch
73
//+kubebuilder:rbac:groups=nvidia.com,resources=gpuclusters/finalizers,verbs=update
74
//+kubebuilder:rbac:groups=nvidia.com,resources=clusterpolicies,verbs=get;list;watch
75
//+kubebuilder:rbac:groups="",resources=namespaces,verbs=get;update;patch
76
//+kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
77
//+kubebuilder:rbac:groups=resource.k8s.io,resources=resourceclaimtemplates,verbs=get;list;watch;create;update;delete
78

79
func (r *GPUClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
1✔
80
        logger := log.FromContext(ctx)
1✔
81
        logger.V(consts.LogLevelInfo).Info("Reconciling GPUCluster")
1✔
82

1✔
83
        instance := &nvidiav1alpha1.GPUCluster{}
1✔
84
        if err := r.Get(ctx, req.NamespacedName, instance); err != nil {
2✔
85
                if apierrors.IsNotFound(err) {
2✔
86
                        // Deleted; owned objects are garbage-collected, so there is nothing to clean up.
1✔
87
                        return ctrl.Result{}, nil
1✔
88
                }
1✔
89
                // instance was not populated by the failed Get, so there is no object to
90
                // update status on; just surface the error for requeue.
91
                logger.Error(err, "error getting GPUCluster object")
×
92
                return ctrl.Result{}, fmt.Errorf("error getting GPUCluster object: %w", err)
×
93
        }
94

95
        if !instance.DeletionTimestamp.IsZero() {
2✔
96
                return r.reconcileDelete(ctx, instance)
1✔
97
        }
1✔
98

99
        if err := utils.EnsureFinalizer(ctx, r.Client, instance, gpuClusterFinalizer); err != nil {
1✔
100
                return ctrl.Result{}, fmt.Errorf("error adding finalizer to GPUCluster %s: %w", req.NamespacedName, err)
×
101
        }
×
102

103
        // GPUCluster (DRA stack) may coexist with a ClusterPolicy (device-plugin
104
        // stack): every operand DaemonSet of both stacks gates on the per-node
105
        // nvidia.com/gpu-operator.resource-allocation.mode label, so each node is served by exactly one stack.
106

107
        // No singleton claim is needed: the CRD's CEL rule pins metadata.name, so at most
108
        // one GPUCluster can exist.
109

110
        // DRA requires all driver management through NVIDIADriver CRs: surface an unmet
111
        // prerequisite on this CR's status and hold off deploying operands until it is met.
112
        if msg, err := r.validatePrerequisites(ctx); err != nil {
1✔
113
                return ctrl.Result{}, err
×
114
        } else if msg != "" {
2✔
115
                logger.V(consts.LogLevelWarning).Info("GPUCluster prerequisite not met", "reason", msg)
1✔
116
                if err := r.updateCRStatus(ctx, instance, nvidiav1alpha1.NotReady); err != nil {
1✔
117
                        return ctrl.Result{}, err
×
118
                }
×
119
                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.PrerequisiteNotMet, msg); condErr != nil {
1✔
120
                        logger.Error(condErr, "failed to set condition")
×
121
                }
×
122
                return ctrl.Result{RequeueAfter: time.Minute}, nil
1✔
123
        }
124

125
        // The operand states render ResourceClaimTemplates with adminAccess: true, which the
126
        // kube-scheduler only admits from a labeled namespace; label it before syncing states.
127
        if err := r.ensureAdminAccessLabel(ctx); err != nil {
1✔
128
                return ctrl.Result{}, fmt.Errorf("failed to label namespace for admin access: %w", err)
×
129
        }
×
130

131
        infoCatalog := state.NewInfoCatalog()
1✔
132
        infoCatalog.Add(state.InfoTypeClusterInfo, r.ClusterInfo)
1✔
133

1✔
134
        managerStatus := r.stateManager.SyncState(ctx, instance, infoCatalog)
1✔
135

1✔
136
        if err := r.updateCRStatus(ctx, instance, nvidiav1alpha1.State(managerStatus.Status)); err != nil {
1✔
137
                return ctrl.Result{}, err
×
138
        }
×
139

140
        if managerStatus.Status != state.SyncStateReady {
1✔
141
                logger.Info("GPUCluster instance is not ready")
×
142
                for _, result := range managerStatus.StatesStatus {
×
143
                        if result.Status != state.SyncStateReady && result.ErrInfo != nil {
×
144
                                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.ReconcileFailed, fmt.Sprintf("Error syncing state %s: %v", result.StateName, result.ErrInfo)); condErr != nil {
×
145
                                        logger.Error(condErr, "failed to set condition")
×
146
                                }
×
147
                                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
×
148
                        }
149
                }
150
                // no state reported an error, so we are waiting on operand pods
151
                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.OperandNotReady, "Waiting for operand pods to be ready"); condErr != nil {
×
152
                        logger.Error(condErr, "failed to set condition")
×
153
                }
×
154
                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
×
155
        }
156

157
        if condErr := r.conditionUpdater.SetConditionsReady(ctx, instance, conditions.Reconciled, "All resources have been successfully reconciled"); condErr != nil {
1✔
158
                logger.Error(condErr, "failed to set condition")
×
159
                return ctrl.Result{}, condErr
×
160
        }
×
161
        // Resync periodically so out-of-band changes (a deleted DeviceClass/VAP, or a
162
        // newly-created ClusterPolicy) are detected and reconciled even while ready;
163
        // only DaemonSets are watched, and the ready path is otherwise event-driven.
164
        return ctrl.Result{RequeueAfter: time.Minute}, nil
1✔
165
}
166

167
// validatePrerequisites checks the cross-CR rules that gate DRA enablement, returning
168
// a message describing the first unmet prerequisite or an empty string when all are met.
169
func (r *GPUClusterReconciler) validatePrerequisites(ctx context.Context) (string, error) {
1✔
170
        clusterPolicies := &gpuv1.ClusterPolicyList{}
1✔
171
        if err := r.List(ctx, clusterPolicies); err != nil {
1✔
172
                return "", fmt.Errorf("error listing ClusterPolicy objects: %w", err)
×
173
        }
×
174
        // Only the active singleton ClusterPolicy matters here: an Ignored instance
175
        // deploys nothing, so it cannot own driver daemonsets.
176
        if active := getSingletonClusterPolicy(clusterPolicies.Items); active != nil && !active.Spec.Driver.UseNvidiaDriverCRDType() {
2✔
177
                return fmt.Sprintf("ClusterPolicy %s does not have driver.useNvidiaDriverCRD enabled; migrate driver management to NVIDIADriver CRs before enabling DRA", active.Name), nil
1✔
178
        }
1✔
179
        return "", nil
1✔
180
}
181

182
// ensureAdminAccessLabel patches the operator namespace with the label required by the
183
// kube-scheduler to allow adminAccess: true in ResourceClaim/ResourceClaimTemplate
184
// objects. The label is deliberately never removed: it is namespace-level configuration
185
// that other adminAccess consumers in the namespace may rely on.
186
func (r *GPUClusterReconciler) ensureAdminAccessLabel(ctx context.Context) error {
1✔
187
        ns := &corev1.Namespace{}
1✔
188
        if err := r.Get(ctx, client.ObjectKey{Name: r.Namespace}, ns); err != nil {
1✔
189
                return fmt.Errorf("could not get namespace %s: %w", r.Namespace, err)
×
190
        }
×
191
        if ns.Labels[draAdminNamespaceLabelKey] == "true" {
1✔
192
                return nil
×
193
        }
×
194
        patch := client.MergeFrom(ns.DeepCopy())
1✔
195
        if ns.Labels == nil {
2✔
196
                ns.Labels = make(map[string]string)
1✔
197
        }
1✔
198
        ns.Labels[draAdminNamespaceLabelKey] = "true"
1✔
199
        return r.Patch(ctx, ns, patch)
1✔
200
}
201

202
// reconcileDelete drains ResourceClaim-consuming DaemonSets before releasing the CR:
203
// garbage collection would otherwise delete the DRA kubelet plugin while their pods
204
// still need it to unprepare claims, leaving them stuck in Terminating. Foreground
205
// propagation keeps each DaemonSet present until its pods are gone, i.e. unprepared.
206
func (r *GPUClusterReconciler) reconcileDelete(ctx context.Context, instance *nvidiav1alpha1.GPUCluster) (ctrl.Result, error) {
1✔
207
        logger := log.FromContext(ctx)
1✔
208

1✔
209
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
1✔
210
                return ctrl.Result{}, nil
×
211
        }
×
212

213
        dsList := &appsv1.DaemonSetList{}
1✔
214
        if err := r.List(ctx, dsList, client.InNamespace(r.Namespace)); err != nil {
1✔
215
                return ctrl.Result{}, fmt.Errorf("error listing DaemonSets: %w", err)
×
216
        }
×
217
        var draining []string
1✔
218
        for i := range dsList.Items {
2✔
219
                ds := &dsList.Items[i]
1✔
220
                if !metav1.IsControlledBy(ds, instance) || len(ds.Spec.Template.Spec.ResourceClaims) == 0 {
2✔
221
                        continue
1✔
222
                }
223
                draining = append(draining, ds.Name)
1✔
224
                if ds.DeletionTimestamp.IsZero() {
2✔
225
                        logger.V(consts.LogLevelInfo).Info("Draining ResourceClaim-consuming DaemonSet before teardown", "DaemonSet", ds.Name)
1✔
226
                        if err := r.Delete(ctx, ds, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil && !apierrors.IsNotFound(err) {
1✔
227
                                return ctrl.Result{}, fmt.Errorf("error deleting DaemonSet %s: %w", ds.Name, err)
×
228
                        }
×
229
                }
230
        }
231
        if len(draining) > 0 {
2✔
232
                r.recorder.Eventf(instance, nil, corev1.EventTypeNormal, "DrainingClaimConsumers", "Delete",
1✔
233
                        "Waiting for ResourceClaim-consuming DaemonSet(s) to terminate: %s", strings.Join(draining, ", "))
1✔
234
                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
1✔
235
        }
1✔
236

237
        controllerutil.RemoveFinalizer(instance, gpuClusterFinalizer)
1✔
238
        if err := r.Update(ctx, instance); err != nil {
1✔
239
                return ctrl.Result{}, fmt.Errorf("error removing finalizer: %w", err)
×
240
        }
×
241
        return ctrl.Result{}, nil
1✔
242
}
243

244
// updateCRStatus persists the given state (and the operator namespace) to the GPUCluster's
245
// .status subresource. It refetches the CR first to avoid resourceVersion conflicts and skips
246
// the API write when the status is already current. The desired status is mirrored onto cr
247
// up front so it is set on every non-error path.
248
func (r *GPUClusterReconciler) updateCRStatus(ctx context.Context, cr *nvidiav1alpha1.GPUCluster, desired nvidiav1alpha1.State) error {
1✔
249
        reqLogger := log.FromContext(ctx)
1✔
250

1✔
251
        // Refetch to avoid a resourceVersion conflict.
1✔
252
        instance := &nvidiav1alpha1.GPUCluster{}
1✔
253
        if err := r.Get(ctx, types.NamespacedName{Name: cr.Name}, instance); err != nil {
1✔
254
                reqLogger.Error(err, "Failed to get GPUCluster instance for status update")
×
255
                return err
×
256
        }
×
257
        cr.Status.State = desired
1✔
258
        cr.Status.Namespace = r.Namespace
1✔
259

1✔
260
        if instance.Status.State == desired && instance.Status.Namespace == r.Namespace {
1✔
261
                return nil
×
262
        }
×
263
        instance.Status.State = desired
1✔
264
        instance.Status.Namespace = r.Namespace
1✔
265

1✔
266
        reqLogger.V(consts.LogLevelInfo).Info("Updating CR Status", "Status", instance.Status)
1✔
267
        if err := r.Status().Update(ctx, instance); err != nil {
1✔
268
                reqLogger.Error(err, "Failed to update CR status")
×
269
                return err
×
270
        }
×
271
        return nil
1✔
272
}
273

274
// enqueueAllGPUClusters enqueues every instance so each is reconciled when any
275
// instance or owned resource changes.
276
func (r *GPUClusterReconciler) enqueueAllGPUClusters(ctx context.Context, _ *nvidiav1alpha1.GPUCluster) []reconcile.Request {
1✔
277
        logger := log.FromContext(ctx)
1✔
278
        list := &nvidiav1alpha1.GPUClusterList{}
1✔
279

1✔
280
        if err := r.List(ctx, list); err != nil {
1✔
281
                logger.Error(err, "Unable to list GPUCluster resources")
×
282
                return []reconcile.Request{}
×
283
        }
×
284

285
        reconcileRequests := make([]reconcile.Request, 0, len(list.Items))
1✔
286
        for _, config := range list.Items {
2✔
287
                reconcileRequests = append(reconcileRequests,
1✔
288
                        reconcile.Request{
1✔
289
                                NamespacedName: types.NamespacedName{
1✔
290
                                        Name: config.GetName(),
1✔
291
                                },
1✔
292
                        })
1✔
293
        }
1✔
294

295
        return reconcileRequests
1✔
296
}
297

298
func (r *GPUClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
×
299
        // The state manager renders the DRA driver operand for the GPUCluster.
×
300
        stateManager, err := state.NewManager(
×
301
                nvidiav1alpha1.GPUClusterCRDName,
×
302
                r.Namespace,
×
303
                mgr.GetClient(),
×
304
                mgr.GetScheme())
×
305
        if err != nil {
×
306
                return fmt.Errorf("error creating state manager: %w", err)
×
307
        }
×
308
        r.stateManager = stateManager
×
309

×
310
        r.conditionUpdater = conditions.NewGPUClusterUpdater(mgr.GetClient())
×
311
        r.recorder = mgr.GetEventRecorder("nvidia-gpu-operator")
×
312

×
313
        c, err := controller.New("gpu-cluster-controller", mgr, controller.Options{
×
314
                Reconciler:              r,
×
315
                MaxConcurrentReconciles: 1,
×
316
                RateLimiter:             workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](minDelayCR, maxDelayCR),
×
317
        })
×
318
        if err != nil {
×
319
                return err
×
320
        }
×
321

322
        err = c.Watch(source.Kind(
×
323
                mgr.GetCache(),
×
324
                &nvidiav1alpha1.GPUCluster{},
×
325
                handler.TypedEnqueueRequestsFromMapFunc(r.enqueueAllGPUClusters),
×
326
                predicate.TypedGenerationChangedPredicate[*nvidiav1alpha1.GPUCluster]{},
×
327
        ),
×
328
        )
×
329
        if err != nil {
×
330
                return err
×
331
        }
×
332

333
        // Watch the secondary resources each state manager owns.
334
        watchSources := stateManager.GetWatchSources(mgr)
×
335
        for _, watchSource := range watchSources {
×
336
                err = c.Watch(
×
337
                        watchSource,
×
338
                )
×
339
                if err != nil {
×
340
                        return fmt.Errorf("error setting up Watch for source type %v: %w", watchSource, err)
×
341
                }
×
342
        }
343

344
        return nil
×
345
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc