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

NVIDIA / gpu-operator / 30040328974

23 Jul 2026 08:00PM UTC coverage: 33.236% (+1.3%) from 31.955%
30040328974

Pull #2571

github

karthikvetrivel
Add golden render tests for GPUCluster operand manifests

Signed-off-by: Karthik Vetrivel <kvetrivel@nvidia.com>
Pull Request #2571: Add GPUCluster CRD and controller for DRA-based stack

596 of 1510 new or added lines in 32 files covered. (39.47%)

18 existing lines in 4 files now uncovered.

4785 of 14397 relevant lines covered (33.24%)

0.38 hits per line

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

52.66
/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
        nvidiav1alpha1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1alpha1"
44
        "github.com/NVIDIA/gpu-operator/controllers/clusterinfo"
45
        "github.com/NVIDIA/gpu-operator/internal/conditions"
46
        "github.com/NVIDIA/gpu-operator/internal/consts"
47
        "github.com/NVIDIA/gpu-operator/internal/state"
48
)
49

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

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

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

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

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

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

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

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

97
        if !instance.DeletionTimestamp.IsZero() {
2✔
98
                return r.reconcileDelete(ctx, instance)
1✔
99
        }
1✔
100
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
2✔
101
                controllerutil.AddFinalizer(instance, gpuClusterFinalizer)
1✔
102
                if err := r.Update(ctx, instance); err != nil {
1✔
NEW
103
                        return ctrl.Result{}, fmt.Errorf("error adding finalizer: %w", err)
×
NEW
104
                }
×
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✔
NEW
118
                        return ctrl.Result{}, err
×
NEW
119
                }
×
120
                return ctrl.Result{}, nil
1✔
121
        }
122
        r.singleton = instance
1✔
123

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

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

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

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

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

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

166
// ensureAdminAccessLabel patches the operator namespace with the label required by the
167
// kube-scheduler to allow adminAccess: true in ResourceClaim/ResourceClaimTemplate
168
// objects. The label is deliberately never removed: it is namespace-level configuration
169
// that other adminAccess consumers in the namespace may rely on.
170
func (r *GPUClusterReconciler) ensureAdminAccessLabel(ctx context.Context) error {
1✔
171
        ns := &corev1.Namespace{}
1✔
172
        if err := r.Get(ctx, client.ObjectKey{Name: r.Namespace}, ns); err != nil {
1✔
NEW
173
                return fmt.Errorf("could not get namespace %s: %w", r.Namespace, err)
×
NEW
174
        }
×
175
        if ns.Labels[draAdminNamespaceLabelKey] == "true" {
1✔
NEW
176
                return nil
×
NEW
177
        }
×
178
        patch := client.MergeFrom(ns.DeepCopy())
1✔
179
        if ns.Labels == nil {
2✔
180
                ns.Labels = make(map[string]string)
1✔
181
        }
1✔
182
        ns.Labels[draAdminNamespaceLabelKey] = "true"
1✔
183
        return r.Patch(ctx, ns, patch)
1✔
184
}
185

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

1✔
193
        if !controllerutil.ContainsFinalizer(instance, gpuClusterFinalizer) {
1✔
NEW
194
                return ctrl.Result{}, nil
×
NEW
195
        }
×
196

197
        dsList := &appsv1.DaemonSetList{}
1✔
198
        if err := r.List(ctx, dsList, client.InNamespace(r.Namespace)); err != nil {
1✔
NEW
199
                return ctrl.Result{}, fmt.Errorf("error listing DaemonSets: %w", err)
×
NEW
200
        }
×
201
        var draining []string
1✔
202
        for i := range dsList.Items {
2✔
203
                ds := &dsList.Items[i]
1✔
204
                if !metav1.IsControlledBy(ds, instance) || len(ds.Spec.Template.Spec.ResourceClaims) == 0 {
2✔
205
                        continue
1✔
206
                }
207
                draining = append(draining, ds.Name)
1✔
208
                if ds.DeletionTimestamp.IsZero() {
2✔
209
                        logger.V(consts.LogLevelInfo).Info("Draining ResourceClaim-consuming DaemonSet before teardown", "DaemonSet", ds.Name)
1✔
210
                        if err := r.Delete(ctx, ds, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil && !apierrors.IsNotFound(err) {
1✔
NEW
211
                                return ctrl.Result{}, fmt.Errorf("error deleting DaemonSet %s: %w", ds.Name, err)
×
NEW
212
                        }
×
213
                }
214
        }
215
        if len(draining) > 0 {
2✔
216
                r.recorder.Eventf(instance, nil, corev1.EventTypeNormal, "DrainingClaimConsumers", "Delete",
1✔
217
                        "Waiting for ResourceClaim-consuming DaemonSet(s) to terminate: %s", strings.Join(draining, ", "))
1✔
218
                return ctrl.Result{RequeueAfter: time.Second * 5}, nil
1✔
219
        }
1✔
220

221
        controllerutil.RemoveFinalizer(instance, gpuClusterFinalizer)
1✔
222
        if err := r.Update(ctx, instance); err != nil {
1✔
NEW
223
                return ctrl.Result{}, fmt.Errorf("error removing finalizer: %w", err)
×
NEW
224
        }
×
225
        return ctrl.Result{}, nil
1✔
226
}
227

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

1✔
235
        // Refetch to avoid a resourceVersion conflict.
1✔
236
        instance := &nvidiav1alpha1.GPUCluster{}
1✔
237
        if err := r.Get(ctx, types.NamespacedName{Name: cr.Name}, instance); err != nil {
1✔
NEW
238
                reqLogger.Error(err, "Failed to get GPUCluster instance for status update")
×
NEW
239
                return err
×
NEW
240
        }
×
241
        cr.Status.State = desired
1✔
242
        cr.Status.Namespace = r.Namespace
1✔
243

1✔
244
        if instance.Status.State == desired && instance.Status.Namespace == r.Namespace {
1✔
NEW
245
                return nil
×
NEW
246
        }
×
247
        instance.Status.State = desired
1✔
248
        instance.Status.Namespace = r.Namespace
1✔
249

1✔
250
        reqLogger.V(consts.LogLevelInfo).Info("Updating CR Status", "Status", instance.Status)
1✔
251
        if err := r.Status().Update(ctx, instance); err != nil {
1✔
NEW
252
                reqLogger.Error(err, "Failed to update CR status")
×
NEW
253
                return err
×
NEW
254
        }
×
255
        return nil
1✔
256
}
257

258
// enqueueAllGPUClusters enqueues every instance so each is reconciled when any
259
// instance or owned resource changes.
260
func (r *GPUClusterReconciler) enqueueAllGPUClusters(ctx context.Context, _ *nvidiav1alpha1.GPUCluster) []reconcile.Request {
1✔
261
        logger := log.FromContext(ctx)
1✔
262
        list := &nvidiav1alpha1.GPUClusterList{}
1✔
263

1✔
264
        if err := r.List(ctx, list); err != nil {
1✔
NEW
265
                logger.Error(err, "Unable to list GPUCluster resources")
×
NEW
266
                return []reconcile.Request{}
×
NEW
267
        }
×
268

269
        reconcileRequests := make([]reconcile.Request, 0, len(list.Items))
1✔
270
        for _, config := range list.Items {
2✔
271
                reconcileRequests = append(reconcileRequests,
1✔
272
                        reconcile.Request{
1✔
273
                                NamespacedName: types.NamespacedName{
1✔
274
                                        Name: config.GetName(),
1✔
275
                                },
1✔
276
                        })
1✔
277
        }
1✔
278

279
        return reconcileRequests
1✔
280
}
281

NEW
282
func (r *GPUClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
×
NEW
283
        // The state manager renders the DRA driver operand for the GPUCluster.
×
NEW
284
        stateManager, err := state.NewManager(
×
NEW
285
                nvidiav1alpha1.GPUClusterCRDName,
×
NEW
286
                r.Namespace,
×
NEW
287
                mgr.GetClient(),
×
NEW
288
                mgr.GetScheme())
×
NEW
289
        if err != nil {
×
NEW
290
                return fmt.Errorf("error creating state manager: %w", err)
×
NEW
291
        }
×
NEW
292
        r.stateManager = stateManager
×
NEW
293

×
NEW
294
        r.conditionUpdater = conditions.NewGPUClusterUpdater(mgr.GetClient())
×
NEW
295
        r.recorder = mgr.GetEventRecorder("nvidia-gpu-operator")
×
NEW
296

×
NEW
297
        c, err := controller.New("gpu-cluster-controller", mgr, controller.Options{
×
NEW
298
                Reconciler:              r,
×
NEW
299
                MaxConcurrentReconciles: 1,
×
NEW
300
                RateLimiter:             workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](minDelayCR, maxDelayCR),
×
NEW
301
        })
×
NEW
302
        if err != nil {
×
NEW
303
                return err
×
NEW
304
        }
×
305

NEW
306
        err = c.Watch(source.Kind(
×
NEW
307
                mgr.GetCache(),
×
NEW
308
                &nvidiav1alpha1.GPUCluster{},
×
NEW
309
                handler.TypedEnqueueRequestsFromMapFunc(r.enqueueAllGPUClusters),
×
NEW
310
                predicate.TypedGenerationChangedPredicate[*nvidiav1alpha1.GPUCluster]{},
×
NEW
311
        ),
×
NEW
312
        )
×
NEW
313
        if err != nil {
×
NEW
314
                return err
×
NEW
315
        }
×
316

317
        // Watch the secondary resources each state manager owns.
NEW
318
        watchSources := stateManager.GetWatchSources(mgr)
×
NEW
319
        for _, watchSource := range watchSources {
×
NEW
320
                err = c.Watch(
×
NEW
321
                        watchSource,
×
NEW
322
                )
×
NEW
323
                if err != nil {
×
NEW
324
                        return fmt.Errorf("error setting up Watch for source type %v: %w", watchSource, err)
×
NEW
325
                }
×
326
        }
327

NEW
328
        return nil
×
329
}
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