/* Copyright 2025 The Kubernetes Authors. 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 driver import ( "context" "errors" "fmt" "os" "time" "github.com/containerd/nri/pkg/api" "github.com/go-logr/logr" "github.com/kubernetes-sigs/dra-driver-cpu/internal/ctxlog" "github.com/kubernetes-sigs/dra-driver-cpu/pkg/device" cpumetrics "github.com/kubernetes-sigs/dra-driver-cpu/pkg/metrics" "github.com/kubernetes-sigs/dra-driver-cpu/pkg/store" resourceapi "k8s.io/api/resource/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/dynamic-resource-allocation/kubeletplugin" "k8s.io/dynamic-resource-allocation/resourceclaim" "k8s.io/dynamic-resource-allocation/resourceslice" "k8s.io/utils/cpuset" cdiparser "tags.cncf.io/container-device-interface/pkg/parser" ) // PublishResources publishes ResourceSlice for CPU resources. func (cp *CPUDriver) PublishResources(ctx context.Context) { ctx, logger := ctxlog.WithValues(ctx, "opID", generateShortID(opIDLen), "deviceMode", cp.cpuDeviceMode, "groupBy", cp.cpuDeviceGroupBy) logger.V(4).Info("begin: publishing resources") defer logger.V(4).Info("end: publishing resources") if cp.topology.deviceSlices == nil { logger.Info("no devices to publish or error occurred") return } slices := make([]resourceslice.Slice, 0, len(cp.topology.deviceSlices)) for _, chunk := range cp.topology.deviceSlices { slices = append(slices, resourceslice.Slice{Devices: chunk}) } resources := resourceslice.DriverResources{ Pools: map[string]resourceslice.Pool{ // All slices are published under the same pool for this node. cp.nodeName: {Slices: slices}, }, } err := cp.draPlugin.PublishResources(ctx, resources) if err != nil { logger.Error(err, "error publishing resources") } } // PrepareResourceClaims is called by the kubelet to prepare a resource claim. func (cp *CPUDriver) PrepareResourceClaims(ctx context.Context, claims []*resourceapi.ResourceClaim) (map[types.UID]kubeletplugin.PrepareResult, error) { _, logger := ctxlog.WithValues(ctx, "opID", generateShortID(opIDLen)) logger.V(4).Info("begin: preparing resource claims", "numClaims", len(claims)) defer logger.V(4).Info("end: preparing resource claims", "numClaims", len(claims)) cp.waitForInitialSync(ctx, logger) result := make(map[types.UID]kubeletplugin.PrepareResult) for _, claim := range claims { start := time.Now() cLogger := logger.WithValues("claim", ctxlog.KObj(claim), "claimUID", claim.UID) result[claim.UID] = cp.prepareResourceClaim(ctx, cLogger, claim) prepareResult := cpumetrics.ResultSuccess if result[claim.UID].Err != nil { prepareResult = cpumetrics.ResultError } cp.metrics.RecordPrepare(prepareResult, time.Since(start)) } return result, nil } // waitForInitialSync gives the first Synchronize after a restart a short window // to complete, so the common restart path prepares on the first attempt. It must // not hold stateMu while waiting: Synchronize needs it to close initialSync. // prepareResourceClaim still enforces the gate if the wait times out. func (cp *CPUDriver) waitForInitialSync(ctx context.Context, logger logr.Logger) { cp.stateMu.Lock() synced, initialSync := cp.hasSynchronized, cp.initialSync cp.stateMu.Unlock() if synced || initialSync == nil { return } logger.V(2).Info("waiting for initial NRI synchronization", "timeout", cp.initialSyncWait) timer := time.NewTimer(cp.initialSyncWait) defer timer.Stop() select { case <-initialSync: case <-ctx.Done(): case <-timer.C: } } // getCDISpecKey returns the claim-level key ("claim-") used to name the // single CDI spec file on disk that holds all request devices for a claim. func getCDISpecKey(uid types.UID) string { return fmt.Sprintf("claim-%s", uid) } // getCDIDeviceName returns the CDI device name inside a claim's spec file: // "claim-_" for a named request, or "claim-" when request // is empty (legacy whole-claim allocation). func getCDIDeviceName(uid types.UID, request string) string { if request == "" { return getCDISpecKey(uid) } return fmt.Sprintf("%s_%s", getCDISpecKey(uid), request) } func getDRAEnvVar(uid types.UID, request string, cpus cpuset.CPUSet) string { if request == "" { return fmt.Sprintf("%s_%s=%s", cdiEnvVarPrefix, uid, cpus.String()) } return fmt.Sprintf("%s_%s_%s=%s", cdiEnvVarPrefix, uid, request, cpus.String()) } func (cp *CPUDriver) checkAdminAccess(claim *resourceapi.ResourceClaim) error { if claim.Status.Allocation == nil { return nil // nothing to do } for _, alloc := range claim.Status.Allocation.Devices.Results { if alloc.Driver != cp.driverName { continue } if alloc.AdminAccess != nil && *alloc.AdminAccess { return fmt.Errorf("admin access is not supported for device %q", alloc.Device) } } return nil } // reserveResourceClaimAllocation records a new claim allocation while applying // the shared-pool guard for currently running shared containers. A shared // container from the same pod may not have been created yet when this DRA hook // runs, so that case is detected later by the NRI CreateContainer check. func (cp *CPUDriver) reserveResourceClaimAllocation(logger logr.Logger, claim *resourceapi.ResourceClaim, requests map[string]cpuset.CPUSet) error { hasSharedContainers := len(cp.podState.GetContainersWithSharedCPUs()) > 0 return cp.allocationState.Reserve(logger, cp.checkpointMgr, store.ClaimIdentifierFrom(claim), requests, hasSharedContainers) } func (cp *CPUDriver) prepareGroupedResourceClaimLocked(logger logr.Logger, claim *resourceapi.ResourceClaim) kubeletplugin.PrepareResult { logger.V(4).Info("preparing grouped resource claim") if claim.Status.Allocation == nil { return kubeletplugin.PrepareResult{ Err: fmt.Errorf("claim %s/%s has no allocation", claim.Namespace, claim.Name), } } if cp.cpuDeviceGroupBy == device.GROUP_BY_MACHINE { if err := checkDeviceRequestCountUpTo(claim, 1, cp.driverName); err != nil { return kubeletplugin.PrepareResult{ Err: err, } } } if existingRequests, ok := cp.allocationState.GetResourceClaimRequests(claim.UID); ok { logger.V(2).Info("claim already has allocated CPUs in store, reusing assignment", "requests", fmt.Sprint(existingRequests)) // Even if the claim is already allocated in our in-memory store (which happens when a duplicate prepare // call is invoked without an intermediate unprepare), we must call prepareDevices and return the result back to Kubelet. // If the CDI file is already created on disk, the CDI manager will safely overwrite it with the same configuration. // This ensures that the CDI specification file is written/recreated on disk (for example, if the driver // pod restarted and synchronized its memory store from the runtime but did not recreate the CDI files on disk). return cp.prepareDevices(logger, claim, existingRequests) } var assignedCPUs cpuset.CPUSet requestCPUs := make(map[string]cpuset.CPUSet) allocatableCPUs := cp.allocationState.GetSharedCPUs() for _, alloc := range claim.Status.Allocation.Devices.Results { if alloc.Driver != cp.driverName { continue } claimCPUCount, err := device.ConsumedCPUCount(alloc, cp.driverName) if err != nil { return kubeletplugin.PrepareResult{Err: err} } logger.V(4).Info("found CPU request", "numCPUs", claimCPUCount, "device", alloc.Device) topo := cp.topology.CPUTopology // TODO: what if `claimCPUCount==0`? // The preferred hint comes from the request's opaque config (if any); the // group-specific branches below pick the actual CPUs out of it. preferredCPUs, err := cp.cpuAllocator.GetPreferredCPUs(logger, claim.Status.Allocation, alloc) if err != nil { return kubeletplugin.PrepareResult{Err: err} } var cur cpuset.CPUSet switch cp.cpuDeviceGroupBy { case device.GROUP_BY_SOCKET: socketID, ok := cp.topology.NameToSocketID[alloc.Device] if !ok { return kubeletplugin.PrepareResult{Err: fmt.Errorf("no valid socket ID found for device %s", alloc.Device)} } socketCPUs := topo.CPUDetails.CPUsInSockets(socketID) availableCPUsForDevice := allocatableCPUs.Difference(assignedCPUs).Intersection(socketCPUs) logger.V(4).Info("socket CPU availability", "socketID", socketID, "socketCPUs", socketCPUs.String(), "availableCPUs", availableCPUsForDevice.String()) cur, err = cp.cpuAllocator.Allocate(logger, availableCPUsForDevice, preferredCPUs, claimCPUCount) case device.GROUP_BY_NUMA_NODE: numaNodeID, ok := cp.topology.NameToNUMANodeID[alloc.Device] if !ok { return kubeletplugin.PrepareResult{Err: fmt.Errorf("no valid NUMA node ID found for device %s", alloc.Device)} } numaCPUs := topo.CPUDetails.CPUsInNUMANodes(numaNodeID) availableCPUsForDevice := allocatableCPUs.Difference(assignedCPUs).Intersection(numaCPUs) logger.V(4).Info("NUMA node CPU availability", "numaNodeID", numaNodeID, "numaCPUs", numaCPUs.String(), "availableCPUs", availableCPUsForDevice.String()) cur, err = cp.cpuAllocator.Allocate(logger, availableCPUsForDevice, preferredCPUs, claimCPUCount) case device.GROUP_BY_MACHINE: // no mapping needed in machine mode - just one device = the whole machine availableCPUs := topo.CPUDetails.CPUs().Difference(cp.topology.ReservedCPUs) logger.V(4).Info("Machine CPU availability", "availableCPUs", availableCPUs.String()) cur, err = cp.cpuAllocator.Allocate(logger, availableCPUs, preferredCPUs, claimCPUCount) logger.V(2).Info("using opaque config CPU assignment", "device", alloc.Device, "assigned", cur.String()) } if err != nil { return kubeletplugin.PrepareResult{Err: err} } if err := cp.cpuAllocator.Validate(cur, assignedCPUs, cp.allocationState.GetPreparedCPUs()); err != nil { return kubeletplugin.PrepareResult{Err: err} } assignedCPUs = assignedCPUs.Union(cur) // Strip any FirstAvailable subrequest suffix ("req/sub" -> "req") to match pod claim references. reqName := resourceclaim.BaseRequestRef(alloc.Request) requestCPUs[reqName] = requestCPUs[reqName].Union(cur) logger.V(2).Info("CPU assignment for device", "request", reqName, "device", alloc.Device, "assigned", cur.String(), "allAssigned", assignedCPUs.String()) } if assignedCPUs.Size() == 0 { logger.V(6).Info("claim has no CPU allocations for this driver") return kubeletplugin.PrepareResult{} } // Reserve before CDI I/O so concurrent Prepare calls cannot select the same CPUs. if err := cp.reserveResourceClaimAllocation(logger, claim, requestCPUs); err != nil { return kubeletplugin.PrepareResult{Err: err} } result := cp.prepareDevices(logger, claim, requestCPUs) if result.Err != nil { if err := cp.allocationState.Release(logger, cp.checkpointMgr, claim.UID); err != nil { result.Err = errors.Join(result.Err, err) } return result } cp.metrics.RecordClaimAllocatedCPUs(assignedCPUs.Size()) cp.refreshAllocationMetrics() return result } func (cp *CPUDriver) prepareResourceClaim(ctx context.Context, logger logr.Logger, claim *resourceapi.ResourceClaim) kubeletplugin.PrepareResult { cp.stateMu.Lock() defer cp.stateMu.Unlock() if err := ctx.Err(); err != nil { return kubeletplugin.PrepareResult{Err: err} } // DRA registration precedes NRI startup. Until the first recovery commits, // the empty allocation store does not describe CPUs held by live containers. if !cp.hasSynchronized { return kubeletplugin.PrepareResult{Err: fmt.Errorf("initial NRI synchronization has not completed; retry preparation")} } if err := cp.checkAdminAccess(claim); err != nil { return kubeletplugin.PrepareResult{Err: err} } if cp.cpuDeviceMode == device.CPU_DEVICE_MODE_GROUPED { return cp.prepareGroupedResourceClaimLocked(logger, claim) } return cp.prepareIndividualResourceClaimLocked(logger, claim) } func (cp *CPUDriver) prepareIndividualResourceClaimLocked(logger logr.Logger, claim *resourceapi.ResourceClaim) kubeletplugin.PrepareResult { logger.V(4).Info("preparing individual resource claim") if claim.Status.Allocation == nil { return kubeletplugin.PrepareResult{ Err: fmt.Errorf("claim %s/%s has no allocation", claim.Namespace, claim.Name), } } var claimCPUSet cpuset.CPUSet requestCPUs := make(map[string]cpuset.CPUSet) for _, alloc := range claim.Status.Allocation.Devices.Results { if alloc.Driver != cp.driverName { continue } cpuID, ok := cp.topology.NameToCPUID[alloc.Device] if !ok { return kubeletplugin.PrepareResult{ Err: fmt.Errorf("device %q not found in device to CPU ID map", alloc.Device), } } cpu := cpuset.New(cpuID) claimCPUSet = claimCPUSet.Union(cpu) // Strip any FirstAvailable subrequest suffix ("req/sub" -> "req") to match pod claim references. reqName := resourceclaim.BaseRequestRef(alloc.Request) requestCPUs[reqName] = requestCPUs[reqName].Union(cpu) } if claimCPUSet.IsEmpty() { logger.V(6).Info("claim has no CPU allocations for this driver") return kubeletplugin.PrepareResult{} } if existingRequests, ok := cp.allocationState.GetResourceClaimRequests(claim.UID); ok { logger.V(2).Info("claim already has allocated CPUs in store, reusing assignment", "requests", fmt.Sprint(existingRequests)) existingCPUs, _ := cp.allocationState.GetResourceClaimAllocation(claim.UID) if !existingCPUs.Equals(claimCPUSet) { // This should realistically never happen as the claim is immutable. return kubeletplugin.PrepareResult{ Err: fmt.Errorf("claim %s/%s is already prepared with different CPUs %s (requested %s)", claim.Namespace, claim.Name, existingCPUs.String(), claimCPUSet.String()), } } return cp.prepareDevices(logger, claim, existingRequests) } // All the CPUs allocated to a claim must not be prepared for another claim. allocatableCPUs := cp.allocationState.GetSharedCPUs() if !claimCPUSet.IsSubsetOf(allocatableCPUs) { return kubeletplugin.PrepareResult{ Err: fmt.Errorf("claim %s/%s has overlapping device assignment with other claims", claim.Namespace, claim.Name), } } // Reserve before CDI I/O so concurrent Prepare calls cannot select the same CPUs. if err := cp.reserveResourceClaimAllocation(logger, claim, requestCPUs); err != nil { return kubeletplugin.PrepareResult{Err: err} } result := cp.prepareDevices(logger, claim, requestCPUs) if result.Err != nil { if err := cp.allocationState.Release(logger, cp.checkpointMgr, claim.UID); err != nil { result.Err = errors.Join(result.Err, err) } return result } cp.metrics.RecordClaimAllocatedCPUs(claimCPUSet.Size()) cp.refreshAllocationMetrics() return result } func (cp *CPUDriver) prepareDevices(logger logr.Logger, claim *resourceapi.ResourceClaim, requestCPUs map[string]cpuset.CPUSet) kubeletplugin.PrepareResult { deviceNames := make(map[string]string, len(requestCPUs)) preparedDevices := []kubeletplugin.Device{} for _, allocResult := range claim.Status.Allocation.Devices.Results { if allocResult.Driver != cp.driverName { continue } reqKey := resourceclaim.BaseRequestRef(allocResult.Request) cpus, ok := requestCPUs[reqKey] if !ok { // This cannot happen on a new NodePrepareResources call; it only happens // when reusing an existing allocation from the store. After upgrading from // an older driver that wrote one CDI device per claim (DRA_CPUSET_=), // Synchronize restores the claim under key "". If kubelet later restarts and // re-calls NodePrepareResources for that claim, allocResult.Request will not // match "", so fall back to "" to preserve the existing claim- CDI device. cpus, ok = requestCPUs[""] if !ok { return kubeletplugin.PrepareResult{ Err: fmt.Errorf("missing CPU allocation for request %q in claim %s/%s", reqKey, claim.Namespace, claim.Name), } } reqKey = "" } deviceName := getCDIDeviceName(claim.UID, reqKey) if _, exists := deviceNames[deviceName]; !exists { deviceNames[deviceName] = getDRAEnvVar(claim.UID, reqKey, cpus) } qualifiedName := cdiparser.QualifiedName(cdiVendor, cdiClass, deviceName) logger.V(6).Info("prepared CDI device", "request", reqKey, "cdiDeviceName", deviceName, "envVar", deviceNames[deviceName], "qualifiedName", qualifiedName) preparedDevice := kubeletplugin.Device{ PoolName: allocResult.Pool, DeviceName: allocResult.Device, CDIDeviceIDs: []string{qualifiedName}, } if allocResult.Request != "" { preparedDevice.Requests = []string{allocResult.Request} } if attrs, ok := getDeviceAttributes(cp.topology.deviceSlices, allocResult.Device); ok && len(attrs) > 0 { metadataAttrs := make(map[string]resourceapi.DeviceAttribute, len(attrs)) for k, v := range attrs { metadataAttrs[string(k)] = v } if quantity, ok := device.LookupConsumedCapacity(allocResult.ConsumedCapacity, cp.driverName); ok { allocatedCount := quantity.Value() metadataAttrs[string(device.AttributeAllocatedNumCPUs)] = resourceapi.DeviceAttribute{ IntValue: &allocatedCount, } } preparedDevice.Metadata = &kubeletplugin.DeviceMetadata{ Attributes: metadataAttrs, } logger.V(6).Info("added device metadata", "device", allocResult.Device, "numAttrs", len(metadataAttrs)) } preparedDevices = append(preparedDevices, preparedDevice) } // Write all per-request devices into one claim-level CDI spec file keyed by // getCDISpecKey(claim.UID), so UnprepareResourceClaims and Synchronize can // look up or remove the claim's CDI state by claim UID alone. if err := cp.cdiMgr.AddDevice(logger, getCDISpecKey(claim.UID), deviceNames); err != nil { return kubeletplugin.PrepareResult{Err: err} } logger.V(4).Info("prepared devices for resource claim", "preparedDevices", preparedDevices) return kubeletplugin.PrepareResult{ Devices: preparedDevices, } } // UnprepareResourceClaims is called by the kubelet to unprepare the resources for a claim. func (cp *CPUDriver) UnprepareResourceClaims(ctx context.Context, claims []kubeletplugin.NamespacedObject) (map[types.UID]error, error) { _, logger := ctxlog.WithValues(ctx, "opID", generateShortID(opIDLen)) logger.V(4).Info("begin: unpreparing resource claims", "numClaims", len(claims)) defer logger.V(4).Info("end: unpreparing resource claims", "numClaims", len(claims)) result := make(map[types.UID]error) if len(claims) == 0 { return result, nil } for _, claim := range claims { // note kubeletplugin.NamespacedObject doesn't implement KMetadata cLogger := logger.WithValues("claim", claim.String(), "claimUID", claim.UID) cLogger.V(2).Info("unpreparing resource claim") start := time.Now() err := cp.unprepareResourceClaim(ctx, cLogger, claim) result[claim.UID] = err if err != nil { cLogger.Error(err, "error unpreparing resources for claim") cp.metrics.RecordUnprepare(cpumetrics.ResultError, time.Since(start)) } else { cp.metrics.RecordUnprepare(cpumetrics.ResultSuccess, time.Since(start)) } } return result, nil } func (cp *CPUDriver) unprepareResourceClaim(ctx context.Context, logger logr.Logger, claim kubeletplugin.NamespacedObject) error { updates, updater, err := cp.releaseClaim(ctx, logger, claim) if err != nil || len(updates) == 0 { return err } // Running shared containers still have the narrower cpuset. Widen them // before returning: releaseClaim dropped stateMu so the runtime call is not // made under it, and kubeletplugin serializes Unprepare against Prepare, so // no other claim can be reserved in between. logger.V(2).Info("reconciling shared containers after claim release", "numContainers", len(updates)) failed, err := updater.UpdateContainers(updates) // A failed update is not retried: the containers keep the narrower cpuset // until their next lifecycle event, as without this option. The claim is // already released, so failing Unprepare here would only make kubelet // retry a release that has already happened. if err != nil { logger.Error(err, "shared container reconcile did not complete", "numFailed", len(failed)) } for _, update := range failed { logger.Info("runtime refused a shared container update", "containerID", update.GetContainerId()) } return nil } // releaseClaim removes the CDI spec and releases the allocation, returning the // shared-container updates the caller should send once stateMu is dropped, and // the updater to send them with: Configure can reset cp.reconcile on reconnect, // so the caller must not read it after the lock is gone. func (cp *CPUDriver) releaseClaim(ctx context.Context, logger logr.Logger, claim kubeletplugin.NamespacedObject) ([]*api.ContainerUpdate, containerUpdater, error) { cp.stateMu.Lock() defer cp.stateMu.Unlock() if err := ctx.Err(); err != nil { return nil, nil, err } // Remove the CDI spec first. If that fails, keep the allocation recorded so // the driver does not make those CPUs available while stale CDI state remains. if err := cp.cdiMgr.RemoveDevice(logger, getCDISpecKey(claim.UID)); err != nil { return nil, nil, err } if err := cp.allocationState.Release(logger, cp.checkpointMgr, claim.UID); err != nil { return nil, nil, err } cp.refreshAllocationMetrics() if cp.reconcile == nil || cp.reconcile.containerUpdater == nil { return nil, nil, nil } updates, err := sharedContainerUpdatesFor(logger, cp.allocationState, cp.podState, types.UID("")) if err != nil { logger.Error(err, "cannot reconcile shared containers") return nil, nil, nil } return updates, cp.reconcile.containerUpdater, nil } // HandleError is called by the kubelet plugin framework when an error occurs in the background, // for example while publishing ResourceSlices. func (cp *CPUDriver) HandleError(ctx context.Context, err error, msg string) { logger := ctxlog.FromContext(ctx) // Log the error using the standard Kubernetes error handler runtime.HandleErrorWithContext(ctx, err, msg) // For unrecoverable errors, exit immediately with a clear error message. // This fail-fast behavior is intentional for early project maturity to surface // issues quickly rather than silently continuing in a broken state. if !errors.Is(err, kubeletplugin.ErrRecoverable) { logger.Error(err, "fatal unrecoverable error in DRA driver, exiting", "driver", cp.driverName, "node", cp.nodeName, "message", msg, ) ctxlog.Flush() os.Exit(1) } } func checkDeviceRequestCountUpTo(claim *resourceapi.ResourceClaim, limit int64, driverName string) error { // we need to backtrack the requests from the allocations, // because driverName (from allocation result) is a parameter we get, // while deviceClass (from allocation request) is not something we can // safely infer. requestsForDriver := sets.New[string]() for _, result := range claim.Status.Allocation.Devices.Results { if result.Driver == driverName { requestsForDriver.Insert(result.Request) } } for _, req := range claim.Spec.Devices.Requests { if req.Exactly != nil { if !requestsForDriver.Has(req.Name) { continue } if req.Exactly.Count > limit { return fmt.Errorf("claim %s/%s: driver grouping mode %q supports exact device request up to %d", claim.Namespace, claim.Name, device.GROUP_BY_MACHINE, limit) } // safe to continue here: the apiserver guarantees only one between Exactly and FirstAvailable will be set continue } for _, subrequest := range req.FirstAvailable { requestName := req.Name + "/" + subrequest.Name if !requestsForDriver.Has(requestName) { continue } if subrequest.Count > limit { return fmt.Errorf("claim %s/%s: driver grouping mode %q supports first available device request up to %d", claim.Namespace, claim.Name, device.GROUP_BY_MACHINE, limit) } } } return nil }