diff --git a/README.md b/README.md index b024359..62e4ccc 100644 --- a/README.md +++ b/README.md @@ -47,16 +47,16 @@ The mock **derives the registered resources from the annotation, not from the co - **Number of fake cards = the number of entries in the annotation array** (not the count value). - Registered `...-memory` = **sum of `devmem`** over all entries. - Registered `...-cores` / `...-core` = **sum of `devcore`** over all entries. -- The **count extended resource is only a health gate**: its value just needs to be `> 0`. It does **not** affect the registered memory/cores. By convention it is set to `cards x splits-per-card` (e.g. Ascend `2 x VDeviceCount(4) = 8`), but `1` would work equally well for the memory/cores to appear. +- The **count extended resource is only a health gate**: its value just needs to be `> 0`. It does **not** affect the registered memory/cores. For a production-shaped scheduling test, set it to `cards x splits-per-card` (for example, one AMD card with the default split count advertises `10`), even though `1` is enough for the mock memory/core reducer to appear. Annotation entry fields: | field | meaning | | :-- | :-- | | `id` | unique device UUID (any string) | -| `devmem` | per-card memory in MB -- **summed** into `...-memory` | -| `devcore` | per-card cores. **NVIDIA/Hygon:** summed into `...-cores` (NVIDIA: percentage, 100 = a whole card). **Ascend:** ignored -- `huawei.com/-core` is percentage-based, registered as **100 per card**. | -| `count` | per-card split count (informational for the mock) | +| `devmem` | per-card memory in MiB -- **summed** into `...-memory` | +| `devcore` | per-card cores. **NVIDIA/Hygon:** summed into `...-cores` (NVIDIA: percentage, 100 = a whole card). **AMD:** physical CU count used by HAMi when converting percentage requests, but the mock registers **100 per healthy card**. **Ascend:** ignored -- `huawei.com/-core` is percentage-based, registered as **100 per card**. | +| `count` | per-card split/concurrency limit used by HAMi Scheduler; the mock memory/core reducer does not sum it | | `type` | device model string | | `health` | must be `true` to be counted | | `index` | card index `0,1,2,...` (`0` may be omitted) | @@ -85,6 +85,42 @@ kubectl get node -o json | jq '.status.allocatable|with_entries(select(.k # expect: nvidia.com/gpu=10, nvidia.com/gpumem=81920, nvidia.com/gpucores=100, nvidia.com/gpumem-percentage=100 ``` +### AMD GPU + +- config block: `amd:` | annotation: `hami.io/node-amd-register` (JSON) | count: `amd.com/gpu` +- mock registers: `amd.com/gpumem`, `amd.com/gpucores` + +The AMD config must declare all three distinct resource names under the same vendor namespace: + +```yaml +amd: + resourceCountName: amd.com/gpu + resourceMemoryName: amd.com/gpumem + resourceCoreName: amd.com/gpucores +``` + +```bash +# (2) external count resource: one card x the AMD plugin's default split count (10) +kubectl patch node --subresource=status --type=json \ + -p '[{"op":"add","path":"/status/capacity/amd.com~1gpu","value":"10"}]' +# (1) transport-safe fake inventory for a Scheduler smoke test. devmem is +# intentionally reduced to 32 GiB; see the MI300X limitation below. +kubectl annotate node \ + 'hami.io/node-amd-register=[{"id":"AMD-MOCK-0","count":10,"devmem":32768,"devcore":304,"type":"AMD-MOCK-32G","health":true,"numa":0}]' +# verify (~30s later) +kubectl get node -o json | jq '.status.allocatable|with_entries(select(.key|test("amd.com")))' +# expect: amd.com/gpu=10, amd.com/gpumem=32768, amd.com/gpucores=100 +``` + +HAMi expresses AMD core requests as percentages. Each healthy physical card therefore contributes `100` to `amd.com/gpucores`; the annotation's `devcore` remains the real CU count that HAMi uses to convert the requested percentage into CUs. Unhealthy annotation entries contribute neither memory nor core capacity. + +The released AMD device plugin reports one MI300X VF with `count: 10`, about `196288` MiB of memory, and `devcore: 304`. The current generic mock expands every MiB of scalar capacity into one Device Plugin API object; a full MI300X response is therefore about 6.76 MiB and exceeds kubelet's default 4 MiB gRPC receive limit. + +> [!IMPORTANT] +> This is a mock-only transport limitation. The released AMD device plugin registers only ten logical `amd.com/gpu` splits per physical card and carries the full memory/CU values in the Node annotation; it does not send 196288 memory Device objects to kubelet. Do not use this PR to claim full-capacity MI300X mock coverage. + +HAMi's AMD configuration does not yet expose an end-to-end `memoryFactor`, so do not use a full MI300X memory value as a working mock example. Supporting that capacity without changing resource semantics requires a matching factor in both HAMi Scheduler and this mock. The reduced 32 GiB inventory above verifies only annotation decoding, resource registration, and Scheduler Filter/Bind behavior. + ### Ascend NPU (e.g. 910B4) - config block: `vnpus.configs` (entry for `910B4`) | annotation: `hami.io/node-register-Ascend910B4` (JSON) | count: `huawei.com/Ascend910B4` @@ -153,10 +189,11 @@ The new nested format is tried first; if that fails it falls back to the legacy | Devices | Mocking Resources | | :--- | :---- | | Nvidia GPU | `nvidia.com/gpumem`, `nvidia.com/gpumem-percentage`, `nvidia.com/gpucores` | +| AMD GPU | `amd.com/gpumem`, `amd.com/gpucores` | | Hygon DCU | `hygon.com/dcumem`, `hygon.com/dcucores` (when `resourceCoreName` is set) | | Ascend | `huawei.com/Ascend{chip}-memory`, `huawei.com/Ascend{chip}-core` (when `resourceCoreName` is set **and** the node is in `hami-vnpu-core` mode) | -**Note:** If the counted memory is too large (e.g. > 120GB) it may display as 0. Set `memoryFactor` in the `hami-scheduler-device` ConfigMap (default 1). +**Note:** If counted memory is too large (e.g. > 120GB), the Device Plugin response may exceed kubelet's receive limit and the resource can display as `0`. Device families whose HAMi configuration exposes `memoryFactor` can reduce the advertised scalar count with the same factor. AMD does not currently have that end-to-end setting; use the reduced smoke-test inventory above until the Scheduler and mock contracts are extended together. ## Build diff --git a/internal/pkg/api/device/amd/device.go b/internal/pkg/api/device/amd/device.go index 44028a1..bd4e9f8 100644 --- a/internal/pkg/api/device/amd/device.go +++ b/internal/pkg/api/device/amd/device.go @@ -17,72 +17,134 @@ limitations under the License. package amd import ( + "errors" "fmt" + "strings" "github.com/HAMi/mock-device-plugin/internal/pkg/api/device" + "github.com/HAMi/mock-device-plugin/internal/pkg/mock" + "github.com/kubevirt/device-plugin-manager/pkg/dpm" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" + utilvalidation "k8s.io/apimachinery/pkg/util/validation" "k8s.io/klog/v2" ) const ( - AMDDevice = "AMDGPU" - AMDCommonWord = "AMDGPU" - AMDDeviceSelection = "amd.com/gpu-index" - AMDUseUUID = "amd.com/use-gpu-uuid" - AMDNoUseUUID = "amd.com/nouse-gpu-uuid" - AMDAssignedNode = "amd.com/predicate-node" - Mi300xMemory = 192000 + AMDDevice = "AMD" + AMDCommonWord = "AMD" + RegisterAnnos = "hami.io/node-amd-register" ) type AMDConfig struct { ResourceCountName string `yaml:"resourceCountName"` ResourceMemoryName string `yaml:"resourceMemoryName"` + ResourceCoreName string `yaml:"resourceCoreName"` } type AMDDevices struct { - resourceCountName string - resourceMemoryName string + config AMDConfig } -func InitAMDGPUDevice(config AMDConfig) *AMDDevices { - return &AMDDevices{ - resourceCountName: config.ResourceCountName, - resourceMemoryName: config.ResourceMemoryName, +func InitAMDGPUDevice(config AMDConfig) (*AMDDevices, error) { + if config.ResourceCountName == "" && config.ResourceMemoryName == "" && config.ResourceCoreName == "" { + return nil, nil } + resourceNames := []string{ + config.ResourceCountName, + config.ResourceMemoryName, + config.ResourceCoreName, + } + for _, resourceName := range resourceNames { + if resourceName == "" { + return nil, errors.New("amd resource count, memory, and core names are required") + } + vendor, resource, qualified := strings.Cut(resourceName, "/") + if !qualified || vendor == "" || resource == "" || len(utilvalidation.IsQualifiedName(resourceName)) > 0 { + return nil, fmt.Errorf("amd resource name %q must be a qualified extended resource name", resourceName) + } + } + if config.ResourceCountName == config.ResourceMemoryName || + config.ResourceCountName == config.ResourceCoreName || + config.ResourceMemoryName == config.ResourceCoreName { + return nil, errors.New("amd resource count, memory, and core names must be distinct") + } + vendor := device.GetVendorName(config.ResourceCountName) + if device.GetVendorName(config.ResourceMemoryName) != vendor || + device.GetVendorName(config.ResourceCoreName) != vendor { + return nil, errors.New("amd resource count, memory, and core names must use the same vendor namespace") + } + + return &AMDDevices{config: config}, nil } func (dev *AMDDevices) CommonWord() string { return AMDCommonWord } -func (dev *AMDDevices) GetNodeDevices(n corev1.Node) ([]*device.DeviceInfo, error) { - nodedevices := []*device.DeviceInfo{} - i := 0 - counts, ok := n.Status.Capacity.Name(corev1.ResourceName(dev.resourceCountName), resource.DecimalSI).AsInt64() - if !ok || counts == 0 { - return []*device.DeviceInfo{}, fmt.Errorf("device not found %s", dev.resourceCountName) +func (dev *AMDDevices) GetNodeDevices(n *corev1.Node) ([]*device.DeviceInfo, error) { + devEncoded, ok := n.Annotations[RegisterAnnos] + if !ok { + return []*device.DeviceInfo{}, errors.New("annos not found " + RegisterAnnos) + } + nodeDevices, err := device.UnMarshalNodeDevices(devEncoded) + if err != nil { + klog.ErrorS(err, "failed to decode node devices", "node", n.Name, "device annotation", devEncoded) + return []*device.DeviceInfo{}, err + } + if len(nodeDevices) == 0 { + return []*device.DeviceInfo{}, fmt.Errorf("no amd gpu found on node %s", n.Name) + } + for idx, nodeDevice := range nodeDevices { + if nodeDevice == nil { + return []*device.DeviceInfo{}, fmt.Errorf("amd device annotation contains null entry at index %d", idx) + } + if nodeDevice.Count < 0 || nodeDevice.Devmem < 0 || nodeDevice.Devcore < 0 { + return []*device.DeviceInfo{}, fmt.Errorf("amd device annotation contains negative capacity at index %d", idx) + } + nodeDevice.DeviceVendor = dev.CommonWord() + } + return nodeDevices, nil +} + +func (dev *AMDDevices) GetResource(n *corev1.Node) map[string]int { + memoryResourceName := device.GetResourceName(dev.config.ResourceMemoryName) + coreResourceName := device.GetResourceName(dev.config.ResourceCoreName) + resourceMap := map[string]int{ + memoryResourceName: 0, + coreResourceName: 0, + } + if !device.CheckHealthy(n, dev.config.ResourceCountName) { + klog.Infof("device %s is unhealthy on this node", dev.CommonWord()) + return resourceMap } - for int64(i) < counts { - nodedevices = append(nodedevices, &device.DeviceInfo{ - Index: uint(i), - ID: n.Name + "-" + AMDDevice + "-" + fmt.Sprint(i), - Count: 1, - Devmem: Mi300xMemory, - Devcore: 100, - Type: AMDDevice, - Numa: 0, - Health: true, - CustomInfo: make(map[string]any), - DeviceVendor: AMDCommonWord, - }) - i++ + + nodeDevices, err := dev.GetNodeDevices(n) + if err != nil { + klog.Infof("no device %s on this node", dev.CommonWord()) + return resourceMap } - i = 0 - for i < len(nodedevices) { - klog.V(4).Infoln("Registered AMD nodedevices:", nodedevices[i]) - i++ + for _, nodeDevice := range nodeDevices { + if !nodeDevice.Health { + continue + } + resourceMap[memoryResourceName] += int(nodeDevice.Devmem) + // HAMi exposes AMD core requests as percentages. The annotation's + // Devcore remains the physical CU count used by the scheduler to turn + // a percentage request into CUs; every healthy card contributes 100. + resourceMap[coreResourceName] += 100 } - return nodedevices, nil -} \ No newline at end of file + klog.InfoS("Add resources", + memoryResourceName, resourceMap[memoryResourceName], + coreResourceName, resourceMap[coreResourceName], + ) + return resourceMap +} + +func (dev *AMDDevices) RunManager() { + lmock := mock.NewMockLister(device.GetVendorName(dev.config.ResourceMemoryName)) + go device.Register(lmock, dev) + mockManager := dpm.NewManager(lmock) + klog.Infof("Running mocking dp: %s", dev.CommonWord()) + mockManager.Run() +} diff --git a/internal/pkg/api/device/amd/device_test.go b/internal/pkg/api/device/amd/device_test.go new file mode 100644 index 0000000..40a58ec --- /dev/null +++ b/internal/pkg/api/device/amd/device_test.go @@ -0,0 +1,265 @@ +/* +Copyright 2025 The HAMi 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 amd + +import ( + "reflect" + "testing" + + "github.com/HAMi/mock-device-plugin/internal/pkg/api/device" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +var _ device.Devices = (*AMDDevices)(nil) + +func validAMDConfig() AMDConfig { + return AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "amd.com/gpumem", + ResourceCoreName: "amd.com/gpucores", + } +} + +func mustInitAMD(t *testing.T, config AMDConfig) *AMDDevices { + t.Helper() + dev, err := InitAMDGPUDevice(config) + if err != nil { + t.Fatalf("InitAMDGPUDevice() error = %v", err) + } + if dev == nil { + t.Fatal("InitAMDGPUDevice() returned nil") + } + return dev +} + +func TestInitAMDGPUDevice(t *testing.T) { + tests := []struct { + name string + config AMDConfig + wantNil bool + wantError bool + }{ + {name: "disabled when config is empty", wantNil: true}, + {name: "valid", config: validAMDConfig()}, + { + name: "missing core resource", + config: AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "amd.com/gpumem", + }, + wantError: true, + }, + { + name: "mixed vendor namespaces", + config: AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "example.com/gpumem", + ResourceCoreName: "amd.com/gpucores", + }, + wantError: true, + }, + { + name: "unqualified resource name", + config: AMDConfig{ + ResourceCountName: "amd.com", + ResourceMemoryName: "amd.com/gpumem", + ResourceCoreName: "amd.com/gpucores", + }, + wantError: true, + }, + { + name: "invalid qualified resource name", + config: AMDConfig{ + ResourceCountName: "AMD.COM/gpu", + ResourceMemoryName: "AMD.COM/gpumem", + ResourceCoreName: "AMD.COM/gpucores", + }, + wantError: true, + }, + { + name: "duplicate resource names", + config: AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "amd.com/gpu", + ResourceCoreName: "amd.com/gpucores", + }, + wantError: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + dev, err := InitAMDGPUDevice(test.config) + if (err != nil) != test.wantError { + t.Fatalf("InitAMDGPUDevice() error = %v, wantError %v", err, test.wantError) + } + if test.wantError { + return + } + if (dev == nil) != test.wantNil { + t.Fatalf("InitAMDGPUDevice() nil = %v, want %v", dev == nil, test.wantNil) + } + if dev != nil && dev.CommonWord() != AMDCommonWord { + t.Fatalf("CommonWord() = %q, want %q", dev.CommonWord(), AMDCommonWord) + } + }) + } +} + +func TestAMDDevicesGetNodeDevices(t *testing.T) { + dev := mustInitAMD(t, validAMDConfig()) + tests := []struct { + name string + annotations map[string]string + wantError bool + }{ + { + name: "valid", + annotations: map[string]string{ + RegisterAnnos: `[{"id":"AMD-MOCK-0","count":10,"devmem":196288,"devcore":304,"type":"AMD Instinct MI300X VF","health":true}]`, + }, + }, + {name: "missing annotation", wantError: true}, + {name: "malformed annotation", annotations: map[string]string{RegisterAnnos: `{`}, wantError: true}, + {name: "empty annotation", annotations: map[string]string{RegisterAnnos: `[]`}, wantError: true}, + {name: "null entry", annotations: map[string]string{RegisterAnnos: `[null]`}, wantError: true}, + {name: "negative count", annotations: map[string]string{RegisterAnnos: `[{"count":-1}]`}, wantError: true}, + {name: "negative memory", annotations: map[string]string{RegisterAnnos: `[{"devmem":-1}]`}, wantError: true}, + {name: "negative core", annotations: map[string]string{RegisterAnnos: `[{"devcore":-1}]`}, wantError: true}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node-1", Annotations: test.annotations}} + got, err := dev.GetNodeDevices(node) + if (err != nil) != test.wantError { + t.Fatalf("GetNodeDevices() error = %v, wantError %v", err, test.wantError) + } + if test.wantError { + return + } + if len(got) != 1 { + t.Fatalf("GetNodeDevices() returned %d devices, want 1", len(got)) + } + if got[0].DeviceVendor != AMDCommonWord { + t.Fatalf("DeviceVendor = %q, want %q", got[0].DeviceVendor, AMDCommonWord) + } + if got[0].Count != 10 || got[0].Devmem != 196288 || got[0].Devcore != 304 { + t.Fatalf("decoded AMD capacity = count %d, memory %d, cores %d; want 10, 196288, 304", got[0].Count, got[0].Devmem, got[0].Devcore) + } + }) + } +} + +func TestAMDDevicesGetResource(t *testing.T) { + config := validAMDConfig() + dev := mustInitAMD(t, config) + annotation := `[` + + `{"id":"AMD-MOCK-0","count":10,"devmem":196608,"devcore":304,"type":"AMD-MI300X","health":true},` + + `{"id":"AMD-MOCK-1","count":10,"devmem":128000,"devcore":120,"type":"AMD-MI250","health":true},` + + `{"id":"AMD-MOCK-2","count":10,"devmem":64000,"devcore":64,"type":"AMD-MOCK","health":false}` + + `]` + + tests := []struct { + name string + capacity corev1.ResourceList + annotation string + wantMemory int + wantCore int + }{ + { + name: "healthy cards contribute memory and one hundred core units each", + capacity: corev1.ResourceList{ + corev1.ResourceName(config.ResourceCountName): resource.MustParse("20"), + }, + annotation: annotation, + wantMemory: 324608, + wantCore: 200, + }, + { + name: "missing external count gate", + annotation: annotation, + }, + { + name: "zero external count gate", + capacity: corev1.ResourceList{ + corev1.ResourceName(config.ResourceCountName): resource.MustParse("0"), + }, + annotation: annotation, + }, + { + name: "malformed annotation fails closed", + capacity: corev1.ResourceList{ + corev1.ResourceName(config.ResourceCountName): resource.MustParse("1"), + }, + annotation: `{`, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + node := &corev1.Node{ + ObjectMeta: metav1.ObjectMeta{ + Name: "node-1", + Annotations: map[string]string{RegisterAnnos: test.annotation}, + }, + Status: corev1.NodeStatus{Capacity: test.capacity}, + } + got := dev.GetResource(node) + if got["gpumem"] != test.wantMemory { + t.Fatalf("gpumem = %d, want %d", got["gpumem"], test.wantMemory) + } + if got["gpucores"] != test.wantCore { + t.Fatalf("gpucores = %d, want %d", got["gpucores"], test.wantCore) + } + if len(got) != 2 { + t.Fatalf("GetResource() returned %d resources, want 2", len(got)) + } + }) + } +} + +func TestAMDDevicesKeepConfigPerInstance(t *testing.T) { + first := mustInitAMD(t, validAMDConfig()) + second := mustInitAMD(t, AMDConfig{ + ResourceCountName: "example.com/cards", + ResourceMemoryName: "example.com/vram", + ResourceCoreName: "example.com/vcores", + }) + node := &corev1.Node{ + ObjectMeta: metav1.ObjectMeta{ + Name: "node-1", + Annotations: map[string]string{ + RegisterAnnos: `[{"id":"AMD-MOCK-0","count":10,"devmem":1024,"devcore":64,"health":true}]`, + }, + }, + Status: corev1.NodeStatus{Capacity: corev1.ResourceList{ + "amd.com/gpu": resource.MustParse("10"), + "example.com/cards": resource.MustParse("10"), + }}, + } + + if got, want := first.GetResource(node), map[string]int{"gpumem": 1024, "gpucores": 100}; !reflect.DeepEqual(got, want) { + t.Fatalf("first GetResource() = %v", got) + } + if got, want := second.GetResource(node), map[string]int{"vram": 1024, "vcores": 100}; !reflect.DeepEqual(got, want) { + t.Fatalf("second GetResource() = %v", got) + } +} diff --git a/internal/pkg/config/amd_test.go b/internal/pkg/config/amd_test.go new file mode 100644 index 0000000..2a341d6 --- /dev/null +++ b/internal/pkg/config/amd_test.go @@ -0,0 +1,90 @@ +/* +Copyright 2025 The HAMi 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 config + +import ( + "testing" + + "github.com/HAMi/mock-device-plugin/internal/pkg/api/device" + "github.com/HAMi/mock-device-plugin/internal/pkg/api/device/amd" + "github.com/HAMi/mock-device-plugin/internal/pkg/api/device/ascend" + "github.com/HAMi/mock-device-plugin/internal/pkg/api/device/nvidia" +) + +func TestInitDevicesWithAMDConfig(t *testing.T) { + err := InitDevicesWithConfig(&Config{AMDGPUConfig: amd.AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "amd.com/gpumem", + ResourceCoreName: "amd.com/gpucores", + }}) + if err != nil { + t.Fatalf("InitDevicesWithConfig() error = %v", err) + } + if _, ok := device.DevicesMap[amd.AMDCommonWord]; !ok { + t.Fatalf("AMD device missing from DevicesMap: %v", device.DevicesMap) + } +} + +func TestInitDevicesWithoutAMDConfig(t *testing.T) { + if err := InitDevicesWithConfig(&Config{}); err != nil { + t.Fatalf("InitDevicesWithConfig() error = %v", err) + } + if _, ok := device.DevicesMap[amd.AMDCommonWord]; ok { + t.Fatalf("disabled AMD device unexpectedly present in DevicesMap: %v", device.DevicesMap) + } +} + +func TestInitDevicesRejectsInvalidAMDConfig(t *testing.T) { + err := InitDevicesWithConfig(&Config{AMDGPUConfig: amd.AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "other.example/gpumem", + ResourceCoreName: "amd.com/gpucores", + }}) + if err == nil { + t.Fatal("InitDevicesWithConfig() error = nil, want invalid AMD resource namespace error") + } +} + +func TestInitDevicesRejectsAMDCommonWordCollisionAtomically(t *testing.T) { + if err := InitDevicesWithConfig(&Config{}); err != nil { + t.Fatalf("InitDevicesWithConfig() setup error = %v", err) + } + previousNvidia := device.DevicesMap[nvidia.NvidiaGPUDevice] + previousLen := len(device.DevicesMap) + + err := InitDevicesWithConfig(&Config{ + AMDGPUConfig: amd.AMDConfig{ + ResourceCountName: "amd.com/gpu", + ResourceMemoryName: "amd.com/gpumem", + ResourceCoreName: "amd.com/gpucores", + }, + VNPUs: ascend.VNPUs{Configs: []ascend.VNPUConfig{{ + CommonWord: amd.AMDCommonWord, + ResourceName: "huawei.com/amd", + ResourceMemoryName: "huawei.com/amd-memory", + }}}, + }) + if err == nil { + t.Fatal("InitDevicesWithConfig() error = nil, want duplicate common word error") + } + if len(device.DevicesMap) != previousLen || device.DevicesMap[nvidia.NvidiaGPUDevice] != previousNvidia { + t.Fatalf("failed initialization changed DevicesMap: %v", device.DevicesMap) + } + if _, ok := device.DevicesMap[amd.AMDCommonWord]; ok { + t.Fatalf("failed initialization installed AMD device: %v", device.DevicesMap) + } +} diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 9cbd2a4..b972059 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -18,6 +18,7 @@ package config import ( "flag" + "fmt" "os" "gopkg.in/yaml.v2" @@ -71,40 +72,55 @@ func LoadConfig(path string) (*Config, error) { } func InitDevicesWithConfig(config *Config) error { - device.DevicesMap = make(map[string]device.Devices) - /*amdDevice := amd.InitAMDDevice(config.AMDGPUConfig) + devicesMap := make(map[string]device.Devices) + amdDevice, err := amd.InitAMDGPUDevice(config.AMDGPUConfig) + if err != nil { + return err + } if amdDevice != nil { - device.DevicesMap[amdDevice.CommonWord()] = amdDevice - }*/ + devicesMap[amdDevice.CommonWord()] = amdDevice + } + addExistingDevice := func(dev device.Devices) error { + commonWord := dev.CommonWord() + if amdDevice != nil && commonWord == amdDevice.CommonWord() { + return fmt.Errorf("device common word %q conflicts with the AMD device config", commonWord) + } + devicesMap[commonWord] = dev + return nil + } + for _, dev := range ascend.InitDevices(config.VNPUs) { commonWord := dev.CommonWord() - device.DevicesMap[commonWord] = dev + if err := addExistingDevice(dev); err != nil { + return err + } klog.Infof("Ascend device %s initialized", commonWord) } /*awsNeuronDevice := awsneuron.InitAWSNeuronDevice(config.AWSNeuronConfig) if awsNeuronDevice != nil { - device.DevicesMap[awsNeuronDevice.CommonWord()] = awsNeuronDevice + devicesMap[awsNeuronDevice.CommonWord()] = awsNeuronDevice } cambriconDevice := cambricon.InitMLUDevice(config.CambriconConfig) if cambriconDevice != nil { - device.DevicesMap[cambriconDevice.CommonWord()] = cambriconDevice + devicesMap[cambriconDevice.CommonWord()] = cambriconDevice } enflameDevice := enflame.InitEnflameVGCUDevice(config.EnflameConfig) if enflameDevice != nil { - device.DevicesMap[enflameDevice.CommonWord()] = enflameDevice + devicesMap[enflameDevice.CommonWord()] = enflameDevice } kunlunDevice := kunlun.InitKunlunVDevice(config.KunlunConfig) if kunlunDevice != nil { - device.DevicesMap[kunlunDevice.CommonWord()] = kunlunDevice + devicesMap[kunlunDevice.CommonWord()] = kunlunDevice }*/ hygonDevice := hygon.InitDCUDevice(config.HygonConfig) - if hygonDevice != nil { - device.DevicesMap[hygonDevice.CommonWord()] = hygonDevice + if err := addExistingDevice(hygonDevice); err != nil { + return err } nvidiaDevice := nvidia.InitNvidiaDevice(config.NvidiaConfig) - if nvidiaDevice != nil { - device.DevicesMap[nvidiaDevice.CommonWord()] = nvidiaDevice + if err := addExistingDevice(nvidiaDevice); err != nil { + return err } + device.DevicesMap = devicesMap return nil }