Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions controllers/clusterpolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/source"

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

Expand Down Expand Up @@ -143,6 +144,20 @@ func (r *ClusterPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reques
}

clusterPolicyCtrl.operatorMetrics.reconciliationTotal.Inc()

nvidiaDriverEnabled := nvidiaDriverCRDEnabled(instance)
if nvidiaDriverEnabled {
if err := assignNVIDIADriverOwners(ctx, r.Client); err != nil {
clusterPolicyCtrl.operatorMetrics.reconciliationStatus.Set(reconciliationStatusNotReady)
clusterPolicyCtrl.operatorMetrics.reconciliationFailed.Inc()
updateCRState(ctx, r, req.NamespacedName, gpuv1.NotReady)
if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.ReconcileFailed, err.Error()); condErr != nil {
r.Log.Error(condErr, "failed to set condition")
}
return ctrl.Result{}, err
}
}

overallStatus := gpuv1.Ready
statesNotReady := []string{}
for {
Expand Down Expand Up @@ -170,6 +185,12 @@ func (r *ClusterPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Reques
}
}

if nvidiaDriverEnabled {
if err := clusterPolicyCtrl.labelNodesWithOrphanedDriverPods(ctx); err != nil {
r.Log.Error(err, "failed to label nodes with orphaned NVIDIA driver pods")
}
}

// if any state is not ready, requeue for reconcile after 5 seconds
if overallStatus != gpuv1.Ready {
clusterPolicyCtrl.operatorMetrics.reconciliationStatus.Set(reconciliationStatusNotReady)
Expand Down Expand Up @@ -371,6 +392,29 @@ func (r *ClusterPolicyReconciler) SetupWithManager(ctx context.Context, mgr ctrl
return err
}

err = c.Watch(
source.Kind(mgr.GetCache(),
&nvidiav1alpha1.NVIDIADriver{},
handler.TypedEnqueueRequestsFromMapFunc(func(ctx context.Context, _ *nvidiav1alpha1.NVIDIADriver) []reconcile.Request {
list := &gpuv1.ClusterPolicyList{}
if err := mgr.GetClient().List(ctx, list); err != nil {
return []reconcile.Request{}
}
requests := make([]reconcile.Request, 0, len(list.Items))
for _, item := range list.Items {
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{Name: item.GetName()},
})
}
return requests
}),
nvidiaDriverGenerationOrDefaultLabelChangedPredicate(),
),
)
if err != nil {
return err
}

// TODO(user): Modify this to be the types you create that are owned by the primary resource
// Watch for changes to secondary resource Daemonsets and requeue the owner ClusterPolicy
err = c.Watch(
Expand Down
55 changes: 53 additions & 2 deletions controllers/nvidiadriver_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ func (r *NVIDIADriverReconciler) Reconcile(ctx context.Context, req ctrl.Request
}

if len(clusterPolicyList.Items) == 0 {
if handled, err := r.handleDefaultNVIDIADriverDeletion(ctx, instance); handled || err != nil {
return reconcile.Result{}, err
}
err := fmt.Errorf("no ClusterPolicy object found in the cluster")
logger.Error(err, "failed to get ClusterPolicy object")
instance.Status.State = nvidiav1alpha1.NotReady
Expand All @@ -120,8 +123,12 @@ func (r *NVIDIADriverReconciler) Reconcile(ctx context.Context, req ctrl.Request
}
clusterPolicyInstance := clusterPolicyList.Items[0]

if handled, err := r.handleDefaultNVIDIADriverDeletion(ctx, instance); handled || err != nil {
return reconcile.Result{}, err
}

// Ensure that ClusterPolicy is configured to use NVIDIADriver CRD
if !clusterPolicyInstance.Spec.Driver.UseNvidiaDriverCRDType() {
if !nvidiaDriverCRDEnabled(&clusterPolicyInstance) {
msg := "useNvidiaDriverCRD is not enabled in ClusterPolicy"
logger.V(consts.LogLevelWarning).Info("NVIDIADriver reconciliation skipped", "reason", msg)
instance.Status.State = nvidiav1alpha1.Disabled
Expand Down Expand Up @@ -152,6 +159,15 @@ func (r *NVIDIADriverReconciler) Reconcile(ctx context.Context, req ctrl.Request
return reconcile.Result{}, nil
}

if err := assignNVIDIADriverOwners(ctx, r.Client); err != nil {
logger.Error(err, "failed to assign NVIDIADriver owners to nodes")
instance.Status.State = nvidiav1alpha1.NotReady
if condErr := r.conditionUpdater.SetConditionsError(ctx, instance, conditions.ReconcileFailed, err.Error()); condErr != nil {
logger.Error(condErr, "failed to set condition")
}
return reconcile.Result{}, err
}

if instance.Spec.UsePrecompiledDrivers() && (instance.Spec.IsGDSEnabled() || instance.Spec.IsGDRCopyEnabled()) {
err := errors.New("GPUDirect Storage driver (nvidia-fs) and/or GDRCopy driver is not supported along with pre-compiled NVIDIA drivers")
logger.Error(err, "unsupported driver combination detected")
Expand Down Expand Up @@ -221,6 +237,14 @@ func (r *NVIDIADriverReconciler) Reconcile(ctx context.Context, req ctrl.Request
return reconcile.Result{}, nil
}

func (r *NVIDIADriverReconciler) handleDefaultNVIDIADriverDeletion(ctx context.Context, driver *nvidiav1alpha1.NVIDIADriver) (bool, error) {
if !isDefaultNVIDIADriver(driver) || driver.GetDeletionTimestamp() == nil {
return false, nil
}
log.FromContext(ctx).Info("Default NVIDIADriver delete requested; skipping reconciliation")
return true, nil
}

func (r *NVIDIADriverReconciler) updateCrStatus(
ctx context.Context, cr *nvidiav1alpha1.NVIDIADriver, status state.Results) error {
reqLogger := log.FromContext(ctx)
Expand Down Expand Up @@ -316,7 +340,7 @@ func (r *NVIDIADriverReconciler) SetupWithManager(ctx context.Context, mgr ctrl.
mgr.GetCache(),
&nvidiav1alpha1.NVIDIADriver{},
handler.TypedEnqueueRequestsFromMapFunc(nvidiaDriverMapFn),
predicate.TypedGenerationChangedPredicate[*nvidiav1alpha1.NVIDIADriver]{},
nvidiaDriverGenerationOrDefaultLabelChangedPredicate(),
),
)
if err != nil {
Expand Down Expand Up @@ -413,3 +437,30 @@ func (r *NVIDIADriverReconciler) SetupWithManager(ctx context.Context, mgr ctrl.

return nil
}

// nvidiaDriverGenerationOrDefaultLabelChangedPredicate reconciles NVIDIADrivers on spec changes and
// on changes to the default-driver label, which is metadata but affects ownership semantics.
func nvidiaDriverGenerationOrDefaultLabelChangedPredicate() predicate.TypedPredicate[*nvidiav1alpha1.NVIDIADriver] {
return predicate.TypedFuncs[*nvidiav1alpha1.NVIDIADriver]{
CreateFunc: func(event.TypedCreateEvent[*nvidiav1alpha1.NVIDIADriver]) bool {
return true
},
DeleteFunc: func(event.TypedDeleteEvent[*nvidiav1alpha1.NVIDIADriver]) bool {
return true
},
UpdateFunc: func(e event.TypedUpdateEvent[*nvidiav1alpha1.NVIDIADriver]) bool {
if e.ObjectOld == nil || e.ObjectNew == nil {
return true
}
if e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration() {
return true
}
oldLabels := e.ObjectOld.GetLabels()
newLabels := e.ObjectNew.GetLabels()
return oldLabels[consts.DefaultNVIDIADriverLabel] != newLabels[consts.DefaultNVIDIADriverLabel]
},
GenericFunc: func(event.TypedGenericEvent[*nvidiav1alpha1.NVIDIADriver]) bool {
return false
},
}
}
109 changes: 109 additions & 0 deletions controllers/nvidiadriver_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,19 @@ import (
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/event"

gpuv1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1"
nvidiav1alpha1 "github.com/NVIDIA/gpu-operator/api/nvidia/v1alpha1"
"github.com/NVIDIA/gpu-operator/internal/consts"
"github.com/NVIDIA/gpu-operator/internal/validator"
)

Expand Down Expand Up @@ -70,6 +74,15 @@ func (f *FakeNodeSelectorValidator) Validate(ctx context.Context, cr *nvidiav1al
return f.CustomError
}

type patchFailingClient struct {
client.Client
patchErr error
}

func (c *patchFailingClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
return c.patchErr
}

// newTestLogger creates a zap.Logger that writes to an in-memory buffer for testing
func newTestLogger() (logr.Logger, *bytes.Buffer) {
buf := &bytes.Buffer{}
Expand Down Expand Up @@ -97,6 +110,7 @@ func TestReconcile(t *testing.T) {
scheme := runtime.NewScheme()
require.NoError(t, nvidiav1alpha1.AddToScheme(scheme))
require.NoError(t, gpuv1.AddToScheme(scheme))
require.NoError(t, corev1.AddToScheme(scheme))

tests := []struct {
name string
Expand Down Expand Up @@ -247,6 +261,59 @@ func TestReconcileConflictSetsNotReadyState(t *testing.T) {
require.Equal(t, nvidiav1alpha1.NotReady, updater.LastErrorState)
}

func TestReconcileReturnsErrorWhenOwnerAssignmentFails(t *testing.T) {
scheme := runtime.NewScheme()
require.NoError(t, nvidiav1alpha1.AddToScheme(scheme))
require.NoError(t, gpuv1.AddToScheme(scheme))
require.NoError(t, corev1.AddToScheme(scheme))

driver := &nvidiav1alpha1.NVIDIADriver{
ObjectMeta: metav1.ObjectMeta{
Name: "test-driver",
Namespace: "default",
},
Spec: nvidiav1alpha1.NVIDIADriverSpec{
NodeSelector: map[string]string{"nodepool": "a"},
},
}
cp := &gpuv1.ClusterPolicy{
ObjectMeta: metav1.ObjectMeta{Name: "default"},
Spec: gpuv1.ClusterPolicySpec{
Driver: gpuv1.DriverSpec{
UseNvidiaDriverCRD: ptr.To(true),
},
},
}
node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{
Name: "gpu-node",
Labels: map[string]string{
"nodepool": "a",
"nvidia.com/gpu.present": "true",
},
}}
patchErr := errors.New("patch failed")
k8sClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cp, driver, node).Build()
updater := &FakeConditionUpdater{}

reconciler := &NVIDIADriverReconciler{
Client: &patchFailingClient{Client: k8sClient, patchErr: patchErr},
Scheme: scheme,
conditionUpdater: updater,
nodeSelectorValidator: &FakeNodeSelectorValidator{},
}

_, err := reconciler.Reconcile(context.Background(), ctrl.Request{
NamespacedName: types.NamespacedName{
Name: driver.Name,
Namespace: driver.Namespace,
},
})

require.Error(t, err)
require.ErrorContains(t, err, patchErr.Error())
require.Equal(t, nvidiav1alpha1.NotReady, updater.LastErrorState)
}

func TestEnqueueAllNVIDIADrivers(t *testing.T) {
scheme := runtime.NewScheme()
require.NoError(t, nvidiav1alpha1.AddToScheme(scheme))
Expand All @@ -267,3 +334,45 @@ func TestEnqueueAllNVIDIADrivers(t *testing.T) {
sort.Strings(got)
require.Equal(t, []string{"default/driver-a", "default/driver-b"}, got)
}

func TestNVIDIADriverGenerationOrDefaultLabelChangedPredicate(t *testing.T) {
p := nvidiaDriverGenerationOrDefaultLabelChangedPredicate()

require.True(t, p.Update(event.TypedUpdateEvent[*nvidiav1alpha1.NVIDIADriver]{
ObjectOld: &nvidiav1alpha1.NVIDIADriver{ObjectMeta: metav1.ObjectMeta{Name: "driver", Generation: 1}},
ObjectNew: &nvidiav1alpha1.NVIDIADriver{ObjectMeta: metav1.ObjectMeta{Name: "driver", Generation: 2}},
}))

require.True(t, p.Update(event.TypedUpdateEvent[*nvidiav1alpha1.NVIDIADriver]{
ObjectOld: &nvidiav1alpha1.NVIDIADriver{
ObjectMeta: metav1.ObjectMeta{
Name: "driver",
Generation: 1,
},
},
ObjectNew: &nvidiav1alpha1.NVIDIADriver{
ObjectMeta: metav1.ObjectMeta{
Name: "driver",
Generation: 1,
Labels: map[string]string{consts.DefaultNVIDIADriverLabel: "true"},
},
},
}))

require.False(t, p.Update(event.TypedUpdateEvent[*nvidiav1alpha1.NVIDIADriver]{
ObjectOld: &nvidiav1alpha1.NVIDIADriver{
ObjectMeta: metav1.ObjectMeta{
Name: "driver",
Generation: 1,
Labels: map[string]string{"example.com/label": "old"},
},
},
ObjectNew: &nvidiav1alpha1.NVIDIADriver{
ObjectMeta: metav1.ObjectMeta{
Name: "driver",
Generation: 1,
Labels: map[string]string{"example.com/label": "new"},
},
},
}))
}
Loading
Loading