From 20f0c243e5993105e1bb120981654898fa20a53a Mon Sep 17 00:00:00 2001 From: Leonardo Ochoa Aday Date: Fri, 27 Nov 2026 14:58:32 +0100 Subject: [PATCH] feat: derive DeviceConfig Ready condition from workload status Ready was set True after any successful reconcile, before the driver was built or the device plugin was running. Derive it from driver and device plugin availability so oc wait --for=condition=Ready is meaningful, with DriverNotReady/DevicePluginNotReady reasons. Add Ready/Reason/Message printer columns, use optimistic locking on status patches, and keep watcher-owned status from being overwritten. Refs: ROCm/gpu-operator#688 Signed-off-by: Leonardo Ochoa-Aday --- api/v1alpha1/deviceconfig_types.go | 4 + config/crd/bases/amd.com_deviceconfigs.yaml | 16 +++- docs/drivers/installation.md | 16 +++- internal/conditions/deviceconfig.go | 38 +++++++++ internal/conditions/deviceconfig_test.go | 85 +++++++++++++++++++ .../controllers/device_config_reconciler.go | 13 ++- internal/controllers/watchers/daemonset.go | 22 +++-- 7 files changed, 184 insertions(+), 10 deletions(-) create mode 100644 internal/conditions/deviceconfig_test.go diff --git a/api/v1alpha1/deviceconfig_types.go b/api/v1alpha1/deviceconfig_types.go index 6b45afaaf..56bf370c4 100644 --- a/api/v1alpha1/deviceconfig_types.go +++ b/api/v1alpha1/deviceconfig_types.go @@ -1067,6 +1067,10 @@ type DeviceConfigStatus struct { //+kubebuilder:object:root=true //+kubebuilder:resource:scope=Namespaced,shortName=gpue //+kubebuilder:subresource:status +//+kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +//+kubebuilder:printcolumn:name="Reason",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].reason` +//+kubebuilder:printcolumn:name="Message",type=string,priority=1,JSONPath=`.status.conditions[?(@.type=="Ready")].message` +//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` // DeviceConfig describes how to enable AMD GPU device // +operator-sdk:csv:customresourcedefinitions:displayName="DeviceConfig",resources={{Module,v1beta1,modules.kmm.sigs.x-k8s.io},{Daemonset,v1,apps},{services,v1,core},{Pod,v1,core}} diff --git a/config/crd/bases/amd.com_deviceconfigs.yaml b/config/crd/bases/amd.com_deviceconfigs.yaml index 47e36f629..f4374023a 100644 --- a/config/crd/bases/amd.com_deviceconfigs.yaml +++ b/config/crd/bases/amd.com_deviceconfigs.yaml @@ -16,7 +16,21 @@ spec: singular: deviceconfig scope: Namespaced versions: - - name: v1alpha1 + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].reason + name: Reason + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].message + name: Message + priority: 1 + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 schema: openAPIV3Schema: description: DeviceConfig describes how to enable AMD GPU device diff --git a/docs/drivers/installation.md b/docs/drivers/installation.md index 2ea35a85b..1d687e322 100644 --- a/docs/drivers/installation.md +++ b/docs/drivers/installation.md @@ -338,7 +338,21 @@ If you are using DockerHub to host images, you don't need to specify the ```--do ### 3. Monitor Installation Status -Check the deployment status: +The `Ready` condition on the `DeviceConfig` is `True` only once the driver is loaded on every selected node (when the operator manages the driver) and the device plugin is available on every selected node (when enabled). You can watch it directly instead of looking for builder pods: + +```bash +kubectl get deviceconfigs -n kube-amd-gpu +# NAME READY REASON AGE +# test-deviceconfig False DriverNotReady 2m +# test-deviceconfig True OperatorReady 9m + +# block until ready, e.g. in scripts or CI +kubectl wait deviceconfig/test-deviceconfig -n kube-amd-gpu --for=condition=Ready --timeout=30m +``` + +`kubectl get deviceconfigs -o wide` also shows the condition message, e.g. `driver available on 1/3 nodes`. Possible reasons when not ready are `DriverNotReady`, `DevicePluginNotReady`, `ValidationError` and `NoMatchingNodes`. + +Check the full deployment status: ```bash kubectl get deviceconfigs test-deviceconfig -n kube-amd-gpu -o yaml diff --git a/internal/conditions/deviceconfig.go b/internal/conditions/deviceconfig.go index eb0533e8a..0b707bc3e 100644 --- a/internal/conditions/deviceconfig.go +++ b/internal/conditions/deviceconfig.go @@ -17,6 +17,8 @@ limitations under the License. package conditions import ( + "fmt" + amdv1alpha1 "github.com/ROCm/gpu-operator/api/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -37,8 +39,44 @@ const ( ReadyStatus = "OperatorReady" // NoMatchingNodes indicates no cluster nodes match the DeviceConfig selector NoMatchingNodes = "NoMatchingNodes" + // DriverNotReady indicates the driver is not yet built/loaded on all targeted nodes + DriverNotReady = "DriverNotReady" + // DevicePluginNotReady indicates the device plugin is not yet available on all targeted nodes + DevicePluginNotReady = "DevicePluginNotReady" ) +// componentReady reports whether a workload is available on every node it targets. +// A workload that targets zero nodes is not considered ready. +func componentReady(s amdv1alpha1.DeploymentStatus) bool { + return s.DesiredNumber > 0 && s.AvailableNumber >= s.DesiredNumber +} + +// UpdateReadyFromStatus derives the Ready condition from the observed component status, +// so that Ready=True means the workloads are actually up, not just that a reconcile succeeded. +// driverManaged must be true when the operator manages the driver via KMM. +// If the Error condition is True, Ready is left untouched, because the error path owns it. +func UpdateReadyFromStatus(devConfig *amdv1alpha1.DeviceConfig, driverManaged bool) { + if errCond := findCondition(devConfig.Status.Conditions, ConditionTypeError); errCond != nil && errCond.Status == metav1.ConditionTrue { + return + } + status, reason, message := metav1.ConditionTrue, ReadyStatus, "" + switch d, dp := devConfig.Status.Drivers, devConfig.Status.DevicePlugin; { + case driverManaged && !componentReady(d): + status, reason = metav1.ConditionFalse, DriverNotReady + message = fmt.Sprintf("driver available on %d/%d nodes", d.AvailableNumber, d.DesiredNumber) + case devConfig.Spec.DevicePlugin.IsEnabled() && !componentReady(dp): + status, reason = metav1.ConditionFalse, DevicePluginNotReady + message = fmt.Sprintf("device plugin available on %d/%d nodes", dp.AvailableNumber, dp.DesiredNumber) + } + setCondition(devConfig, metav1.Condition{ + Type: ConditionTypeReady, + Status: status, + LastTransitionTime: metav1.Now(), + Reason: reason, + Message: message, + }) +} + type ConditionManager struct{} func NewDeviceConfigConditionMgr() ConditionUpdater { diff --git a/internal/conditions/deviceconfig_test.go b/internal/conditions/deviceconfig_test.go new file mode 100644 index 000000000..a9da459bc --- /dev/null +++ b/internal/conditions/deviceconfig_test.go @@ -0,0 +1,85 @@ +/* +Copyright (c) Advanced Micro Devices, Inc. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the \"License\"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an \"AS IS\" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package conditions + +import ( + "testing" + + amdv1alpha1 "github.com/ROCm/gpu-operator/api/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestUpdateReadyFromStatus(t *testing.T) { + enabled, disabled := true, false + ready := amdv1alpha1.DeploymentStatus{DesiredNumber: 2, AvailableNumber: 2} + partial := amdv1alpha1.DeploymentStatus{DesiredNumber: 2, AvailableNumber: 1} + none := amdv1alpha1.DeploymentStatus{} + + tests := []struct { + name string + driverManaged bool + devicePlugin *bool + drivers amdv1alpha1.DeploymentStatus + dp amdv1alpha1.DeploymentStatus + errorTrue bool + wantStatus metav1.ConditionStatus + wantReason string + }{ + {"all ready", true, &enabled, ready, ready, false, metav1.ConditionTrue, ReadyStatus}, + {"driver building", true, &enabled, partial, ready, false, metav1.ConditionFalse, DriverNotReady}, + {"driver not scheduled yet", true, &enabled, none, ready, false, metav1.ConditionFalse, DriverNotReady}, + {"driver not managed", false, &enabled, none, ready, false, metav1.ConditionTrue, ReadyStatus}, + {"device plugin starting", true, &enabled, ready, partial, false, metav1.ConditionFalse, DevicePluginNotReady}, + {"device plugin disabled", true, &disabled, ready, none, false, metav1.ConditionTrue, ReadyStatus}, + {"nothing managed", false, &disabled, none, none, false, metav1.ConditionTrue, ReadyStatus}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dc := &amdv1alpha1.DeviceConfig{} + dc.Spec.DevicePlugin.EnableDevicePlugin = tt.devicePlugin + dc.Status.Drivers, dc.Status.DevicePlugin = tt.drivers, tt.dp + UpdateReadyFromStatus(dc, tt.driverManaged) + got := findCondition(dc.Status.Conditions, ConditionTypeReady) + if got == nil || got.Status != tt.wantStatus || got.Reason != tt.wantReason { + t.Fatalf("got %+v, want status=%s reason=%s", got, tt.wantStatus, tt.wantReason) + } + }) + } +} + +func TestUpdateReadyFromStatusKeepsReadyOnError(t *testing.T) { + dc := &amdv1alpha1.DeviceConfig{} + dc.Status.Conditions = []metav1.Condition{ + {Type: ConditionTypeError, Status: metav1.ConditionTrue, Reason: ValidationError}, + {Type: ConditionTypeReady, Status: metav1.ConditionFalse, Reason: ValidationError}, + } + UpdateReadyFromStatus(dc, false) + got := findCondition(dc.Status.Conditions, ConditionTypeReady) + if got.Status != metav1.ConditionFalse || got.Reason != ValidationError { + t.Fatalf("Ready must not be changed while Error=True, got %+v", got) + } +} + +func TestUpdateReadyFromStatusKeepsTransitionTime(t *testing.T) { + dc := &amdv1alpha1.DeviceConfig{} + UpdateReadyFromStatus(dc, false) + first := findCondition(dc.Status.Conditions, ConditionTypeReady).LastTransitionTime + UpdateReadyFromStatus(dc, false) + if got := findCondition(dc.Status.Conditions, ConditionTypeReady).LastTransitionTime; !got.Equal(&first) { + t.Fatalf("LastTransitionTime changed without a status transition: %v -> %v", first, got) + } +} diff --git a/internal/controllers/device_config_reconciler.go b/internal/controllers/device_config_reconciler.go index ee1a6a5b0..b8c8bb557 100644 --- a/internal/controllers/device_config_reconciler.go +++ b/internal/controllers/device_config_reconciler.go @@ -121,7 +121,7 @@ func NewDeviceConfigReconciler( helper := newDeviceConfigReconcilerHelper(client, kmmHandler, dpHandler, nlHandler, upgradeMgrHandler, remediationMgrHandler, metricsHandler, testrunnerHandler, configmanagerHandler, workerMgr, isOpenShift, kmmWatchEnabled) podEventHandler := watchers.NewPodEventHandler(client, workerMgr) nodeEventHandler := watchers.NewNodeEventHandler(client, workerMgr) - daemonsetEventHandler := watchers.NewDaemonsetEventHandler(client) + daemonsetEventHandler := watchers.NewDaemonsetEventHandler(client, kmmWatchEnabled) return &DeviceConfigReconciler{ Client: client, kmmWatchEnabled: kmmWatchEnabled, @@ -667,8 +667,8 @@ func (dcrh *deviceConfigReconcilerHelper) buildDeviceConfigStatus(ctx context.Co // Successfully processed the config devConfig.Status.ObservedGeneration = devConfig.Generation + // Ready is derived from the component status in updateDeviceConfigStatus dcrh.conditionUpdater.DeleteErrorCondition(devConfig) - dcrh.conditionUpdater.SetReadyCondition(devConfig, metav1.ConditionTrue, conditions.ReadyStatus, "") return nil } @@ -682,8 +682,15 @@ func (dcrh *deviceConfigReconcilerHelper) updateDeviceConfigStatus(ctx context.C return err } originalObj := latestObj.DeepCopy() + // DevicePlugin and MetricsExporter status are owned by the daemonset watcher, + // keep the latest persisted values instead of the possibly stale in-memory copy + devicePluginStatus, metricsExporterStatus := latestObj.Status.DevicePlugin, latestObj.Status.MetricsExporter devConfig.Status.DeepCopyInto(&latestObj.Status) - if err := dcrh.client.Status().Patch(ctx, latestObj, client.MergeFrom(originalObj)); err != nil { + latestObj.Status.DevicePlugin, latestObj.Status.MetricsExporter = devicePluginStatus, metricsExporterStatus + conditions.UpdateReadyFromStatus(latestObj, dcrh.shouldUseKMMOperatorLevel(latestObj)) + // optimistic lock: the conditions list is replaced as a whole by a merge patch, + // so fail on conflict and retry rather than overwrite a concurrent status update + if err := dcrh.client.Status().Patch(ctx, latestObj, client.MergeFromWithOptions(originalObj, client.MergeFromWithOptimisticLock{})); err != nil { return err } return nil diff --git a/internal/controllers/watchers/daemonset.go b/internal/controllers/watchers/daemonset.go index 5c5e5a0ec..70edf9e3e 100644 --- a/internal/controllers/watchers/daemonset.go +++ b/internal/controllers/watchers/daemonset.go @@ -50,6 +50,7 @@ import ( "github.com/ROCm/gpu-operator/api/v1alpha1" utils "github.com/ROCm/gpu-operator/internal" + "github.com/ROCm/gpu-operator/internal/conditions" ) type DaemonsetPredicate struct { @@ -85,14 +86,16 @@ type DaemonsetEventHandlerAPI interface { Generic(ctx context.Context, evt event.GenericEvent, q workqueue.TypedRateLimitingInterface[reconcile.Request]) } -func NewDaemonsetEventHandler(client client.Client) DaemonsetEventHandlerAPI { +func NewDaemonsetEventHandler(client client.Client, kmmWatchEnabled bool) DaemonsetEventHandlerAPI { return &DaemonsetEventHandler{ - client: client, + client: client, + kmmWatchEnabled: kmmWatchEnabled, } } type DaemonsetEventHandler struct { - client client.Client + client client.Client + kmmWatchEnabled bool } // Create handle create event @@ -157,7 +160,11 @@ func (h *DaemonsetEventHandler) patchDeviceConfigNodeStatus(ctx context.Context, if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { devConfig := &v1alpha1.DeviceConfig{} err := h.client.Get(ctx, types.NamespacedName{Name: devConfigName, Namespace: ds.Namespace}, devConfig) - if err != nil && !k8serrors.IsNotFound(err) { + if err != nil { + if k8serrors.IsNotFound(err) { + // owner DeviceConfig is gone, nothing to patch + return nil + } logger.Error(err, "cannot get DeviceConfig for handling daemonset event", "namespace", ds.Namespace, "name", ds.Name) return err @@ -170,7 +177,12 @@ func (h *DaemonsetEventHandler) patchDeviceConfigNodeStatus(ctx context.Context, case strings.HasSuffix(ds.Name, utils.DevicePluginNameSuffix): h.handleDevicePluginStatus(ds, devConfig) } - err = h.client.Status().Patch(ctx, devConfig, client.MergeFrom(devConfigCopy)) + // device plugin availability affects readiness, which the reconciler does not + // re-evaluate on daemonset status changes, so refresh it here + conditions.UpdateReadyFromStatus(devConfig, h.kmmWatchEnabled && utils.ShouldUseKMM(devConfig)) + // optimistic lock: the conditions list is replaced as a whole by a merge patch, + // so fail on conflict and retry rather than overwrite a concurrent status update + err = h.client.Status().Patch(ctx, devConfig, client.MergeFromWithOptions(devConfigCopy, client.MergeFromWithOptimisticLock{})) if err != nil && !k8serrors.IsNotFound(err) { logger.Error(err, "cannot patch DeviceConfig status") }