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

NVIDIA / gpu-operator / 30284536713

27 Jul 2026 04:23PM UTC coverage: 34.873% (+0.3%) from 34.591%
30284536713

Pull #2572

github

karthikvetrivel
Support NVIDIADriver reconciliation and driver upgrades without a ClusterPolicy

Signed-off-by: Karthik Vetrivel <kvetrivel@nvidia.com>
Pull Request #2572: Support NVIDIADriver reconciliation and driver upgrades without a ClusterPolicy

53 of 95 new or added lines in 5 files covered. (55.79%)

259 existing lines in 6 files now uncovered.

5028 of 14418 relevant lines covered (34.87%)

0.4 hits per line

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

54.72
/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
)
50

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

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

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

65
        stateManager     state.Manager
66
        conditionUpdater conditions.Updater
67
        recorder         events.EventRecorder
68

69
        // singleton is the GPUCluster that owns reconciliation; the first instance to
70
        // reconcile claims it (first-wins), mirroring ClusterPolicy.
71
        singleton *nvidiav1alpha1.GPUCluster
72
}
73

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

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

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

98
        if !instance.DeletionTimestamp.IsZero() {
2✔
99
                return r.reconcileDelete(ctx, instance)
1✔
100
        }
1✔
101
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
2✔
102
                controllerutil.AddFinalizer(instance, gpuClusterFinalizer)
1✔
103
                if err := r.Update(ctx, instance); err != nil {
1✔
104
                        return ctrl.Result{}, fmt.Errorf("error adding finalizer: %w", err)
×
105
                }
×
106
        }
107

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

112
        // Singleton, first-wins (mirroring ClusterPolicy): the first instance to reconcile
113
        // claims ownership; any other instance is marked Ignored and skipped. The owner is
114
        // held in memory, so the choice resets on operator restart.
115
        if r.singleton != nil && r.singleton.Name != instance.Name {
2✔
116
                logger.V(consts.LogLevelWarning).Info("Multiple GPUCluster instances found, ignoring this one",
1✔
117
                        "name", instance.Name, "owner", r.singleton.Name)
1✔
118
                if err := r.updateCRStatus(ctx, instance, nvidiav1alpha1.Ignored); err != nil {
1✔
119
                        return ctrl.Result{}, err
×
UNCOV
120
                }
×
121
                return ctrl.Result{}, nil
1✔
122
        }
123
        r.singleton = instance
1✔
124

1✔
125
        // Enabling DRA requires that all driver management is done through NVIDIADriver
1✔
126
        // CRs: a coexisting ClusterPolicy must delegate its driver with
1✔
127
        // useNvidiaDriverCRD=true. Surface the unmet prerequisite on this CR's status
1✔
128
        // and hold off deploying operands until it is met.
1✔
129
        if msg, err := r.validatePrerequisites(ctx); err != nil {
1✔
NEW
130
                return ctrl.Result{}, err
×
131
        } else if msg != "" {
2✔
132
                logger.V(consts.LogLevelWarning).Info("GPUCluster prerequisite not met", "reason", msg)
1✔
133
                if err := r.updateCRStatus(ctx, instance, nvidiav1alpha1.NotReady); err != nil {
1✔
NEW
134
                        return ctrl.Result{}, err
×
NEW
135
                }
×
136
                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.PrerequisiteNotMet, msg); condErr != nil {
1✔
NEW
137
                        logger.Error(condErr, "failed to set condition")
×
NEW
138
                }
×
139
                return ctrl.Result{RequeueAfter: time.Minute}, nil
1✔
140
        }
141

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

148
        infoCatalog := state.NewInfoCatalog()
1✔
149
        infoCatalog.Add(state.InfoTypeClusterInfo, r.ClusterInfo)
1✔
150

1✔
151
        managerStatus := r.stateManager.SyncState(ctx, instance, infoCatalog)
1✔
152

1✔
153
        if err := r.updateCRStatus(ctx, instance, nvidiav1alpha1.State(managerStatus.Status)); err != nil {
1✔
154
                return ctrl.Result{}, err
×
UNCOV
155
        }
×
156

157
        if managerStatus.Status != state.SyncStateReady {
1✔
158
                logger.Info("GPUCluster instance is not ready")
×
159
                for _, result := range managerStatus.StatesStatus {
×
160
                        if result.Status != state.SyncStateReady && result.ErrInfo != nil {
×
161
                                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.ReconcileFailed, fmt.Sprintf("Error syncing state %s: %v", result.StateName, result.ErrInfo)); condErr != nil {
×
162
                                        logger.Error(condErr, "failed to set condition")
×
163
                                }
×
UNCOV
164
                                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
×
165
                        }
166
                }
167
                // no state reported an error, so we are waiting on operand pods
168
                if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.OperandNotReady, "Waiting for operand pods to be ready"); condErr != nil {
×
169
                        logger.Error(condErr, "failed to set condition")
×
170
                }
×
UNCOV
171
                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
×
172
        }
173

174
        if condErr := r.conditionUpdater.SetConditionsReady(ctx, instance, conditions.Reconciled, "All resources have been successfully reconciled"); condErr != nil {
1✔
175
                logger.Error(condErr, "failed to set condition")
×
176
                return ctrl.Result{}, condErr
×
UNCOV
177
        }
×
178
        // Resync periodically so out-of-band changes (a deleted DeviceClass/VAP, or a
179
        // newly-created ClusterPolicy) are detected and reconciled even while ready;
180
        // only DaemonSets are watched, and the ready path is otherwise event-driven.
181
        return ctrl.Result{RequeueAfter: time.Minute}, nil
1✔
182
}
183

184
// validatePrerequisites checks the cross-CR rules that gate DRA enablement, returning a
185
// message describing the first unmet prerequisite or an empty string when all are met.
186
// The rules span multiple CRs, so they cannot be expressed as CRD schema validation and
187
// are re-evaluated on every reconcile.
188
func (r *GPUClusterReconciler) validatePrerequisites(ctx context.Context) (string, error) {
1✔
189
        clusterPolicies := &gpuv1.ClusterPolicyList{}
1✔
190
        if err := r.List(ctx, clusterPolicies); err != nil {
1✔
NEW
191
                return "", fmt.Errorf("error listing ClusterPolicy objects: %w", err)
×
NEW
192
        }
×
193
        for i := range clusterPolicies.Items {
2✔
194
                cp := &clusterPolicies.Items[i]
1✔
195
                if !cp.Spec.Driver.UseNvidiaDriverCRDType() {
2✔
196
                        return fmt.Sprintf("ClusterPolicy %s does not have driver.useNvidiaDriverCRD enabled; migrate driver management to NVIDIADriver CRs before enabling DRA", cp.Name), nil
1✔
197
                }
1✔
198
        }
199
        return "", nil
1✔
200
}
201

202
// ensureAdminAccessLabel patches the operator namespace with the label required by the
203
// kube-scheduler to allow adminAccess: true in ResourceClaim/ResourceClaimTemplate
204
// objects. The label is deliberately never removed: it is namespace-level configuration
205
// that other adminAccess consumers in the namespace may rely on.
206
func (r *GPUClusterReconciler) ensureAdminAccessLabel(ctx context.Context) error {
1✔
207
        ns := &corev1.Namespace{}
1✔
208
        if err := r.Get(ctx, client.ObjectKey{Name: r.Namespace}, ns); err != nil {
1✔
209
                return fmt.Errorf("could not get namespace %s: %w", r.Namespace, err)
×
UNCOV
210
        }
×
211
        if ns.Labels[draAdminNamespaceLabelKey] == "true" {
1✔
212
                return nil
×
UNCOV
213
        }
×
214
        patch := client.MergeFrom(ns.DeepCopy())
1✔
215
        if ns.Labels == nil {
2✔
216
                ns.Labels = make(map[string]string)
1✔
217
        }
1✔
218
        ns.Labels[draAdminNamespaceLabelKey] = "true"
1✔
219
        return r.Patch(ctx, ns, patch)
1✔
220
}
221

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

1✔
229
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
1✔
230
                return ctrl.Result{}, nil
×
UNCOV
231
        }
×
232

233
        dsList := &appsv1.DaemonSetList{}
1✔
234
        if err := r.List(ctx, dsList, client.InNamespace(r.Namespace)); err != nil {
1✔
235
                return ctrl.Result{}, fmt.Errorf("error listing DaemonSets: %w", err)
×
UNCOV
236
        }
×
237
        var draining []string
1✔
238
        for i := range dsList.Items {
2✔
239
                ds := &dsList.Items[i]
1✔
240
                if !metav1.IsControlledBy(ds, instance) || len(ds.Spec.Template.Spec.ResourceClaims) == 0 {
2✔
241
                        continue
1✔
242
                }
243
                draining = append(draining, ds.Name)
1✔
244
                if ds.DeletionTimestamp.IsZero() {
2✔
245
                        logger.V(consts.LogLevelInfo).Info("Draining ResourceClaim-consuming DaemonSet before teardown", "DaemonSet", ds.Name)
1✔
246
                        if err := r.Delete(ctx, ds, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil && !apierrors.IsNotFound(err) {
1✔
247
                                return ctrl.Result{}, fmt.Errorf("error deleting DaemonSet %s: %w", ds.Name, err)
×
UNCOV
248
                        }
×
249
                }
250
        }
251
        if len(draining) > 0 {
2✔
252
                r.recorder.Eventf(instance, nil, corev1.EventTypeNormal, "DrainingClaimConsumers", "Delete",
1✔
253
                        "Waiting for ResourceClaim-consuming DaemonSet(s) to terminate: %s", strings.Join(draining, ", "))
1✔
254
                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
1✔
255
        }
1✔
256

257
        controllerutil.RemoveFinalizer(instance, gpuClusterFinalizer)
1✔
258
        if err := r.Update(ctx, instance); err != nil {
1✔
259
                return ctrl.Result{}, fmt.Errorf("error removing finalizer: %w", err)
×
UNCOV
260
        }
×
261
        return ctrl.Result{}, nil
1✔
262
}
263

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

1✔
271
        // Refetch to avoid a resourceVersion conflict.
1✔
272
        instance := &nvidiav1alpha1.GPUCluster{}
1✔
273
        if err := r.Get(ctx, types.NamespacedName{Name: cr.Name}, instance); err != nil {
1✔
274
                reqLogger.Error(err, "Failed to get GPUCluster instance for status update")
×
275
                return err
×
UNCOV
276
        }
×
277
        cr.Status.State = desired
1✔
278
        cr.Status.Namespace = r.Namespace
1✔
279

1✔
280
        if instance.Status.State == desired && instance.Status.Namespace == r.Namespace {
1✔
281
                return nil
×
UNCOV
282
        }
×
283
        instance.Status.State = desired
1✔
284
        instance.Status.Namespace = r.Namespace
1✔
285

1✔
286
        reqLogger.V(consts.LogLevelInfo).Info("Updating CR Status", "Status", instance.Status)
1✔
287
        if err := r.Status().Update(ctx, instance); err != nil {
1✔
288
                reqLogger.Error(err, "Failed to update CR status")
×
289
                return err
×
UNCOV
290
        }
×
291
        return nil
1✔
292
}
293

294
// enqueueAllGPUClusters enqueues every instance so each is reconciled when any
295
// instance or owned resource changes.
296
func (r *GPUClusterReconciler) enqueueAllGPUClusters(ctx context.Context, _ *nvidiav1alpha1.GPUCluster) []reconcile.Request {
1✔
297
        logger := log.FromContext(ctx)
1✔
298
        list := &nvidiav1alpha1.GPUClusterList{}
1✔
299

1✔
300
        if err := r.List(ctx, list); err != nil {
1✔
301
                logger.Error(err, "Unable to list GPUCluster resources")
×
302
                return []reconcile.Request{}
×
UNCOV
303
        }
×
304

305
        reconcileRequests := make([]reconcile.Request, 0, len(list.Items))
1✔
306
        for _, config := range list.Items {
2✔
307
                reconcileRequests = append(reconcileRequests,
1✔
308
                        reconcile.Request{
1✔
309
                                NamespacedName: types.NamespacedName{
1✔
310
                                        Name: config.GetName(),
1✔
311
                                },
1✔
312
                        })
1✔
313
        }
1✔
314

315
        return reconcileRequests
1✔
316
}
317

318
func (r *GPUClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
×
319
        // The state manager renders the DRA driver operand for the GPUCluster.
×
320
        stateManager, err := state.NewManager(
×
321
                nvidiav1alpha1.GPUClusterCRDName,
×
322
                r.Namespace,
×
323
                mgr.GetClient(),
×
324
                mgr.GetScheme())
×
325
        if err != nil {
×
326
                return fmt.Errorf("error creating state manager: %w", err)
×
327
        }
×
328
        r.stateManager = stateManager
×
329

×
330
        r.conditionUpdater = conditions.NewGPUClusterUpdater(mgr.GetClient())
×
331
        r.recorder = mgr.GetEventRecorder("nvidia-gpu-operator")
×
332

×
333
        c, err := controller.New("gpu-cluster-controller", mgr, controller.Options{
×
334
                Reconciler:              r,
×
335
                MaxConcurrentReconciles: 1,
×
336
                RateLimiter:             workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](minDelayCR, maxDelayCR),
×
337
        })
×
338
        if err != nil {
×
339
                return err
×
UNCOV
340
        }
×
341

342
        err = c.Watch(source.Kind(
×
343
                mgr.GetCache(),
×
344
                &nvidiav1alpha1.GPUCluster{},
×
345
                handler.TypedEnqueueRequestsFromMapFunc(r.enqueueAllGPUClusters),
×
346
                predicate.TypedGenerationChangedPredicate[*nvidiav1alpha1.GPUCluster]{},
×
347
        ),
×
348
        )
×
349
        if err != nil {
×
350
                return err
×
UNCOV
351
        }
×
352

353
        // Watch the secondary resources each state manager owns.
354
        watchSources := stateManager.GetWatchSources(mgr)
×
355
        for _, watchSource := range watchSources {
×
356
                err = c.Watch(
×
357
                        watchSource,
×
358
                )
×
359
                if err != nil {
×
360
                        return fmt.Errorf("error setting up Watch for source type %v: %w", watchSource, err)
×
UNCOV
361
                }
×
362
        }
363

UNCOV
364
        return nil
×
365
}
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