From ba306e20c020a5de33b6cbf2496070463a5128b4 Mon Sep 17 00:00:00 2001 From: AyushSrivastava1818 Date: Wed, 26 Aug 2026 00:18:38 +0530 Subject: [PATCH 1/2] fix(device): address verified device scheduling and topology edge cases - Guard against nil nodeInfo, deviceScoreMap, and score entries in NVIDIA topology scoring to prevent nil pointer panics on nodes with missing pair-score annotations. - Prevent silent scheduling bypass in Cambricon by preserving request.Nums and setting math.MaxInt32 on invalid/overflowing/fractional memory requests so requests reach Fit() and are properly rejected with CardInsufficientMemory. - Clean up legacy unstructured logging in Cambricon GenerateResourceRequests to use structured klog.V(5).InfoS. - Add regression coverage for GetResourceQuota verifying mutation isolation and safe deep copying when quota entries are present. Signed-off-by: AyushSrivastava1818 --- pkg/device/cambricon/device.go | 18 +++---- pkg/device/cambricon/device_test.go | 77 +++++++++++++++++++++++++++++ pkg/device/nvidia/device.go | 16 ++++-- pkg/device/nvidia/device_test.go | 59 ++++++++++++++++++++++ pkg/device/quota_test.go | 29 +++++++++++ 5 files changed, 186 insertions(+), 13 deletions(-) diff --git a/pkg/device/cambricon/device.go b/pkg/device/cambricon/device.go index 222b4cf3e0..0c9177d8c5 100644 --- a/pkg/device/cambricon/device.go +++ b/pkg/device/cambricon/device.go @@ -21,6 +21,7 @@ import ( "encoding/json" "flag" "fmt" + "math" "math/rand" "slices" "strings" @@ -230,30 +231,29 @@ func (dev *CambriconDevices) checkType(annos map[string]string, d device.DeviceU } func (dev *CambriconDevices) GenerateResourceRequests(ctr *corev1.Container) device.ContainerDeviceRequest { - klog.Info("Start to count mlu devices for container ", ctr.Name) + klog.V(5).InfoS("Counting MLU devices for container", "container", ctr.Name) mluResourceCount := corev1.ResourceName(MLUResourceCount) mluResourceMem := corev1.ResourceName(MLUResourceMemory) mluResourceCores := corev1.ResourceName(MLUResourceCores) - for idx, val := range ctr.Resources.Limits { - klog.Infoln("idx=", idx, "val=", val, ctr.Resources.Limits[mluResourceMem]) - } v, ok := ctr.Resources.Limits[mluResourceCount] if !ok { v, ok = ctr.Resources.Requests[mluResourceCount] } if ok { if n, ok := v.AsInt64(); ok { - klog.Info("Found cambricon devices") + klog.V(5).InfoS("Found cambricon devices", "container", ctr.Name, "count", n) memnum := 0 mem, ok := ctr.Resources.Limits[mluResourceMem] if !ok { mem, ok = ctr.Resources.Requests[mluResourceMem] } - klog.Infoln("mluResourceMem", mem, "ok=", ok, "memoryname=", mluResourceMem) if ok { - memnums, ok := mem.AsInt64() - klog.Infoln("mluResourceMem", mem, memnums) - if ok { + memnums, parsed := mem.AsInt64() + if !parsed || memnums < 0 || memnums > int64(math.MaxInt32)/int64(MemoryFactor) { + klog.ErrorS(nil, "cambricon memory request is not a plain integer within the int32 range; rejecting to avoid silent under-allocation", + "container", ctr.Name, "requested", mem.String()) + memnum = math.MaxInt32 + } else { memnum = int(memnums) * MemoryFactor } } diff --git a/pkg/device/cambricon/device_test.go b/pkg/device/cambricon/device_test.go index eb3ffa007e..3530182eb1 100644 --- a/pkg/device/cambricon/device_test.go +++ b/pkg/device/cambricon/device_test.go @@ -19,6 +19,7 @@ package cambricon import ( "context" "flag" + "math" "strings" "testing" "time" @@ -30,6 +31,7 @@ import ( "k8s.io/client-go/kubernetes/fake" "github.com/Project-HAMi/HAMi/pkg/device" + "github.com/Project-HAMi/HAMi/pkg/device/common" "github.com/Project-HAMi/HAMi/pkg/util/client" ) @@ -287,6 +289,42 @@ func Test_GenerateResourceRequests(t *testing.T) { Coresreq: int32(2), }, }, + { + name: "memory overflowing int32 is rejected, not truncated to zero", + args: corev1.Container{ + Resources: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + "cambricon.com/mlu": resource.MustParse("1"), + "cambricon.com/mlu.smlu.vmemory": resource.MustParse("16Gi"), + }, + }, + }, + want: device.ContainerDeviceRequest{ + Nums: 1, + Type: CambriconMLUDevice, + Memreq: math.MaxInt32, + MemPercentagereq: 0, + Coresreq: 100, + }, + }, + { + name: "decimal-form memory request is rejected, not treated as zero", + args: corev1.Container{ + Resources: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + "cambricon.com/mlu": resource.MustParse("1"), + "cambricon.com/mlu.smlu.vmemory": resource.MustParse("16.0Gi"), + }, + }, + }, + want: device.ContainerDeviceRequest{ + Nums: 1, + Type: CambriconMLUDevice, + Memreq: math.MaxInt32, + MemPercentagereq: 0, + Coresreq: 100, + }, + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -1164,3 +1202,42 @@ func TestDevices_AddResourceUsage(t *testing.T) { }) } } + +func Test_Fit_InvalidMemoryRejected(t *testing.T) { + config := CambriconConfig{ + ResourceMemoryName: "cambricon.com/mlu.smlu.vmemory", + ResourceCoreName: "cambricon.com/mlu.smlu.vcore", + ResourceCountName: "cambricon.com/mlu", + } + InitMLUDevice(config) + dev := CambriconDevices{} + + devices := []*device.DeviceUsage{ + { + ID: "mlu-0", + Type: CambriconMLUDevice, + Totalmem: 16384, + Totalcore: 100, + Count: 100, + Health: true, + }, + } + + pod := &corev1.Pod{} + + // Invalid request with Memreq: math.MaxInt32 (generated from invalid memory quantity) + req := dev.GenerateResourceRequests(&corev1.Container{ + Resources: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + "cambricon.com/mlu": resource.MustParse("1"), + "cambricon.com/mlu.smlu.vmemory": resource.MustParse("16Gi"), // overflows int32 + }, + }, + }) + assert.Equal(t, int32(1), req.Nums) + assert.Equal(t, int32(math.MaxInt32), req.Memreq) + + fit, _, reason := dev.Fit(devices, req, pod, &device.NodeInfo{}, &device.PodDevices{}) + assert.False(t, fit) + assert.Contains(t, reason, common.CardInsufficientMemory) +} diff --git a/pkg/device/nvidia/device.go b/pkg/device/nvidia/device.go index 57553c5210..ada8d88af9 100644 --- a/pkg/device/nvidia/device.go +++ b/pkg/device/nvidia/device.go @@ -935,6 +935,9 @@ func generateCombinations(request device.ContainerDeviceRequest, tmpDevs map[str func getDevicePairScoreMap(nodeInfo *device.NodeInfo) map[string]*device.DevicePairScore { deviceScoreMap := make(map[string]*device.DevicePairScore) + if nodeInfo == nil { + return deviceScoreMap + } for _, dev := range nodeInfo.Devices[NvidiaGPUDevice] { deviceScoreMap[dev.ID] = &dev.DevicePairScore @@ -954,11 +957,13 @@ func computeWorstSingleCard(nodeInfo *device.NodeInfo, request device.ContainerD for _, dev1 := range devices { totalScore := 0 scoreMapDev1 := deviceScoreMap[dev1.UUID] - for _, dev2 := range devices { - if dev1.UUID == dev2.UUID { - continue + if scoreMapDev1 != nil && scoreMapDev1.Scores != nil { + for _, dev2 := range devices { + if dev1.UUID == dev2.UUID { + continue + } + totalScore += scoreMapDev1.Scores[dev2.UUID] } - totalScore += scoreMapDev1.Scores[dev2.UUID] } if !found || totalScore < worstScore { found = true @@ -981,6 +986,9 @@ func computeBestCombination(nodeInfo *device.NodeInfo, combinations []device.Con for i := 0; i < len(partition)-1; i++ { dev1 := partition[i] scoreMapDev1 := deviceScoreMap[dev1.UUID] + if scoreMapDev1 == nil || scoreMapDev1.Scores == nil { + continue + } for z := i + 1; z < len(partition); z++ { dev2 := partition[z] totalScore += scoreMapDev1.Scores[dev2.UUID] diff --git a/pkg/device/nvidia/device_test.go b/pkg/device/nvidia/device_test.go index b980b12155..3d41b3de66 100644 --- a/pkg/device/nvidia/device_test.go +++ b/pkg/device/nvidia/device_test.go @@ -3042,3 +3042,62 @@ func TestFit_TopologyNegativeScores(t *testing.T) { assert.Assert(t, uuids["dev-2"]) }) } + +func TestComputeWorstSingleCard_MissingScoreEntries(t *testing.T) { + req := device.ContainerDeviceRequest{ + Type: NvidiaGPUDevice, + Nums: 1, + } + candidates := map[string]device.ContainerDevices{ + NvidiaGPUDevice: { + {UUID: "gpu-0"}, + {UUID: "gpu-1"}, + }, + } + + // 1. Nil nodeInfo does not panic + worst := computeWorstSingleCard(nil, req, candidates) + assert.Equal(t, len(worst), 1) + + // 2. NodeInfo without device score entries does not panic + nodeInfo := &device.NodeInfo{ + Devices: map[string][]device.DeviceInfo{ + NvidiaGPUDevice: { + {ID: "gpu-0"}, // DevicePairScore is empty/nil + {ID: "gpu-1"}, + }, + }, + } + worst = computeWorstSingleCard(nodeInfo, req, candidates) + assert.Equal(t, len(worst), 1) +} + +func TestComputeBestCombination_MissingScoreEntries(t *testing.T) { + combinations := []device.ContainerDevices{ + { + {UUID: "gpu-0"}, + {UUID: "gpu-1"}, + }, + { + {UUID: "gpu-1"}, + {UUID: "gpu-2"}, + }, + } + + // 1. Nil nodeInfo does not panic + best := computeBestCombination(nil, combinations) + assert.Equal(t, len(best), 2) + + // 2. NodeInfo without device score entries does not panic + nodeInfo := &device.NodeInfo{ + Devices: map[string][]device.DeviceInfo{ + NvidiaGPUDevice: { + {ID: "gpu-0"}, + {ID: "gpu-1"}, + {ID: "gpu-2"}, + }, + }, + } + best = computeBestCombination(nodeInfo, combinations) + assert.Equal(t, len(best), 2) +} diff --git a/pkg/device/quota_test.go b/pkg/device/quota_test.go index 654768dee6..14a85bfc7b 100644 --- a/pkg/device/quota_test.go +++ b/pkg/device/quota_test.go @@ -400,3 +400,32 @@ func TestUpdateQuota(t *testing.T) { t.Errorf("memory limit = %d, want 3000", got) } } + +func TestGetResourceQuota(t *testing.T) { + initTest() + qm := NewQuotaManager() + ns := "quota-copy-test" + t.Cleanup(func() { delete(qm.Quotas, ns) }) + + qm.Quotas[ns] = &DeviceQuota{ + "nvidia.com/gpumem": &Quota{Used: 1024, Limit: 2048, LimitSet: true}, + "nvidia.com/gpucores": &Quota{Used: 50, Limit: 100, LimitSet: true}, + } + + quotas := qm.GetResourceQuota() + nsQuotas, ok := quotas[ns] + if !ok || nsQuotas == nil { + t.Fatalf("expected quotas for %s, got nil", ns) + } + + memQuota, ok := (*nsQuotas)["nvidia.com/gpumem"] + if !ok || memQuota.Used != 1024 || memQuota.Limit != 2048 || !memQuota.LimitSet { + t.Errorf("unexpected memQuota: %+v", memQuota) + } + + // Verify deep copy mutation isolation + memQuota.Used = 9999 + if (*qm.Quotas[ns])["nvidia.com/gpumem"].Used == 9999 { + t.Errorf("modifying copy mutated original QuotaManager state") + } +} From 32f3878b128bd383a67fe5d3675f254abf71c341 Mon Sep 17 00:00:00 2001 From: AyushSrivastava1818 Date: Thu, 27 Aug 2026 20:34:50 +0530 Subject: [PATCH 2/2] fix(device): address verified device scheduling and topology edge cases Cambricon LockNode race (CodeRabbit finding #1): - LockNode now fetches live node state from Kubernetes API before checking DsmluLockTime, eliminating stale-cache false negatives. - setNodeLock includes metadata.resourceVersion in the JSON merge patch payload so the API server enforces optimistic concurrency and returns 409 Conflict on concurrent writes. - On conflict retry, re-fetches the node and aborts if an unexpired lock was placed by a concurrent caller, preventing overwrite. - Tests: stale-caller node case + concurrent patch-conflict scenario. NVIDIA invalid-memory scheduling bypass (CodeRabbit finding #2): - GenerateResourceRequests previously returned ContainerDeviceRequest{} (Nums==0) for invalid/overflowing/fractional gpumem values, causing Resourcereqs to drop the container and Scheduler.Filter to bypass HAMi scheduling entirely. - Now preserves Nums:int32(n) and sets Memreq:math.MaxInt32 so Fit() always sees the request and fails with CardInsufficientMemory. - Tests: overflow/decimal expectation updated; Test_Fit_InvalidMemoryRejected added to prove end-to-end rejection. Test fixture corrections (CodeRabbit nitpicks): - ResourceCoreName fixtures corrected from nvidia.com/gpumem to nvidia.com/gpucores in TestDevices_Fit and TestFit_DeviceCordon. - TestFit_MigPercentageRequestRejectsUndersizedTemplate migrated from deprecated MigTemplate to MigProfiles so selectMigCandidate is actually exercised. Signed-off-by: AyushSrivastava1818 --- pkg/device/cambricon/device.go | 70 ++++++++++++++++++--------- pkg/device/cambricon/device_test.go | 61 ++++++++++++++++++++++-- pkg/device/nvidia/device.go | 17 +++---- pkg/device/nvidia/device_test.go | 73 ++++++++++++++++++++++++++--- 4 files changed, 180 insertions(+), 41 deletions(-) diff --git a/pkg/device/cambricon/device.go b/pkg/device/cambricon/device.go index 7550ede26e..f02bfda7b4 100644 --- a/pkg/device/cambricon/device.go +++ b/pkg/device/cambricon/device.go @@ -99,26 +99,34 @@ func (dev *CambriconDevices) CommonWord() string { func (dev *CambriconDevices) setNodeLock(node *corev1.Node) error { ctx := context.Background() - patchedAnnotation, err := json.Marshal( - map[string]any{ - "metadata": map[string]map[string]string{"annotations": { - DsmluLockTime: time.Now().Format(time.RFC3339), - }}}) - if err != nil { - klog.ErrorS(err, "Failed to marshal node annotation", "node", node.Name) - return fmt.Errorf("marshal node annotation: %w", err) - } + nodeName := node.Name + patchData := fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, + DsmluLockTime, time.Now().Format(time.RFC3339), node.ResourceVersion) - _, err = client.GetClient().CoreV1().Nodes().Patch(ctx, node.Name, types.MergePatchType, patchedAnnotation, metav1.PatchOptions{}) + _, err := client.GetClient().CoreV1().Nodes().Patch(ctx, nodeName, types.MergePatchType, []byte(patchData), metav1.PatchOptions{}) for i := 0; i < retry && err != nil; i++ { - klog.ErrorS(err, "Failed to patch node annotation", "node", node.Name, "retry", i) + klog.ErrorS(err, "Failed to patch node annotation", "node", nodeName, "retry", i) time.Sleep(time.Duration(rand.Intn(i+1)) * 10 * time.Millisecond) - _, err = client.GetClient().CoreV1().Nodes().Patch(ctx, node.Name, types.MergePatchType, patchedAnnotation, metav1.PatchOptions{}) + + current, getErr := client.GetClient().CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{}) + if getErr != nil { + return fmt.Errorf("failed to get node on lock retry: %w", getErr) + } + if current.Annotations != nil { + if val, ok := current.Annotations[DsmluLockTime]; ok && val != "" { + if lockTime, parseErr := time.Parse(time.RFC3339, val); parseErr == nil && time.Since(lockTime) <= time.Minute*2 { + return fmt.Errorf("node %s has been locked within 2 minutes", nodeName) + } + } + } + patchData = fmt.Sprintf(`{"metadata":{"annotations":{"%s":"%s"},"resourceVersion":"%s"}}`, + DsmluLockTime, time.Now().Format(time.RFC3339), current.ResourceVersion) + _, err = client.GetClient().CoreV1().Nodes().Patch(ctx, nodeName, types.MergePatchType, []byte(patchData), metav1.PatchOptions{}) } if err != nil { return fmt.Errorf("setNodeLock exceeds retry count %d", retry) } - klog.InfoS("Node lock set", "node", node.Name) + klog.InfoS("Node lock set", "node", nodeName) return nil } @@ -126,23 +134,43 @@ func (dev *CambriconDevices) LockNode(n *corev1.Node, p *corev1.Pod) error { if !device.PodRequiresDevice(dev, p) { return nil } - if _, ok := n.Annotations[DsmluLockTime]; !ok { - return dev.setNodeLock(n) + ctx := context.Background() + nodeName := n.Name + + current, err := client.GetClient().CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("failed to get node for lock: %w", err) + } + if current.Annotations == nil { + current.Annotations = make(map[string]string) + } + lockVal, ok := current.Annotations[DsmluLockTime] + if !ok || lockVal == "" { + return dev.setNodeLock(current) } - lockTime, err := time.Parse(time.RFC3339, n.Annotations[DsmluLockTime]) + lockTime, err := time.Parse(time.RFC3339, lockVal) if err != nil { return err } if time.Since(lockTime) > time.Minute*2 { - klog.InfoS("Node lock expired", "node", n.Name, "lockTime", lockTime) - err = dev.ReleaseNodeLock(n, p) + klog.InfoS("Node lock expired", "node", nodeName, "lockTime", lockTime) + err = dev.ReleaseNodeLock(current, p) if err != nil { - klog.ErrorS(err, "Failed to release node lock", "node", n.Name) + klog.ErrorS(err, "Failed to release node lock", "node", nodeName) return err } - return dev.setNodeLock(n) + current, err = client.GetClient().CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{}) + if err != nil { + return fmt.Errorf("failed to re-get node after releasing expired lock: %w", err) + } + if current.Annotations != nil { + if val, ok := current.Annotations[DsmluLockTime]; ok && val != "" { + return fmt.Errorf("node %s has been locked within 2 minutes", nodeName) + } + } + return dev.setNodeLock(current) } - return fmt.Errorf("node %s has been locked within 2 minutes", n.Name) + return fmt.Errorf("node %s has been locked within 2 minutes", nodeName) } func (dev *CambriconDevices) ReleaseNodeLock(n *corev1.Node, p *corev1.Pod) error { diff --git a/pkg/device/cambricon/device_test.go b/pkg/device/cambricon/device_test.go index 2b3190767f..b92b39b3f7 100644 --- a/pkg/device/cambricon/device_test.go +++ b/pkg/device/cambricon/device_test.go @@ -531,9 +531,10 @@ func setupTest(t *testing.T) (*corev1.Node, *corev1.Pod, func(), *fake.Clientset func Test_LockNode(t *testing.T) { tests := []struct { - name string - annotations map[string]string - wantErr bool + name string + annotations map[string]string + callerAnnotations map[string]string + wantErr bool }{ { name: "node is not locked", @@ -547,6 +548,14 @@ func Test_LockNode(t *testing.T) { }, wantErr: true, }, + { + name: "stale caller node — lock on server but caller has no annotations", + annotations: map[string]string{ + DsmluLockTime: time.Now().Add(-time.Minute).Format(time.RFC3339), + }, + callerAnnotations: map[string]string{}, + wantErr: true, + }, { name: "lock time expired (more than 2 minutes)", annotations: map[string]string{ @@ -569,8 +578,17 @@ func Test_LockNode(t *testing.T) { client.KubeClient = clientset defer teardown() - // Set up the node with the specified annotations. + // Set up the node on the server with the specified annotations. node.Annotations = tt.annotations + _, err := clientset.CoreV1().Nodes().Update(context.TODO(), node, metav1.UpdateOptions{}) + if err != nil { + t.Fatalf("failed to update node annotations in fake client: %v", err) + } + + callerNode := node.DeepCopy() + if tt.callerAnnotations != nil { + callerNode.Annotations = tt.callerAnnotations + } dev := InitMLUDevice(CambriconConfig{ ResourceCountName: MLUResourceCount, @@ -578,7 +596,7 @@ func Test_LockNode(t *testing.T) { ResourceCoreName: MLUResourceCores, }) - err := dev.LockNode(node, pod) + err = dev.LockNode(callerNode, pod) if (err != nil) != tt.wantErr { t.Errorf("LockNode() error = %v, wantErr %v", err, tt.wantErr) } @@ -592,6 +610,39 @@ func Test_LockNode(t *testing.T) { } }) } + + t.Run("patch conflict where concurrent caller acquires lock during retry", func(t *testing.T) { + node, pod, teardown, clientset := setupTest(t) + client.KubeClient = clientset + defer teardown() + + dev := InitMLUDevice(CambriconConfig{ + ResourceCountName: MLUResourceCount, + ResourceMemoryName: MLUResourceMemory, + ResourceCoreName: MLUResourceCores, + }) + + getAttempts := 0 + clientset.PrependReactor("patch", "nodes", func(action k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewConflict(corev1.Resource("nodes"), node.Name, fmt.Errorf("simulated conflict")) + }) + clientset.PrependReactor("get", "nodes", func(action k8stesting.Action) (bool, runtime.Object, error) { + getAttempts++ + if getAttempts > 1 { + // On retry after patch failure, node has been locked by concurrent caller + n := node.DeepCopy() + n.Annotations = map[string]string{ + DsmluLockTime: time.Now().Format(time.RFC3339), + } + return true, n, nil + } + return false, nil, nil + }) + + err := dev.LockNode(node, pod) + require.Error(t, err) + assert.Contains(t, err.Error(), "has been locked within 2 minutes") + }) } func Test_ReleaseNodeLock(t *testing.T) { diff --git a/pkg/device/nvidia/device.go b/pkg/device/nvidia/device.go index 0a598bb660..05f554fc02 100644 --- a/pkg/device/nvidia/device.go +++ b/pkg/device/nvidia/device.go @@ -524,15 +524,16 @@ func (dev *NvidiaGPUDevices) GenerateResourceRequests(ctr *corev1.Container) dev factor := max(int64(dev.config.MemoryFactor), 1) if !parsed || memnums < 0 || memnums > int64(math.MaxInt32)/factor { klog.ErrorS(nil, "nvidia memory request is not a plain integer within the int32 range; rejecting to avoid silent under-allocation", - "container", ctr.Name) - return device.ContainerDeviceRequest{} - } - if factor > 1 { - rawMemnums := memnums - memnums = memnums * factor - klog.V(4).Infof("Update memory request. before %d, after %d, factor %d", rawMemnums, memnums, factor) + "container", ctr.Name, "requested", mem.String()) + memnum = math.MaxInt32 + } else { + if factor > 1 { + rawMemnums := memnums + memnums = memnums * factor + klog.V(4).Infof("Update memory request. before %d, after %d, factor %d", rawMemnums, memnums, factor) + } + memnum = int(memnums) } - memnum = int(memnums) } mempnum := int32(101) mem, ok = ctr.Resources.Limits[resourceMemPercentage] diff --git a/pkg/device/nvidia/device_test.go b/pkg/device/nvidia/device_test.go index 5dd07ec751..18f437939f 100644 --- a/pkg/device/nvidia/device_test.go +++ b/pkg/device/nvidia/device_test.go @@ -19,6 +19,7 @@ package nvidia import ( "context" "errors" + "math" "strings" "testing" "time" @@ -30,6 +31,7 @@ import ( "k8s.io/client-go/kubernetes/fake" "github.com/Project-HAMi/HAMi/pkg/device" + "github.com/Project-HAMi/HAMi/pkg/device/common" "github.com/Project-HAMi/HAMi/pkg/util" "github.com/Project-HAMi/HAMi/pkg/util/client" "github.com/Project-HAMi/HAMi/pkg/util/nodelock" @@ -754,7 +756,7 @@ func TestDevices_Fit(t *testing.T) { config := NvidiaConfig{ ResourceCountName: "nvidia.com/gpu", ResourceMemoryName: "nvidia.com/gpumem", - ResourceCoreName: "nvidia.com/gpumem", + ResourceCoreName: "nvidia.com/gpucores", ResourceMemoryPercentageName: "nvidia.com/gpumem-percentage", } dev := InitNvidiaDevice(config) @@ -1227,7 +1229,7 @@ func TestFit_DeviceCordon(t *testing.T) { config := NvidiaConfig{ ResourceCountName: "nvidia.com/gpu", ResourceMemoryName: "nvidia.com/gpumem", - ResourceCoreName: "nvidia.com/gpumem", + ResourceCoreName: "nvidia.com/gpucores", ResourceMemoryPercentageName: "nvidia.com/gpumem-percentage", } dev := InitNvidiaDevice(config) @@ -1968,7 +1970,13 @@ func TestGenerateResourceRequests(t *testing.T) { }, }, }, - want: device.ContainerDeviceRequest{}, + want: device.ContainerDeviceRequest{ + Nums: 1, + Type: NvidiaGPUDevice, + Memreq: math.MaxInt32, + MemPercentagereq: 101, + Coresreq: 0, + }, }, { name: "decimal-form memory request is rejected, not treated as zero", @@ -1980,7 +1988,13 @@ func TestGenerateResourceRequests(t *testing.T) { }, }, }, - want: device.ContainerDeviceRequest{}, + want: device.ContainerDeviceRequest{ + Nums: 1, + Type: NvidiaGPUDevice, + Memreq: math.MaxInt32, + MemPercentagereq: 101, + Coresreq: 0, + }, }, } @@ -2753,15 +2767,21 @@ func TestFit_MigPercentageRequestRejectsUndersizedTemplate(t *testing.T) { } nv := InitNvidiaDevice(config) - // The only MIG template offers 1024MiB slots, but the pod requests 4096MiB (50% of 8192MiB) via MemPercentagereq. + // The only MIG profile offers 1024MiB slots, but the pod requests 4096MiB (50% of 8192MiB) via MemPercentagereq. devices := []*device.DeviceUsage{ { ID: "dev-0", Index: 0, Used: 0, Count: 1, Totalmem: 8192, Totalcore: 100, Type: NvidiaGPUDevice, Health: true, Mode: MigMode, - MigTemplate: []device.Geometry{ + MigProfiles: []device.MigProfile{ { - {Name: "1g.5gb", Memory: 1024, Core: 14, Count: 1}, + Name: "1g.5gb", + MemoryMB: 1024, + Core: 14, + SliceCount: 1, + Placements: []device.MigPlacement{ + {Start: 0, Size: 1}, + }, }, }, }, @@ -3293,3 +3313,42 @@ func TestDistinctCardCandidates(t *testing.T) { }) } } + +func Test_Fit_InvalidMemoryRejected(t *testing.T) { + config := NvidiaConfig{ + ResourceCountName: "nvidia.com/gpu", + ResourceMemoryName: "nvidia.com/gpumem", + ResourceCoreName: "nvidia.com/gpucores", + ResourceMemoryPercentageName: "nvidia.com/gpumem-percentage", + } + dev := InitNvidiaDevice(config) + + devices := []*device.DeviceUsage{ + { + ID: "gpu-0", + Type: NvidiaGPUDevice, + Totalmem: 16384, + Totalcore: 100, + Count: 100, + Health: true, + }, + } + + pod := &corev1.Pod{} + + // Invalid request with Memreq: math.MaxInt32 (generated from invalid memory quantity) + req := dev.GenerateResourceRequests(&corev1.Container{ + Resources: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + "nvidia.com/gpu": *resource.NewQuantity(1, resource.BinarySI), + "nvidia.com/gpumem": resource.MustParse("16Gi"), // overflows int32 + }, + }, + }) + assert.Equal(t, int32(1), req.Nums) + assert.Equal(t, int32(math.MaxInt32), req.Memreq) + + fit, _, reason := dev.Fit(devices, req, pod, &device.NodeInfo{}, &device.PodDevices{}) + assert.Equal(t, fit, false) + assert.Equal(t, strings.Contains(reason, common.CardInsufficientMemory), true) +}