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

NVIDIA / gpu-operator / 30395815252

28 Jul 2026 08:19PM UTC coverage: 36.56% (+1.3%) from 35.256%
30395815252

push

github

web-flow
Merge pull request #2572 from NVIDIA/kv-nvidiadriver-standalone

Support NVIDIADriver reconciliation and driver upgrades without a ClusterPolicy

42 of 94 new or added lines in 6 files covered. (44.68%)

1 existing line in 1 file now uncovered.

5307 of 14516 relevant lines covered (36.56%)

0.42 hits per line

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

53.62
/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
        // singleton is the GPUCluster that owns reconciliation; the first instance to
71
        // reconcile claims it (first-wins), mirroring ClusterPolicy.
72
        singleton *nvidiav1alpha1.GPUCluster
73
}
74

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

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

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

99
        if !instance.DeletionTimestamp.IsZero() {
2✔
100
                return r.reconcileDelete(ctx, instance)
1✔
101
        }
1✔
102

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

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

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

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

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

145
        infoCatalog := state.NewInfoCatalog()
1✔
146
        infoCatalog.Add(state.InfoTypeClusterInfo, r.ClusterInfo)
1✔
147

1✔
148
        managerStatus := r.stateManager.SyncState(ctx, instance, infoCatalog)
1✔
149

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

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

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

181
// validatePrerequisites checks the cross-CR rules that gate DRA enablement, returning
182
// a message describing the first unmet prerequisite or an empty string when all are met.
183
func (r *GPUClusterReconciler) validatePrerequisites(ctx context.Context) (string, error) {
1✔
184
        clusterPolicies := &gpuv1.ClusterPolicyList{}
1✔
185
        if err := r.List(ctx, clusterPolicies); err != nil {
1✔
NEW
186
                return "", fmt.Errorf("error listing ClusterPolicy objects: %w", err)
×
NEW
187
        }
×
188
        // TODO: check only the active singleton ClusterPolicy once the singleton
189
        // selection is resolvable across controllers (see resolveActiveConfig).
190
        for _, clusterPolicy := range clusterPolicies.Items {
2✔
191
                if !clusterPolicy.Spec.Driver.UseNvidiaDriverCRDType() {
2✔
192
                        return fmt.Sprintf("ClusterPolicy %s does not have driver.useNvidiaDriverCRD enabled; migrate driver management to NVIDIADriver CRs before enabling DRA", clusterPolicy.Name), nil
1✔
193
                }
1✔
194
        }
195
        return "", nil
1✔
196
}
197

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

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

1✔
225
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
1✔
226
                return ctrl.Result{}, nil
×
227
        }
×
228

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

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

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

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

1✔
276
        if instance.Status.State == desired && instance.Status.Namespace == r.Namespace {
1✔
277
                return nil
×
278
        }
×
279
        instance.Status.State = desired
1✔
280
        instance.Status.Namespace = r.Namespace
1✔
281

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

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

1✔
296
        if err := r.List(ctx, list); err != nil {
1✔
297
                logger.Error(err, "Unable to list GPUCluster resources")
×
298
                return []reconcile.Request{}
×
299
        }
×
300

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

311
        return reconcileRequests
1✔
312
}
313

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

×
326
        r.conditionUpdater = conditions.NewGPUClusterUpdater(mgr.GetClient())
×
327
        r.recorder = mgr.GetEventRecorder("nvidia-gpu-operator")
×
328

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

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

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

360
        return nil
×
361
}
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